From 643904bc5e4f2c2871cf0a9c44f071212fb71a7b Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Wed, 18 Nov 2026 20:49:54 -0700 Subject: [PATCH] Make every opt-out fail closed (0.8.0) A switch that does not clearly mean "on" now turns reporting off, so an operator's opt-out can never be read as consent: - Server-wide config: every enabled: line counts, its value is read as a YAML scalar (quotes and trailing comment stripped), and only true/on/yes/1 keeps reporting on. A quoted "false", an empty enabled:, a typo, or any later enabled: false now disables (#15, #27). - A server-wide file that exists but cannot be read now disables; one that is not UTF-8 is read as ISO-8859-1 and not appended to (#40). A file that is missing and cannot be created still counts as enabled. - Environment: TRACE_USAGE_REPORTING set to anything but blank or a clear "on" disables; DO_NOT_TRACK set to anything but blank or a clear "no" disables; an environment that cannot be read disables (#39). - New TraceClient.allowsReporting(Object) for a program's own setting, which fails closed the same way; the docs now use it instead of getBoolean(path, true), which reads a quoted "false" as on. Co-Authored-By: Claude Opus 5.5 --- README.md | 16 +- pom.xml | 2 +- .../stephenson/trace/TraceClient.java | 171 +++++++++++++----- .../stephenson/trace/TraceClientTest.java | 151 ++++++++++------ 4 files changed, 233 insertions(+), 107 deletions(-) diff --git a/README.md b/README.md index 5325e94..83a6295 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ program side is meant to stay one call. TraceClient trace = TraceClient.builder("https://trace.danielstephenson.dev", "MyPlugin", getDescription().getVersion()) .key(config.getString("usage-reporting.key")) - .enabled(config.getBoolean("usage-reporting.enabled", true)) + .enabled(TraceClient.allowsReporting(config.get("usage-reporting.enabled"))) .serverWideConfig(getDataFolder().getParentFile()) // plugins/ -- Bukkit plugins only .logger(getLogger()) .build(); @@ -99,7 +99,7 @@ chooses it; there is no default location: ```java TraceClient trace = TraceClient.builder(url, "mycli", version).key(key) - .enabled(settings.usageReportingEnabled()) + .enabled(TraceClient.allowsReporting(settings.usageReportingEnabled())) .installIdFile(new File(dataDir, "trace-install-id")) // e.g. ~/.local/share/mycli/ .build(); ``` @@ -191,14 +191,16 @@ finer than that anyway. ## Opting out Reporting is **opt-out**, and the person running the program always has the -last word. `build()` checks these in order; the first match wins and is what +last word. **Every switch fails closed:** a value that does not clearly mean +"on" — a typo, a quoted `"false"`, an empty value — turns reporting off, and +nothing in this client ever turns a switch back on. `build()` checks these in order; the first match wins and is what `disabledReason()` returns, verbatim, so the program can log it: | Switch | `disabledReason()` | |---|---| -| Environment: `TRACE_USAGE_REPORTING=off` (or `false`, `0`, `no`) or `DO_NOT_TRACK=1` (or `true`, `yes`), case-insensitive. Always checked. | `environment` | -| Server-wide, when `serverWideConfig(pluginsDirectory)` was given: `enabled: false` in `plugins/trace/config.yml`. `build()` creates the file with `enabled: true` (and a commented-out [`tags:`](#server-wide-tags) example) if it is missing; afterwards the only change it ever makes is appending a [`server-id:`](#every-event-carries-a-random-server-id) line when an enabled client finds none. When the environment has already opted out, the file is neither read nor created. It is read with a line regex, no YAML library. An IO failure is logged at `FINE` and counts as enabled. | `server-wide config: plugins/trace/config.yml` | -| The program's own setting: `enabled(false)`. | `config.yml` | +| Environment, case-insensitive, always checked: `TRACE_USAGE_REPORTING` set to anything but blank, `true`, `on`, `yes` or `1` (so `off`, `false`, `0`, `no`, `disabled`, …); or `DO_NOT_TRACK` set to anything but blank, `0`, `false`, `off` or `no` (so `1`, `true`, `yes`, …). An environment that cannot be read (e.g. a `SecurityManager` denying `getenv`) counts as opting out. | `environment` | +| Server-wide, when `serverWideConfig(pluginsDirectory)` was given: any `enabled:` line in `plugins/trace/config.yml` whose value, bare or quoted, is not `true`, `on`, `yes` or `1` — `enabled: false`, `enabled: "off"`, `enabled: no`, an empty `enabled:`, a typo. With several `enabled:` lines, any one that is not on turns reporting off. `build()` creates the file with `enabled: true` (and a commented-out [`tags:`](#server-wide-tags) example) if it is missing; afterwards the only change it ever makes is appending a [`server-id:`](#every-event-carries-a-random-server-id) line when an enabled client finds none. When the environment has already opted out, the file is neither read nor created. It is read with a line regex, no YAML library. A file that is not UTF-8 is read as ISO-8859-1 (and not appended to). A file that is there but cannot be read counts as **disabled** — it may say `enabled: false`; a file that is missing and cannot be created counts as enabled, since the operator has said nothing. Failures are logged at `FINE`. | `server-wide config: plugins/trace/config.yml` | +| The program's own setting: `enabled(false)`. Read it with `TraceClient.allowsReporting(value)`, which fails closed the same way: only `true`, or a string `true`/`on`/`yes`/`1`, allows reporting. On Bukkit pass `getConfig().get(path)`, not `getBoolean(path, true)` — `getBoolean` returns its default for a quoted `"false"`. | `config.yml` | | No key, or a blank one. | `no key` | `disabledReason()` is `null` when the client is enabled. A disabled client does @@ -262,7 +264,7 @@ plugins already vendor bStats' `Metrics.java`. com.github.Stephenson-Software trace-client-java - 0.7.0 + 0.8.0 ``` diff --git a/pom.xml b/pom.xml index cb292dd..6564496 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ software.stephenson trace-client - 0.7.0 + 0.8.0 jar trace-client diff --git a/src/main/java/software/stephenson/trace/TraceClient.java b/src/main/java/software/stephenson/trace/TraceClient.java index d1b4b48..b4680d0 100644 --- a/src/main/java/software/stephenson/trace/TraceClient.java +++ b/src/main/java/software/stephenson/trace/TraceClient.java @@ -1,5 +1,5 @@ /* - * trace-client 0.7.0 -- https://github.com/Stephenson-Software/trace-client-java + * trace-client 0.8.0 -- https://github.com/Stephenson-Software/trace-client-java * * One call to report that a program was used. Copy this file into a project as * is, or depend on the artifact; either way there is nothing else to add. @@ -14,7 +14,9 @@ import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; +import java.nio.charset.CharacterCodingException; import java.nio.charset.StandardCharsets; +import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; @@ -23,6 +25,7 @@ import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.TreeMap; import java.util.UUID; @@ -66,19 +69,27 @@ * * *

