From 5958b8f478b6142437e7b7c7fd9a3c025cf5a1c9 Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Thu, 19 Nov 2026 00:18:43 -0700 Subject: [PATCH] fix: count a near-miss usage-reporting opt-out as off Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYNeupL3KtraCJoZMADVQE --- README.md | 5 ++- tests/test_usage_reporting.py | 61 +++++++++++++++++++++++++++++++ usage_reporting.py | 68 ++++++++++++++++++++++++++++++----- 3 files changed, 125 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index d00dd19..d94bc3f 100644 --- a/README.md +++ b/README.md @@ -362,7 +362,10 @@ For both variables, case and surrounding whitespace are ignored, and a blank val Every switch fails closed. In `settings.json`, only `true` (or the string `"true"`, `"on"`, `"yes"` or `"1"`) reports; `false`, `"false"`, `"off"`, `0`, `""`, `null` or a typo all keep reporting off. A `usage_reporting` entry that is not an object, such as `"usage_reporting": false`, is read as the -switch itself and is never overwritten. +switch itself and is never overwritten. An opt-out written under another spelling also counts as +off: a block named `usage-reporting`, `usageReporting` or `UsageReporting`, an `enable`/`Enabled` +switch that is not clearly on, or `"disabled": true`; the first run then writes +`"usage_reporting": {"enabled": false}` next to it. The environment variables win over `settings.json`. `endpoint` selects the trace server and `key` the key reports are sent with; the `PATCHWORK_USAGE_REPORTING_KEY` environment variable, when diff --git a/tests/test_usage_reporting.py b/tests/test_usage_reporting.py index dc259bc..ce3a957 100644 --- a/tests/test_usage_reporting.py +++ b/tests/test_usage_reporting.py @@ -13,6 +13,7 @@ DETAILS_URL, FIRST_RUN_NOTICE, FIRST_RUN_NOTICE_OFF_BY_ENVIRONMENT, + FIRST_RUN_NOTICE_OFF_BY_SETTINGS, KEY_ENV_VAR, buildClient, installIdFile, @@ -172,6 +173,66 @@ def test_a_block_that_is_not_an_object_can_still_turn_reporting_on(self): finally: client.close() + def test_an_opt_out_written_under_a_near_miss_name_is_an_opt_out(self): + # these used to be ignored, so the default block (on) was written next to them + cases = ( + {"usage-reporting": {"enabled": False}}, + {"usageReporting": {"enabled": "off"}}, + {"UsageReporting": {"enabled": "false"}}, + {"usage-reporting": "off"}, + {"usage_reporting": {"enable": False}}, + {"usage_reporting": {"Enabled": "no"}}, + {"usage_reporting": {"disabled": True}}, + {"usage_reporting": {"enabled": True, "disabled": "yes"}}, + {"usage_reporting": True, "usageReporting": False}, + ) + for settings in cases: + with self.subTest(settings=settings): + with open(self.settingsFile, "w") as f: + json.dump(settings, f) + + client = buildClient(loadSettings(self.settingsFile, self.log), self.log) + try: + self.assertFalse(client.enabled) + finally: + client.close() + self.assertNotIn(FIRST_RUN_NOTICE, self.logged) + + def test_near_miss_names_that_say_on_are_not_an_opt_out(self): + cases = ( + {"usage-reporting": {"enabled": True}}, + {"usageReporting": "on"}, + {"usage_reporting": {"enabled": True, "enable": "yes"}}, + {"usage_reporting": {"enabled": True, "disabled": False}}, + {"usage_reporting": {"enabled": True, "disabled": "no"}}, + ) + for settings in cases: + with self.subTest(settings=settings): + with open(self.settingsFile, "w") as f: + json.dump(settings, f) + + client = buildClient(loadSettings(self.settingsFile, self.log), self.log) + try: + self.assertTrue(client.enabled) + finally: + client.close() + + def test_a_first_run_over_a_near_miss_opt_out_writes_the_real_switch_off(self): + with open(self.settingsFile, "w") as f: + json.dump({"usage-reporting": {"enabled": False}}, f) + + loadSettings(self.settingsFile, self.log) + client = buildClient(loadSettings(self.settingsFile, self.log), self.log) + try: + self.assertFalse(client.enabled) + finally: + client.close() + + written = self.readSettingsFile() + self.assertIs(False, written["usage_reporting"]["enabled"]) + self.assertEqual({"enabled": False}, written["usage-reporting"], "the operator's block is kept") + self.assertEqual([FIRST_RUN_NOTICE_OFF_BY_SETTINGS], self.logged) + def test_enabled_fails_closed(self): # enabled used to go through bool(), so the string "false" turned reporting on; # now only true or an "on" string does diff --git a/usage_reporting.py b/usage_reporting.py index 6d45f66..3d2be77 100644 --- a/usage_reporting.py +++ b/usage_reporting.py @@ -1,6 +1,7 @@ import atexit import json import os +import re import sys from trace_client import TraceClient, allows_reporting, environment_opts_out @@ -42,13 +43,60 @@ ) -def firstRunNotice(): - """The line the first run prints: FIRST_RUN_NOTICE, unless the environment has opted out.""" +# Shown on the first run instead when settings.json already turns reporting off under another +# spelling (see hasNearMissOptOut): the real block is written with "enabled": false next to it. +FIRST_RUN_NOTICE_OFF_BY_SETTINGS = ( + 'Usage reporting is off (settings.json), and "usage_reporting": {"enabled": false} was ' + "written to settings.json so it stays off. Details: " + DETAILS_URL +) + + +def firstRunNotice(nearMissOptOut=False): + """The line the first run prints: FIRST_RUN_NOTICE, unless the environment or a near-miss + opt-out in settings.json has already turned reporting off.""" if environment_opts_out(): return FIRST_RUN_NOTICE_OFF_BY_ENVIRONMENT + if nearMissOptOut: + return FIRST_RUN_NOTICE_OFF_BY_SETTINGS return FIRST_RUN_NOTICE +def _normaliseKey(key): + return re.sub(r"[^a-z0-9]", "", str(key).lower()) + + +def hasNearMissOptOut(settings, settingsKey=SETTINGS_SECTION, switchKey="enabled"): + """ + Whether ``settings`` holds an attempt to turn usage reporting off that is not written exactly + as ``usage_reporting`` -> ``enabled``. Such a setting would not be recognised, the default + block (``enabled: true``) would be written next to it, and reporting would stay on. An operator + who wrote any of these did not ask for reporting, so each counts as off: + + - a top-level key that spells "usage reporting" another way (``usage-reporting``, + ``usageReporting``, ``UsageReporting``, ...) holding a value, or an ``enabled``-like key, + that is not clearly on; + - ``"usage_reporting": "off"`` -- a value instead of a block; + - inside any such block, a key that spells "enabled" another way (``enable``, ``Enabled``, + ...) that is not clearly on, or one that spells "disabled" whose value is on. + """ + for key, value in settings.items(): + if "usagereport" not in _normaliseKey(key): + continue + if not isinstance(value, dict): + if not allows_reporting(value): + return True + continue + for child, childValue in value.items(): + if key == settingsKey and child == switchKey: + continue # the switch itself, read by the caller + name = _normaliseKey(child) + if "disabl" in name and allows_reporting(childValue): + return True + if "enabl" in name and not allows_reporting(childValue): + return True + return False + + def defaultSettings(enabled=True): """The usage_reporting block written to settings.json on first run.""" return {"enabled": enabled, "endpoint": DEFAULT_ENDPOINT, "key": DEFAULT_KEY} @@ -100,18 +148,22 @@ def loadSettings(settingsFile=SETTINGS_FILE, log=print): log(f"Could not read {settingsFile} ({e}); usage reporting is off until it is fixed.") return None + # An opt-out written under another spelling (usage-reporting, an "enable" switch, + # "disabled": true, ...) is an opt-out. + nearMissOptOut = hasNearMissOptOut(settings) section = settings.get(SETTINGS_SECTION) if isinstance(section, dict): - return section + return dict(section, enabled=False) if nearMissOptOut else section if SETTINGS_SECTION in settings: # "usage_reporting": false (or "off", or anything else that is not a block) is the # switch itself: read it as such, and never write the default block (on) over it. - return {"enabled": section} + return {"enabled": False if nearMissOptOut else section} - # Under an environment opt-out the first run records "off", so a later run without the - # variable does not quietly report. - settings[SETTINGS_SECTION] = defaultSettings(enabled=not environment_opts_out()) - log(firstRunNotice()) + # Under an environment or near-miss opt-out the first run records "off", so a later run + # does not quietly report. + settings[SETTINGS_SECTION] = defaultSettings( + enabled=not (environment_opts_out() or nearMissOptOut)) + log(firstRunNotice(nearMissOptOut)) try: with open(settingsFile, "w") as f: json.dump(settings, f, indent=2)