From 0389fa506c5c0464eb294349383bd075dd965232 Mon Sep 17 00:00:00 2001 From: Michael Gilardi <11632652+mgilardi@users.noreply.github.com> Date: Sun, 15 Nov 2026 23:22:53 -0700 Subject: [PATCH] Check packs that only joining players can download A private texture pack goes only to players joining the server, through Leaf Juice's joining-only gate (D219). Packmule's startup check isn't a player, so the gate would refuse it and the pack would be marked dead. A pack can now carry a check block: Packmule checks it at a loopback address with a token from a mode-600 file, and players keep the public address. The config is refused when the local address isn't loopback or the public prefix doesn't start the pack's url. The check fails on a linked, shared, missing or malformed token file, token requests never follow redirects, and the token is never logged. pack set keeps the block while the new address stays under the prefix. Tested with unit tests against a made-up gate (51 pass). Not yet run against Leaf Juice's own gate, which waits for its side (D220), or with bots. Co-Authored-By: Claude Opus 5.5 --- README.md | 18 +- build.gradle.kts | 2 +- docs/decisions.md | 5 + docs/releases/v0.4.0.md | 14 ++ docs/test-audit.md | 14 ++ .../java/com/extantape/packmule/Packmule.java | 9 +- .../extantape/packmule/check/CheckToken.java | 57 ++++++ .../extantape/packmule/check/LinkChecker.java | 31 +++- .../packmule/config/PackmuleConfig.java | 71 +++++++- src/main/resources/config.yml | 12 ++ .../packmule/check/GatedCheckTest.java | 171 ++++++++++++++++++ .../packmule/config/PackmuleConfigTest.java | 47 +++++ 12 files changed, 437 insertions(+), 14 deletions(-) create mode 100644 docs/releases/v0.4.0.md create mode 100644 src/main/java/com/extantape/packmule/check/CheckToken.java create mode 100644 src/test/java/com/extantape/packmule/check/GatedCheckTest.java diff --git a/README.md b/README.md index 5443034..a87f1e3 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,22 @@ With a hash file, Packmule also looks for `/.zip`. If that ad Leaf Juice serves its recipes at both kinds of address, but Packmule works with any host. +### Packs only your players can download + +Leaf Juice can serve a pack only to players joining the server: it checks the game's own request headers against the whitelist and the server log, and refuses everyone else. Packmule's startup check isn't a player, so a pack like that needs a `check` block: + +```yaml +packs: + private: + url: https://join.example.com/zz/TOKEN/0123456789abcdef0123456789abcdef01234567.zip + check: + public-prefix: https://join.example.com/zz/ + local-prefix: http://127.0.0.1:8766/ + token-file: ~/Library/Application Support/LeafJuice/pack-check/my-server.token +``` + +Packmule then checks the pack at the local address, sending the token from the file in an `X-Pack-Check-Token` header. Players still get `url`. Packmule refuses the config if `local-prefix` isn't on this machine (127.0.0.1, ::1 or localhost) or `public-prefix` isn't the start of `url`. It refuses the check if the token file is a link, belongs to another user, can be read by anyone else (it must be mode 600), or doesn't hold 64 hex characters. A token request never follows a redirect, and the token is never logged. `/packmule pack set` keeps the block when the new address is still under `public-prefix`. Your web server should strip `X-Pack-Check-Token` from outside requests. + ## Install 1. Put `Packmule-.jar` in `plugins/` and start the server once. @@ -102,7 +118,7 @@ The jar is `build/libs/Packmule-.jar`. A `v*` tag builds it and attache ## Tests -`./gradlew test` runs the unit tests: config parsing, the link checker against a local web server, and the pack diff. +`./gradlew test` runs the unit tests: config parsing, the link checker against a local web server, the check for gated packs against a made-up gate, and the pack diff. `test/` holds the bot tests. They start throwaway Paper servers on 127.0.0.1:25613 in a temp folder you choose, and serve made-up packs on 127.0.0.1:25614. Bots connect as 26.1 clients: directly on 26.1.2, and through ViaVersion and ViaBackwards on 26.2 and 26.3. They answer pack requests the way the client's pack manager does, and download and hash each pack. `test/waystation.mjs` walks a bot through a Waystation gate and back. diff --git a/build.gradle.kts b/build.gradle.kts index 6e5ea09..2743be1 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -4,7 +4,7 @@ plugins { } group = "com.extantape" -version = "0.3.0" +version = "0.4.0" java { toolchain.languageVersion.set(JavaLanguageVersion.of(25)) diff --git a/docs/decisions.md b/docs/decisions.md index f7d2118..f011c2e 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,3 +30,8 @@ Owner decisions that shape Butler, with the date each was made. Change these onl - **Name (2026-11-08, owner):** ResourcePackButler is renamed Packmule, one word in every place: repo, plugin name, jar, package and prose. Released as 0.2.0. Existing servers get their `plugins/ResourcePackButler/` folder copied on first start (never overwritten), and the old commands and permissions keep working for one release with a log warning. Pack IDs keep the old `resourcepackbutler:pack:` namespace for good, because clients see them. - **pack set for Leaf Juice (2026-11-14, D189):** each pack build is published at a new unguessable path on the join host, and Leaf Juice hands Packmule the new link through `/packmule pack set --json `, as the Leaf Juice App session proposed and Helm assigned (K644). It takes https only, with the SHA-1 as the file name. Packmule downloads the file and checks the SHA-1 before writing `config.yml` (comments kept) and reloading, and a failure keeps the old address. Released as 0.2.1, so the old ResourcePackButler names stay for this 0.2.x release as promised. - **Old names (2026-11-14, owner):** the ResourcePackButler commands, permissions, folder copy and pack ID namespace are gone; pack IDs are now packmule:pack:, so clients download each pack once more. + +## 2026-11-15 + +- **Packs only players can download (D219, D220):** a private texture pack goes only to players joining the server, through Leaf Juice's joining-only gate. Packmule's startup check isn't a player, so a pack can carry a `check` block: Packmule checks it at a loopback address with a token from a mode-600 file, and players keep the public address. Agreed with the Head of Software (Leaf Juice side: the token file lives in Leaf Juice's Application Support folder, and Leaf Juice refuses the token on any proxied request) and the Head of Infrastructure (Caddy strips the header). Packmule refuses non-loopback local addresses, linked or shared token files and redirects on token requests. Released as 0.4.0. + diff --git a/docs/releases/v0.4.0.md b/docs/releases/v0.4.0.md new file mode 100644 index 0000000..03d85be --- /dev/null +++ b/docs/releases/v0.4.0.md @@ -0,0 +1,14 @@ +Packmule can check packs that only your players can download. + +## Added + +- **A `check` block per pack** for packs behind a gate that admits only joining players, such as Leaf Juice's "Only players joining this server". Packmule checks the pack at a loopback address with a token read from a mode-600 file, and players still get the public address. See "Packs only your players can download" in the README. +- The config is refused if the local address isn't on this machine or the public prefix isn't the start of the pack's address. The check fails if the token file is a link, another user's, readable by others or malformed. Token requests never follow redirects, and the token is never logged. + +## Upgrading + +Replace the jar and restart. Configs without a `check` block work as before. + +## Tested + +Unit tests against a made-up gate on 127.0.0.1 (51 tests). Not yet run against Leaf Juice's own gate; that waits for its side (D220). diff --git a/docs/test-audit.md b/docs/test-audit.md index 1b6d874..a51d034 100644 --- a/docs/test-audit.md +++ b/docs/test-audit.md @@ -27,3 +27,17 @@ Each README promise and the test that holds it. "Bots" is `test/suite.mjs` on th **Skipped, with reasons:** - "No background polling": it's an absence of code (there's no scheduled check); a test watching for traffic over time would prove little more than reading `Packmule.java`, done at this audit. - How the prompt and kick messages read on screen, and how a real loading screen feels: real client only, listed under "What hasn't been tested". + +## 2026-11-15: gated packs (0.4.0) + +| Promise | Test | +| --- | --- | +| A gated pack is checked at the local address with the token, and players keep the public address | unit `checksAtTheLocalAddressWithTheTokenAndPlayersKeepThePublicOne` | +| Without a check block the gate refuses Packmule's check | unit `withoutTheCheckBlockTheGateRefusesTheCheck` | +| **The token never leaves this machine:** non-loopback, user-part, wrong-prefix and incomplete check blocks are config errors | unit `refusesACheckBlockThatCouldSendTheTokenAway`, `loopbackMeansThisMachineOnly` | +| **The token never follows a redirect** or goes to an address outside the public prefix | unit `theTokenNeverFollowsARedirect`, `addressesOutsideThePublicPrefixGoWithoutTheToken` | +| **Fail closed on the token file:** shared (not 600), linked, missing or malformed files fail the check, and the token isn't in the reason | unit `aTokenFileOthersCanReadIsRefusedAndNothingIsSent`, `aLinkedTokenFileIsRefused`, `aMissingOrMalformedTokenFileIsRefused`, `aWrongTokenIsDead` | +| The check block is read | unit `readsAGatedPacksCheckBlock` | + +**Gaps:** `/packmule pack set` keeping the block is a three-line lookup in `Packmule.gatedCheck`, covered by reading it; a bot test needs Leaf Juice's half (D220), so it runs with the refusal tests against the real gate. +**Skipped:** a file owned by another user, since a test can't create one without root; the owner comparison is one line next to the tested mode check. diff --git a/src/main/java/com/extantape/packmule/Packmule.java b/src/main/java/com/extantape/packmule/Packmule.java index c99f489..e5894e4 100644 --- a/src/main/java/com/extantape/packmule/Packmule.java +++ b/src/main/java/com/extantape/packmule/Packmule.java @@ -132,11 +132,18 @@ public List reload() { * /packmule reload. Any failure leaves config.yml and the pack as they were. {@code done} gets the outcome on the * main thread: null when it worked, or the refusal. */ + /** A gated pack keeps its check block when Leaf Juice hands it a new address, as long as the address stays under it. */ + private PackmuleConfig.Check gatedCheck(com.extantape.packmule.command.PackSet.Plan plan) { + PackSource old = config.packs().get(plan.pack()); + if (old == null || old.check() == null || !plan.url().startsWith(old.check().publicPrefix())) return null; + return old.check(); + } + public boolean setPack(com.extantape.packmule.command.PackSet.Plan plan, java.util.function.Consumer done) { if (setting) return false; setting = true; LinkChecker checker = new LinkChecker(Duration.ofSeconds(config.checkTimeoutSeconds())); - CompletableFuture.supplyAsync(() -> checker.check(new PackSource(plan.pack(), plan.url(), plan.sha1(), null), null), checks) + CompletableFuture.supplyAsync(() -> checker.check(new PackSource(plan.pack(), plan.url(), plan.sha1(), null, gatedCheck(plan)), null), checks) .whenComplete((outcome, error) -> { if (!isEnabled()) return; Bukkit.getScheduler().runTask(this, () -> { diff --git a/src/main/java/com/extantape/packmule/check/CheckToken.java b/src/main/java/com/extantape/packmule/check/CheckToken.java new file mode 100644 index 0000000..31655ef --- /dev/null +++ b/src/main/java/com/extantape/packmule/check/CheckToken.java @@ -0,0 +1,57 @@ +package com.extantape.packmule.check; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.util.EnumSet; +import java.util.Set; +import java.util.regex.Pattern; + +/** + * Reads the pack-check token for a gated pack (D219). The file must be a plain file, not a link, owned by the user + * the server runs as, readable by nobody else, and hold exactly 64 hex characters. Anything else is refused, so a + * gated pack fails its check instead of going out with a token someone else could have read or swapped. + * The token itself never appears in a message. + */ +final class CheckToken { + private static final Pattern TOKEN = Pattern.compile("[0-9a-f]{64}"); + private static final Set OWNER_ONLY = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE); + + private CheckToken() { + } + + static String read(String file) throws LinkChecker.CheckFailed { + String shown = "check token file " + file; + Path path; + try { + path = Path.of(file.startsWith("~/") ? System.getProperty("user.home") + file.substring(1) : file); + } catch (RuntimeException e) { + throw new LinkChecker.CheckFailed(shown + " isn't a valid path"); + } + try { + PosixFileAttributes a = Files.readAttributes(path, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!a.isRegularFile()) throw new LinkChecker.CheckFailed(shown + " isn't a plain file"); + if (!a.owner().getName().equals(System.getProperty("user.name"))) throw new LinkChecker.CheckFailed(shown + " belongs to another user"); + if (!OWNER_ONLY.containsAll(a.permissions())) throw new LinkChecker.CheckFailed(shown + " can be read by others; it must be mode 600"); + if (a.size() > 256) throw new LinkChecker.CheckFailed(shown + " doesn't hold a token"); + } catch (UnsupportedOperationException e) { + throw new LinkChecker.CheckFailed(shown + " can't be checked on this file system"); + } catch (java.nio.file.NoSuchFileException e) { + throw new LinkChecker.CheckFailed(shown + " doesn't exist"); + } catch (IOException e) { + throw new LinkChecker.CheckFailed(shown + " can't be read"); + } + String text; + try { + text = Files.readString(path, StandardCharsets.US_ASCII).strip(); + } catch (IOException | RuntimeException e) { + throw new LinkChecker.CheckFailed(shown + " can't be read"); + } + if (!TOKEN.matcher(text).matches()) throw new LinkChecker.CheckFailed(shown + " doesn't hold a token"); + return text; + } +} diff --git a/src/main/java/com/extantape/packmule/check/LinkChecker.java b/src/main/java/com/extantape/packmule/check/LinkChecker.java index d5bf45a..a1536af 100644 --- a/src/main/java/com/extantape/packmule/check/LinkChecker.java +++ b/src/main/java/com/extantape/packmule/check/LinkChecker.java @@ -1,6 +1,7 @@ package com.extantape.packmule.check; import com.extantape.packmule.config.PackmuleConfig; +import com.extantape.packmule.config.PackmuleConfig.Check; import com.extantape.packmule.config.PackmuleConfig.PackSource; import java.io.IOException; @@ -64,7 +65,7 @@ public Outcome check(PackSource source, String lastGood) { } else { String read; try { - read = readHashFile(source.sha1Url()); + read = readHashFile(source.sha1Url(), source.check()); } catch (CheckFailed e) { read = null; notes.add("Couldn't read its hash file " + source.sha1Url() + ": " + e.getMessage() + "."); @@ -88,7 +89,7 @@ public Outcome check(PackSource source, String lastGood) { for (int i = 0; i < candidates.size(); i++) { String url = candidates.get(i); try { - String got = downloadSha1(url); + String got = downloadSha1(url, source.check()); if (got.equals(sha1)) { boolean build = source.movingAddress() ? i == 0 : PackmuleConfig.sha1FromAddress(url) != null; if (source.movingAddress() && i > 0) { @@ -111,7 +112,11 @@ private static Outcome dead(PackSource source, String reason, List notes /** The first 40-hex word of the hash file, lowercased. sha1sum's "hash filename" form works too. */ String readHashFile(String url) throws CheckFailed { - byte[] body = fetch(url, MAX_HASH_FILE, null); + return readHashFile(url, null); + } + + String readHashFile(String url, Check check) throws CheckFailed { + byte[] body = fetch(url, MAX_HASH_FILE, null, check); String text = new String(body, StandardCharsets.UTF_8).trim(); String first = text.isEmpty() ? "" : text.split("\\s+", 2)[0].toLowerCase(Locale.ROOT); if (!PackmuleConfig.isSha1(first)) throw new CheckFailed("it doesn't hold a SHA-1"); @@ -119,30 +124,42 @@ String readHashFile(String url) throws CheckFailed { } String downloadSha1(String url) throws CheckFailed { + return downloadSha1(url, null); + } + + String downloadSha1(String url, Check check) throws CheckFailed { MessageDigest digest; try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } - fetch(url, MAX_BYTES, digest); + fetch(url, MAX_BYTES, digest, check); return HexFormat.of().formatHex(digest.digest()); } /** Downloads into the digest, or returns the body when there's no digest. */ - private byte[] fetch(String url, long limit, MessageDigest digest) throws CheckFailed { + private byte[] fetch(String url, long limit, MessageDigest digest, Check check) throws CheckFailed { String problem = PackmuleConfig.addressProblem(url); if (problem != null) throw new CheckFailed("bad address, because " + problem); + // A gated pack is checked on this machine, with the token. Anything not under the public prefix goes as usual. + String token = null; + if (check != null && url.startsWith(check.publicPrefix())) { + url = check.localPrefix() + url.substring(check.publicPrefix().length()); + token = CheckToken.read(check.tokenFile()); + } HttpURLConnection connection = null; long started = System.nanoTime(); try { connection = (HttpURLConnection) URI.create(url).toURL().openConnection(); connection.setConnectTimeout((int) timeout.toMillis()); connection.setReadTimeout((int) timeout.toMillis()); - connection.setInstanceFollowRedirects(true); + // The token must never follow a redirect somewhere else. + connection.setInstanceFollowRedirects(token == null); connection.setRequestProperty("User-Agent", "Packmule"); + if (token != null) connection.setRequestProperty(Check.HEADER, token); int code = connection.getResponseCode(); - if (code != 200) throw new CheckFailed("HTTP " + code); + if (code != 200) throw new CheckFailed("HTTP " + code + (token != null ? " from the local check address" : "")); var buffer = new java.io.ByteArrayOutputStream(); long total = 0; byte[] chunk = new byte[64 * 1024]; diff --git a/src/main/java/com/extantape/packmule/config/PackmuleConfig.java b/src/main/java/com/extantape/packmule/config/PackmuleConfig.java index 123bb7d..72cf038 100644 --- a/src/main/java/com/extantape/packmule/config/PackmuleConfig.java +++ b/src/main/java/com/extantape/packmule/config/PackmuleConfig.java @@ -27,12 +27,33 @@ public record PackmuleConfig( * Where a pack lives and how its hash is known. Exactly one of sha1 and sha1Url is set, except for a * malformed url, which has neither and is always reported dead. */ - public record PackSource(String name, String url, String sha1, String sha1Url) { + public record PackSource(String name, String url, String sha1, String sha1Url, Check check) { + public PackSource(String name, String url, String sha1, String sha1Url) { + this(name, url, sha1, sha1Url, null); + } + public boolean movingAddress() { return sha1Url != null; } } + /** + * For a pack behind a gate that only lets players in (D219): Packmule checks it at a loopback address instead, + * with a token read fresh from a file, so the token never leaves this machine. Addresses under + * {@code publicPrefix} are fetched at {@code localPrefix} plus the rest. Players still get the public address. + */ + public record Check(String publicPrefix, String localPrefix, String tokenFile) { + public static final String HEADER = "X-Pack-Check-Token"; + } + + /** True for a host name that can only mean this machine. */ + public static boolean isLoopback(String host) { + if (host == null) return false; + String h = host.toLowerCase(Locale.ROOT); + if (h.startsWith("[") && h.endsWith("]")) h = h.substring(1, h.length() - 1); + return h.equals("localhost") || h.equals("::1") || h.matches("127(\\.\\d{1,3}){3}"); + } + /** * What players see, in MiniMessage. {@code } in no-answer is the timeout. Defaults match config.yml; * a message left out of the config uses its default, so an old config still reads well. @@ -188,14 +209,56 @@ private static PackSource parsePack(String name, ConfigurationSection pack, List errors.add("Pack '" + name + "': sha1 doesn't match the hash in the url's file name."); return null; } - return new PackSource(name, url, sha1, null); + return withCheck(new PackSource(name, url, sha1, null), pack, errors); } - if (sha1Url != null) return new PackSource(name, url, null, sha1Url); // A bad one is reported by the check. - if (fromName != null) return new PackSource(name, url, fromName, null); + if (sha1Url != null) return withCheck(new PackSource(name, url, null, sha1Url), pack, errors); // A bad one is reported by the check. + if (fromName != null) return withCheck(new PackSource(name, url, fromName, null), pack, errors); errors.add("Pack '" + name + "' needs a hash: use a per-build url ending in .zip, or add sha1 or sha1-url."); return null; } + /** Adds the pack's check block, if it has one. Any problem in it is a config error, so a gated pack never half-works. */ + private static PackSource withCheck(PackSource source, ConfigurationSection pack, List errors) { + if (!pack.contains("check")) return source; + String name = source.name(); + ConfigurationSection c = pack.getConfigurationSection("check"); + if (c == null) { + errors.add("Pack '" + name + "': check must be a map with public-prefix, local-prefix and token-file."); + return null; + } + String pub = trimmed(c.getString("public-prefix")); + String local = trimmed(c.getString("local-prefix")); + String token = trimmed(c.getString("token-file")); + if (pub == null || local == null || token == null) { + errors.add("Pack '" + name + "': check needs public-prefix, local-prefix and token-file."); + return null; + } + if (!pub.endsWith("/") || !local.endsWith("/")) { + errors.add("Pack '" + name + "': check's public-prefix and local-prefix must each end in /."); + return null; + } + if (addressProblem(pub) != null || !source.url().startsWith(pub)) { + errors.add("Pack '" + name + "': check's public-prefix must be the start of the pack's url."); + return null; + } + URI localUri; + try { + localUri = URI.create(local); + } catch (IllegalArgumentException e) { + localUri = null; + } + if (localUri == null || addressProblem(local) != null || !isLoopback(localUri.getHost()) + || localUri.getRawQuery() != null || localUri.getRawFragment() != null || localUri.getRawUserInfo() != null) { + errors.add("Pack '" + name + "': check's local-prefix must be a plain http address on this machine, like http://127.0.0.1:8766/, so the token never leaves it."); + return null; + } + return new PackSource(name, source.url(), source.sha1(), source.sha1Url(), new Check(pub, local, token)); + } + + private static String trimmed(String value) { + return value == null || value.isBlank() ? null : value.trim(); + } + private static int intSetting(ConfigurationSection root, String key, int fallback, int min, int max, List errors) { if (!root.contains(key)) return fallback; Object value = root.get(key); diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 7e75c9d..848b338 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -28,6 +28,18 @@ packs: {} # main: # url: https://packs.example.com/TOKEN/0123456789abcdef0123456789abcdef01234567.zip +# +# A pack behind a gate that lets only joining players download it (Leaf Juice's "Only players joining this +# server") would fail Packmule's startup check, since that check isn't a player. Give it a check block: Packmule +# then checks it on this machine at local-prefix, sending the token from token-file, and players still get url. +# local-prefix must be on this machine (127.0.0.1, ::1 or localhost), so the token never leaves it. The token file +# must be a plain file, mode 600, owned by the user the server runs as. Leaf Juice shows its path on the hosting card. +# private: +# url: https://join.example.com/zz/TOKEN/0123456789abcdef0123456789abcdef01234567.zip +# check: +# public-prefix: https://join.example.com/zz/ +# local-prefix: http://127.0.0.1:8766/ +# token-file: ~/Library/Application Support/LeafJuice/pack-check/my-server.token worlds: {} # world: [main] diff --git a/src/test/java/com/extantape/packmule/check/GatedCheckTest.java b/src/test/java/com/extantape/packmule/check/GatedCheckTest.java new file mode 100644 index 0000000..f42d804 --- /dev/null +++ b/src/test/java/com/extantape/packmule/check/GatedCheckTest.java @@ -0,0 +1,171 @@ +package com.extantape.packmule.check; + +import com.extantape.packmule.config.PackmuleConfig.Check; +import com.extantape.packmule.config.PackmuleConfig.PackSource; +import com.sun.net.httpserver.HttpServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.MessageDigest; +import java.time.Duration; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * A pack behind a players-only gate (D219). A made-up gate on 127.0.0.1 admits only the right token, like Leaf + * Juice's; a second server stands in for the public address and must never see the token. + */ +class GatedCheckTest { + private static final String TOKEN = "ab".repeat(32); + private HttpServer gate, outside; + private String gateBase, outsideBase; + private final Map files = new ConcurrentHashMap<>(); + private final List outsideTokens = new CopyOnWriteArrayList<>(); + private final LinkChecker checker = new LinkChecker(Duration.ofSeconds(2)); + @TempDir Path dir; + + @BeforeEach + void start() throws Exception { + gate = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 8); + gate.createContext("/", exchange -> { + try (exchange) { + String path = exchange.getRequestURI().getPath(); + if (path.equals("/redirect")) { + exchange.getResponseHeaders().add("Location", outsideBase + "/caught"); + exchange.sendResponseHeaders(302, -1); + return; + } + byte[] body = files.get(path); + if (!TOKEN.equals(exchange.getRequestHeaders().getFirst("X-Pack-Check-Token")) || body == null) { + exchange.sendResponseHeaders(404, -1); + return; + } + exchange.sendResponseHeaders(200, body.length); + exchange.getResponseBody().write(body); + } + }); + gate.start(); + outside = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 8); + outside.createContext("/", exchange -> { + try (exchange) { + String t = exchange.getRequestHeaders().getFirst("X-Pack-Check-Token"); + if (t != null) outsideTokens.add(t); + exchange.sendResponseHeaders(404, -1); + } + }); + outside.start(); + gateBase = "http://127.0.0.1:" + gate.getAddress().getPort() + "/"; + outsideBase = "http://127.0.0.1:" + outside.getAddress().getPort(); + } + + @AfterEach + void stop() { + gate.stop(0); + outside.stop(0); + } + + private Path tokenFile(String text, String mode) throws Exception { + Path f = dir.resolve("server.token"); + Files.writeString(f, text, StandardCharsets.US_ASCII); + Files.setPosixFilePermissions(f, PosixFilePermissions.fromString(mode)); + return f; + } + + private String put(String name) throws Exception { + byte[] body = ("PK-fake-" + name).getBytes(StandardCharsets.UTF_8); + String h = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(body)); + files.put("/tok/" + h + ".zip", body); + return h; + } + + private PackSource gated(String h, Path token) { + String pub = "https://join.example.invalid/zz/"; + return new PackSource("zz", pub + "tok/" + h + ".zip", h, null, new Check(pub, gateBase, token.toString())); + } + + @Test + void checksAtTheLocalAddressWithTheTokenAndPlayersKeepThePublicOne() throws Exception { + String h = put("a"); + var outcome = checker.check(gated(h, tokenFile(TOKEN + "\n", "rw-------")), null); + assertTrue(outcome.live(), outcome.deadReason()); + assertEquals("https://join.example.invalid/zz/tok/" + h + ".zip", outcome.url()); + } + + @Test + void withoutTheCheckBlockTheGateRefusesTheCheck() throws Exception { + String h = put("a"); + var outcome = checker.check(new PackSource("zz", gateBase + "tok/" + h + ".zip", h, null), null); + assertFalse(outcome.live()); + } + + @Test + void aWrongTokenIsDead() throws Exception { + String h = put("a"); + var outcome = checker.check(gated(h, tokenFile("cd".repeat(32), "rw-------")), null); + assertFalse(outcome.live()); + assertFalse(outcome.deadReason().contains("cd".repeat(32))); + } + + @Test + void aTokenFileOthersCanReadIsRefusedAndNothingIsSent() throws Exception { + String h = put("a"); + var outcome = checker.check(gated(h, tokenFile(TOKEN, "rw-r--r--")), null); + assertFalse(outcome.live()); + assertTrue(outcome.deadReason().contains("mode 600"), outcome.deadReason()); + assertFalse(outcome.deadReason().contains(TOKEN)); + } + + @Test + void aMissingOrMalformedTokenFileIsRefused() throws Exception { + String h = put("a"); + var missing = checker.check(gated(h, dir.resolve("nope.token")), null); + assertFalse(missing.live()); + assertTrue(missing.deadReason().contains("doesn't exist"), missing.deadReason()); + var shortToken = checker.check(gated(h, tokenFile("abc", "rw-------")), null); + assertFalse(shortToken.live()); + assertTrue(shortToken.deadReason().contains("doesn't hold a token"), shortToken.deadReason()); + } + + @Test + void aLinkedTokenFileIsRefused() throws Exception { + String h = put("a"); + Path real = tokenFile(TOKEN, "rw-------"); + Path link = dir.resolve("link.token"); + Files.createSymbolicLink(link, real); + var outcome = checker.check(gated(h, link), null); + assertFalse(outcome.live()); + assertTrue(outcome.deadReason().contains("isn't a plain file"), outcome.deadReason()); + } + + @Test + void theTokenNeverFollowsARedirect() throws Exception { + Path token = tokenFile(TOKEN, "rw-------"); + String pub = "https://join.example.invalid/zz/"; + var source = new PackSource("zz", pub + "redirect", "e".repeat(40), null, new Check(pub, gateBase, token.toString())); + var outcome = checker.check(source, null); + assertFalse(outcome.live()); + assertTrue(outsideTokens.isEmpty(), "the token reached another address"); + } + + @Test + void addressesOutsideThePublicPrefixGoWithoutTheToken() throws Exception { + Path token = tokenFile(TOKEN, "rw-------"); + String h = "f".repeat(40); + var source = new PackSource("zz", outsideBase + "/other/" + h + ".zip", h, null, + new Check("https://join.example.invalid/zz/", gateBase, token.toString())); + checker.check(source, null); + assertTrue(outsideTokens.isEmpty(), "the token went to an address outside the public prefix"); + } +} diff --git a/src/test/java/com/extantape/packmule/config/PackmuleConfigTest.java b/src/test/java/com/extantape/packmule/config/PackmuleConfigTest.java index 2f0c250..c88df64 100644 --- a/src/test/java/com/extantape/packmule/config/PackmuleConfigTest.java +++ b/src/test/java/com/extantape/packmule/config/PackmuleConfigTest.java @@ -100,4 +100,51 @@ void leftOutMessagesUseTheirDefaults() throws Exception { assertEquals("Custom", result.config().messages().prompt()); assertEquals(PackmuleConfig.Messages.DEFAULTS.declined(), result.config().messages().declined()); } + + @Test + void readsAGatedPacksCheckBlock() throws Exception { + var result = parse(""" + packs: + zz: + url: "https://join.example/zz/t/%s.zip" + check: {public-prefix: "https://join.example/zz/", local-prefix: "http://127.0.0.1:8766/", token-file: "/x/s.token"} + """.formatted(H)); + assertTrue(result.ok(), result.errors().toString()); + var check = result.config().packs().get("zz").check(); + assertEquals("http://127.0.0.1:8766/", check.localPrefix()); + assertEquals("/x/s.token", check.tokenFile()); + } + + @Test + void refusesACheckBlockThatCouldSendTheTokenAway() throws Exception { + String[] bad = { + "{public-prefix: \"https://join.example/zz/\", local-prefix: \"http://10.0.0.5:8766/\", token-file: \"/t\"}", + "{public-prefix: \"https://join.example/zz/\", local-prefix: \"http://example.com/\", token-file: \"/t\"}", + "{public-prefix: \"https://join.example/zz/\", local-prefix: \"http://user@127.0.0.1:8766/\", token-file: \"/t\"}", + "{public-prefix: \"https://other.example/zz/\", local-prefix: \"http://127.0.0.1:8766/\", token-file: \"/t\"}", + "{public-prefix: \"https://join.example/zz\", local-prefix: \"http://127.0.0.1:8766/\", token-file: \"/t\"}", + "{public-prefix: \"https://join.example/zz/\", local-prefix: \"http://127.0.0.1:8766/\"}", + "yes", + }; + for (String check : bad) { + var result = parse(""" + packs: + zz: + url: "https://join.example/zz/t/%s.zip" + check: %s + """.formatted(H, check)); + assertFalse(result.ok(), check); + } + } + + @Test + void loopbackMeansThisMachineOnly() { + assertTrue(PackmuleConfig.isLoopback("127.0.0.1")); + assertTrue(PackmuleConfig.isLoopback("[::1]")); + assertTrue(PackmuleConfig.isLoopback("localhost")); + assertFalse(PackmuleConfig.isLoopback("127.0.0.1.example.com")); + assertFalse(PackmuleConfig.isLoopback("localhost.example.com")); + assertFalse(PackmuleConfig.isLoopback("192.168.1.2")); + assertFalse(PackmuleConfig.isLoopback(null)); + } }