Reporting is opt-out, and the person running the program always has the - * last word. {@link Builder#build()} checks, in this order, and the first - * match is what {@link #disabledReason()} reports: + * last word. Every switch fails closed: a value that does not clearly mean + * "on" -- a typo, a quoted {@code "false"}, an empty value -- turns reporting + * off, and nothing in this client ever turns a switch back on. + * {@link Builder#build()} checks, in this order, and the first match is what + * {@link #disabledReason()} reports: * *

    - *
  1. the environment: {@code TRACE_USAGE_REPORTING=off} (or {@code false}, - * {@code 0}, {@code no}) or {@code DO_NOT_TRACK=1} (or {@code true}, - * {@code yes}), case-insensitive -- reason {@code environment};
  2. + *
  3. the environment: {@code TRACE_USAGE_REPORTING} set to anything but + * blank, {@code true}, {@code on}, {@code yes} or {@code 1}; or + * {@code DO_NOT_TRACK} set to anything but blank, {@code 0}, + * {@code false}, {@code off} or {@code no}; case-insensitive -- reason + * {@code environment};
  4. *
  5. the server-wide switch, when {@link Builder#serverWideConfig(File)} - * was given: {@code enabled: false} (or {@code off}, {@code 0}, - * {@code no}, case-insensitive) in {@code plugins/trace/config.yml} - * -- reason {@code server-wide config: plugins/trace/config.yml};
  6. + * was given: any {@code enabled:} line in {@code plugins/trace/config.yml} + * whose value, bare or quoted, is not {@code true}, {@code on}, + * {@code yes} or {@code 1} (case-insensitive); or that file existing but + * being unreadable -- reason + * {@code server-wide config: plugins/trace/config.yml}; *
  7. the program's own setting, {@link Builder#enabled(boolean) - * enabled(false)} -- reason {@code config.yml};
  8. + * enabled(false)} -- reason {@code config.yml}. Read it with + * {@link #allowsReporting(Object)} so it fails closed too; *
  9. no key -- reason {@code no key}.
  10. *
* @@ -117,7 +128,7 @@ * TraceClient trace = TraceClient.builder("https://trace.example.org", "MyPlugin", * getDescription().getVersion()) * .key(config.getString("usage-reporting.key")) - * .enabled(config.getBoolean("usage-reporting.enabled", true)) + * .enabled(TraceClient.allowsReporting(config.get("usage-reporting.enabled"))) * .serverWideConfig(getDataFolder().getParentFile()) // plugins/ * .logger(getLogger()) * .build(); @@ -138,7 +149,7 @@ public final class TraceClient { /** This client's version, as sent in the User-Agent. */ - public static final String VERSION = "0.7.0"; + public static final String VERSION = "0.8.0"; /** How many reports may wait to be sent before new ones are dropped. */ public static final int QUEUE_CAPACITY = 256; @@ -219,7 +230,7 @@ public final class TraceClient { /** What {@link #installIdFromFile(File)} accepts as an ID on a line of its file. */ private static final Pattern INSTALL_ID_LINE = Pattern.compile("[A-Za-z0-9_.\\-]{1,255}"); - private static final Pattern ENABLED_LINE = Pattern.compile("^\\s*enabled\\s*:\\s*(\\S+)"); + private static final Pattern ENABLED_LINE = Pattern.compile("^\\s*enabled\\s*:(.*)$"); private static final Pattern TAGS_LINE = Pattern.compile("^tags\\s*:\\s*(#.*)?$"); private static final Pattern SERVER_ID_LINE = Pattern.compile("^server-id\\s*:(.*)$"); @@ -458,30 +469,71 @@ private static String disabledReason(Builder builder, ServerWideConfig serverWid return null; } + // Both variables fail closed: once set to anything but blank, only a value + // that clearly means "keep reporting" keeps it on. private static boolean environmentDisables() { - return isOff(environment.apply(ENV_USAGE_REPORTING)) || isYes(environment.apply(ENV_DO_NOT_TRACK)); + try { + return environmentSaysOff(); + } catch (RuntimeException unreadable) { + // e.g. a SecurityManager denying getenv: an environment that cannot + // be read may hold DO_NOT_TRACK=1, so it counts as opting out. + return true; + } } - private static boolean isOff(String value) { - if (value == null) { - return false; + private static boolean environmentSaysOff() { + String usageReporting = environment.apply(ENV_USAGE_REPORTING); + if (usageReporting != null && !usageReporting.trim().isEmpty() && !isOn(usageReporting)) { + return true; } - String v = value.trim().toLowerCase(); - return v.equals("off") || v.equals("false") || v.equals("0") || v.equals("no"); + String doNotTrack = environment.apply(ENV_DO_NOT_TRACK); + return doNotTrack != null && !doNotTrack.trim().isEmpty() && !isNegative(doNotTrack); } - private static boolean isYes(String value) { + /** {@code true}, {@code on}, {@code yes} or {@code 1}, ignoring case and surrounding space. */ + private static boolean isOn(String value) { if (value == null) { return false; } - String v = value.trim().toLowerCase(); - return v.equals("1") || v.equals("true") || v.equals("yes"); + String v = value.trim().toLowerCase(Locale.ROOT); + return v.equals("true") || v.equals("on") || v.equals("yes") || v.equals("1"); + } + + /** {@code false}, {@code off}, {@code no} or {@code 0}, ignoring case and surrounding space. */ + private static boolean isNegative(String value) { + String v = value.trim().toLowerCase(Locale.ROOT); + return v.equals("false") || v.equals("off") || v.equals("no") || v.equals("0"); + } + + /** + * Whether a program's own reporting setting, as read from its + * configuration, allows reporting -- for {@link Builder#enabled(boolean)}. + * Fails closed: only {@link Boolean#TRUE}, or a string reading + * {@code true}, {@code on}, {@code yes} or {@code 1} (any case), allows it. + * Anything else turns reporting off: {@code false}, a quoted + * {@code "false"}, {@code off}, {@code no}, a typo, a number, or + * {@code null}. + * + *

Prefer this over {@code getBoolean(path, true)}: Bukkit's + * {@code getBoolean} returns its default for a value that is not a YAML + * boolean, so an operator's {@code enabled: "false"} would read as on. + * Pass the raw value -- on Bukkit, {@code getConfig().get(path)}, which + * still falls through to the defaults bundled in the jar when the + * operator's file has no such key. + */ + public static boolean allowsReporting(Object setting) { + if (setting instanceof Boolean) { + return (Boolean) setting; + } + return setting instanceof String && isOn((String) setting); } /** What {@code plugins/trace/config.yml} says: the switch, the server-wide tags and the server-id. */ static final class ServerWideConfig { /** No file was read: none was asked for, or it could not be read. */ static final ServerWideConfig NONE = new ServerWideConfig(false, Collections.emptyMap(), null); + /** The file is there but could not be read: whatever it says, it may say off. */ + static final ServerWideConfig UNREADABLE = new ServerWideConfig(true, Collections.emptyMap(), null); final boolean disables; final Map tags; @@ -510,35 +562,65 @@ ServerWideConfig readFromDisk(boolean created) { * Ensures {@code /trace/config.yml} exists and reads its * {@code enabled:} line, {@code tags:} block and {@code server-id:} line. * Not called when the environment opts out. No YAML library: the file - * is ours, shallow, and a line scan is enough. Anything going wrong on - * disk is logged at FINE and counts as enabled with no tags -- a - * read-only plugins directory must not silently switch reporting off, - * nor stop the host program. + * is ours, shallow, and a line scan is enough. Nothing here throws. + * A file that is missing and cannot be created counts as enabled with no + * tags: the operator has said nothing, and a read-only plugins directory + * must not silently switch reporting off. A file that is there but cannot + * be read counts as disabled: it may say {@code enabled: false}. A file + * that is not valid UTF-8 is read as ISO-8859-1. */ private ServerWideConfig readServerWideConfig(File pluginsDirectory) { File location = new File(pluginsDirectory, SERVER_WIDE_CONFIG_PATH); + Path file; + try { + // toPath() throws InvalidPathException for a path the file system + // cannot represent. No file can be there, so the operator has said + // nothing; and build() never throws. + file = location.toPath(); + } catch (RuntimeException unrepresentable) { + log("could not read server-wide config " + location + ": " + unrepresentable); + return ServerWideConfig.NONE; + } try { - // Inside the try: toPath() throws InvalidPathException for a path - // the file system cannot represent, and build() never throws. - Path file = location.toPath(); boolean created = false; if (!Files.exists(file)) { - Files.createDirectories(file.getParent()); - Files.write(file, SERVER_WIDE_CONFIG_CONTENT.getBytes(StandardCharsets.UTF_8)); - // just written: enabled: true, and the tags example commented out - created = true; + try { + Files.createDirectories(file.getParent()); + Files.write(file, SERVER_WIDE_CONFIG_CONTENT.getBytes(StandardCharsets.UTF_8), + StandardOpenOption.CREATE_NEW); + // just written: enabled: true, and the tags example commented out + created = true; + } catch (FileAlreadyExistsException raced) { + // another plugin wrote it first: read theirs + } catch (IOException | RuntimeException failure) { + // No file, and none can be made: the operator has said nothing. + log("could not create server-wide config " + location + ": " + failure); + return ServerWideConfig.NONE; + } + } + try { + return parseServerWideConfig(Files.readAllLines(file, StandardCharsets.UTF_8)).readFromDisk(created); + } catch (CharacterCodingException notUtf8) { + // Saved in another encoding, e.g. with an accented comment. The + // switch is still read; nothing is appended to the file, so the + // install ID lives in memory for this process. + log("server-wide config " + location + " is not UTF-8; reading it as ISO-8859-1"); + return parseServerWideConfig(Files.readAllLines(file, StandardCharsets.ISO_8859_1)); } - return parseServerWideConfig(Files.readAllLines(file, StandardCharsets.UTF_8)).readFromDisk(created); } catch (IOException | RuntimeException failure) { - log("could not read server-wide config " + location + ": " + failure); - return ServerWideConfig.NONE; + // The file is there but cannot be read. It may say enabled: false, + // so reporting stays off rather than guessing. + log("could not read server-wide config " + location + ", so reporting is off: " + failure); + return ServerWideConfig.UNREADABLE; } } + /** * Reads the switch and the tags from the lines of the server-wide file. - * The first {@code enabled:} line outside a {@code tags:} block is the - * switch. A {@code tags:} line at column 0 opens a block of indented + * Every {@code enabled:} line outside a {@code tags:} block is a switch, + * and reporting stays on only if each one reads, bare or quoted, + * {@code true}, {@code on}, {@code yes} or {@code 1}. A {@code tags:} line at column 0 opens a block of indented * {@code key: value} lines, which ends at the next line that is not * blank, a comment or indented; blank and {@code #} lines inside it are * skipped, at any indent, as are lines indented differently from its @@ -593,10 +675,15 @@ static ServerWideConfig parseServerWideConfig(List lines) { continue; } } - if (disables == null) { - Matcher matcher = ENABLED_LINE.matcher(line); - if (matcher.find()) { - disables = isOff(matcher.group(1)); + Matcher enabled = ENABLED_LINE.matcher(line); + if (enabled.matches()) { + // Fails closed: every enabled: line counts, and only a value + // that clearly means "on" keeps reporting on. + String value = scalar(enabled.group(1).trim()); + if (value == null || !isOn(value)) { + disables = true; + } else if (disables == null) { + disables = false; } } } diff --git a/src/test/java/software/stephenson/trace/TraceClientTest.java b/src/test/java/software/stephenson/trace/TraceClientTest.java index ea0f1a2..f28bd5b 100644 --- a/src/test/java/software/stephenson/trace/TraceClientTest.java +++ b/src/test/java/software/stephenson/trace/TraceClientTest.java @@ -487,24 +487,25 @@ void withInstall_addsTheIdOnlyWhenThereIsOneAndRoomAndNoneAlready() { } @Test - void serverWideConfig_theFirstEnabledLineIsTheSwitch() { - assertFalse(TraceClient.parseServerWideConfig(Arrays.asList("enabled: true", "enabled: false")).disables); - assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled: false", "enabled: true")).disables); + void serverWideConfig_anyEnabledLineThatIsNotOnDisables() { + assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled: true", "enabled: false")).disables, + "a later off wins over an earlier on"); + assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled: false", "enabled: true")).disables, + "and an earlier off wins over a later on"); + assertFalse(TraceClient.parseServerWideConfig(Arrays.asList("enabled: true", "enabled: yes")).disables); assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("# enabled: true", "enabled: false")).disables, - "a commented-out line is not the first one"); + "a commented-out line is not a switch"); } @Test - void serverWideConfig_aValuelessEnabledLineIsSkippedButACommentOnlyOneIsTheSwitch() { - // Characterizes current behaviour, which issue #27 questions: - // ENABLED_LINE needs a non-blank value, so a bare "enabled:" is - // passed over and a later line is the switch; but after - // "enabled: # ..." the captured value is "#", which is not off, so - // that line is the switch and a later one is ignored. - assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled:", "enabled: false")).disables); - assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled: ", "enabled: false")).disables); - assertFalse(TraceClient.parseServerWideConfig(Arrays.asList("enabled: # set below", "enabled: false")).disables); - assertFalse(TraceClient.parseServerWideConfig(Arrays.asList("enabled:")).disables, "a bare enabled: alone is enabled"); + void serverWideConfig_aValuelessEnabledLineDisables() { + // Fails closed (issue #27): an enabled: line with no value, or only a + // comment, does not clearly mean "on", so it turns reporting off. + assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled:")).disables); + assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled: ")).disables); + assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled: # set below", "enabled: true")).disables); + assertFalse(TraceClient.parseServerWideConfig(Arrays.asList("enabled: true # on")).disables, + "a trailing comment after a value is not part of it"); } @Test @@ -1125,16 +1126,17 @@ void serverWideConfig_enabledFalseDisablesWithTheServerWideReason(@TempDir Path } @Test - void serverWideConfig_acceptsEverySpellingOfOff(@TempDir Path plugins) throws Exception { + void serverWideConfig_onlyClearSpellingsOfOnLeaveReportingOn(@TempDir Path plugins) throws Exception { Path file = plugins.resolve("trace").resolve("config.yml"); Files.createDirectories(file.getParent()); - for (String off : new String[] {"false", "no", "0", "off", "OFF", "No"}) { + for (String off : new String[] {"false", "no", "0", "off", "OFF", "No", "\"false\"", "'off'", + "flase", "disabled", "anything-else"}) { Files.write(file, ("enabled: " + off + "\n").getBytes(StandardCharsets.UTF_8)); assertEquals(TraceClient.REASON_SERVER_WIDE, TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").serverWideConfig(plugins.toFile()).build().disabledReason(), "enabled: " + off + " should disable"); } - for (String on : new String[] {"true", "yes", "1", "on", "anything-else"}) { + for (String on : new String[] {"true", "yes", "1", "on", "ON", "\"true\""}) { Files.write(file, ("enabled: " + on + "\n").getBytes(StandardCharsets.UTF_8)); assertNull(TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").serverWideConfig(plugins.toFile()).build().disabledReason(), "enabled: " + on + " should not disable"); @@ -1153,42 +1155,73 @@ void serverWideConfig_theSwitchIgnoresATrailingCommentAndLeadingIndent() { } @Test - void serverWideConfig_aQuotedFalseDoesNotDisableYet() { - // Characterizes current behaviour, which issue #15 questions: the - // enabled: value is compared with its quotes on, unlike tag values - // and server-id:, so a quoted spelling of off leaves reporting on. + void serverWideConfig_aQuotedOffDisables() { + // Issue #15: the value used to be compared with its quotes on. for (String quoted : new String[] {"\"false\"", "'false'", "\"off\"", "'no'"}) { - assertFalse(TraceClient.parseServerWideConfig(Arrays.asList("enabled: " + quoted)).disables, + assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled: " + quoted)).disables, "enabled: " + quoted); } + assertFalse(TraceClient.parseServerWideConfig(Arrays.asList("enabled: \"true\"")).disables); } @Test - void serverWideConfig_aByteThatIsNotUtf8LeavesReportingOnYet(@TempDir Path plugins) throws Exception { - // Characterizes current behaviour, which issue #40 questions: one - // byte of another encoding fails the whole read, which counts as an - // IO failure, so the enabled: false below it is never seen. - // Arrange + void environment_thatCannotBeReadOptsOut() { + java.util.function.Function saved = TraceClient.environment; + TraceClient.environment = name -> { throw new SecurityException("getenv." + name); }; + try { + TraceClient client = assertDoesNotThrow(() -> TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build()); + assertEquals(TraceClient.REASON_ENVIRONMENT, client.disabledReason()); + assertDoesNotThrow(() -> TraceClient.disabled()); + } finally { + TraceClient.environment = saved; + } + } + + @Test + void allowsReporting_failsClosed() { + assertTrue(TraceClient.allowsReporting(true)); + assertTrue(TraceClient.allowsReporting("true")); + assertTrue(TraceClient.allowsReporting(" ON ")); + assertTrue(TraceClient.allowsReporting("yes")); + assertTrue(TraceClient.allowsReporting("1")); + assertFalse(TraceClient.allowsReporting(false)); + assertFalse(TraceClient.allowsReporting("false")); + assertFalse(TraceClient.allowsReporting("off")); + assertFalse(TraceClient.allowsReporting("flase")); + assertFalse(TraceClient.allowsReporting("")); + assertFalse(TraceClient.allowsReporting(1)); + assertFalse(TraceClient.allowsReporting(null)); + } + + @Test + void serverWideConfig_aFileThatIsNotUtf8IsStillObeyed(@TempDir Path plugins) throws Exception { + // Issue #40: one byte of another encoding used to fail the whole read, + // so the enabled: false below it was never seen. Path file = plugins.resolve("trace").resolve("config.yml"); Files.createDirectories(file.getParent()); - Files.write(file, "# café\nenabled: false\n".getBytes(StandardCharsets.ISO_8859_1)); - RecordingHandler log = new RecordingHandler(); - Logger logger = Logger.getLogger("TraceClientTest.serverWideNotUtf8"); - logger.setLevel(Level.ALL); - logger.addHandler(log); + byte[] latin1 = "# café\nenabled: false\n".getBytes(StandardCharsets.ISO_8859_1); + Files.write(file, latin1); - // Act TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k") - .serverWideConfig(plugins.toFile()).logger(logger).build(); + .serverWideConfig(plugins.toFile()).build(); - // Assert - assertTrue(client.isEnabled(), "the switch was not read"); - assertTrue(log.await(1, TimeUnit.SECONDS), "the failure should be mentioned at FINE"); - assertTrue(log.records.get(0).getMessage().contains("could not read server-wide config"), - log.records.get(0).getMessage()); + assertEquals(TraceClient.REASON_SERVER_WIDE, client.disabledReason()); + assertArrayEquals(latin1, Files.readAllBytes(file), "the file is left as it is"); client.close(); } + @Test + void serverWideConfig_aFileThatIsThereButUnreadableDisables(@TempDir Path plugins) throws Exception { + // A directory where the file should be cannot be read, and may be + // hiding an opt-out: reporting stays off. + Files.createDirectories(plugins.resolve("trace").resolve("config.yml")); + + TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k") + .serverWideConfig(plugins.toFile()).build(); + + assertEquals(TraceClient.REASON_SERVER_WIDE, client.disabledReason()); + } + @Test void serverWideConfig_aByteOrderMarkHidesAFirstLineEnabledFalseYet(@TempDir Path plugins) throws Exception { // Characterizes current behaviour, which issue #40 questions: the @@ -1269,33 +1302,37 @@ void environment_eitherVariableAloneTurnsReportingOffWhateverTheOtherSays() { } @Test - void environment_valuesThatAreNotAnOptOutLeaveReportingOn() { - // Only the listed spellings opt out: a blank value, the opposite - // word, or anything else is not read as a wish to stop reporting. - for (String value : new String[] {"", " ", "on", "true", "yes", "1", "disabled", "offline"}) { - // Arrange + void environment_onlyBlankOrAClearOnLeavesReportingOn() { + // Fails closed: once a variable is set to anything but blank, only a + // value that clearly means "keep reporting" leaves it on. + for (String value : new String[] {"", " ", "on", "true", "yes", "1", "TRUE"}) { environment.clear(); environment.put("TRACE_USAGE_REPORTING", value); - - // Act TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build(); - - // Assert assertNull(client.disabledReason(), "TRACE_USAGE_REPORTING=\"" + value + "\""); client.close(); } - for (String value : new String[] {"", " ", "0", "false", "no", "off", "2", "y"}) { - // Arrange + for (String value : new String[] {"disabled", "offline", "nope", "2"}) { + environment.clear(); + environment.put("TRACE_USAGE_REPORTING", value); + assertEquals(TraceClient.REASON_ENVIRONMENT, + TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build().disabledReason(), + "TRACE_USAGE_REPORTING=\"" + value + "\""); + } + for (String value : new String[] {"", " ", "0", "false", "no", "off"}) { environment.clear(); environment.put("DO_NOT_TRACK", value); - - // Act TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build(); - - // Assert assertNull(client.disabledReason(), "DO_NOT_TRACK=\"" + value + "\""); client.close(); } + for (String value : new String[] {"2", "y", "please"}) { + environment.clear(); + environment.put("DO_NOT_TRACK", value); + assertEquals(TraceClient.REASON_ENVIRONMENT, + TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build().disabledReason(), + "DO_NOT_TRACK=\"" + value + "\""); + } } @Test @@ -1675,8 +1712,8 @@ void serverWideTags_malformedFileNeverThrowsAndReportingStillWorks(@TempDir Path byte[] notUtf8 = Files.readAllBytes(file); String body = reportedBody(plugins, "startup", null); assertTrue(body.matches("\\{\"application\":\"MyPlugin\",\"name\":\"startup\",\"tags\":" - + "\\{\"version\":\"1\\.2\\.3\",\"install\":\"" + UUID_PATTERN + "\"}}"), - "a file that is not UTF-8 counts as enabled with no tags, and an in-memory install ID: " + body); + + "\\{\"version\":\"1\\.2\\.3\",\"install\":\"" + UUID_PATTERN + "\",\"ci\":\"\u00c3\\(\"}}"), + "a file that is not UTF-8 is read as ISO-8859-1, with an in-memory install ID: " + body); assertArrayEquals(notUtf8, Files.readAllBytes(file), "a file that cannot be read is never appended to"); } @@ -1947,7 +1984,7 @@ void installId_anUnreadableConfigIsLoggedFineAndNotAppendedTo(@TempDir Path scra // Assert: both happen on the building thread, so they are already logged. assertEquals(2, log.records.size(), log.records.toString()); assertEquals(Level.FINE, log.records.get(0).getLevel()); - assertTrue(log.records.get(0).getMessage().startsWith("[trace] could not read server-wide config "), + assertTrue(log.records.get(0).getMessage().startsWith("[trace] could not create server-wide config "), log.records.get(0).getMessage()); assertEquals(Level.FINE, log.records.get(1).getLevel()); assertEquals("[trace] using an in-memory server-id for this process: server-wide config was not readable",