diff --git a/README.md b/README.md index 901e954..aa243b0 100644 --- a/README.md +++ b/README.md @@ -271,6 +271,14 @@ Turn it off any of these ways: - `DO_NOT_TRACK=1` (also `true`, `yes`) in the environment — the [console DNT convention](https://consoledonottrack.com), honoured the same way +Every switch fails closed, so an opt-out is never read as "on": +`GARDENER_USAGE_REPORTING_ENABLED`, once set (in the environment or +`notify.env`, even blank), keeps reporting on only for `true`, `on`, `yes` or +`1` (any case); anything else — empty, a typo — turns it off, and so does a +`notify.env` that exists but cannot be read. `TRACE_USAGE_REPORTING` set to +anything but blank or one of those values turns it off, as does `DO_NOT_TRACK` +set to anything but blank, `0`, `false`, `off` or `no`. + ```bash export GARDENER_USAGE_REPORTING_ENABLED=false # or, in the same notify.env file as above: @@ -282,7 +290,7 @@ echo 'GARDENER_USAGE_REPORTING_ENABLED=false' >> ~/.local/state/gardener/notify. ``` The client is [trace-client-python](https://github.com/Stephenson-Software/trace-client-python) -0.4.1, vendored unmodified as `gardener/trace_client.py` (stdlib only, so +0.5.0, vendored unmodified as `gardener/trace_client.py` (stdlib only, so gardener's no-dependency rule holds); `gardener/usage.py` is the wiring. Details: https://danielstephenson.dev/usage-reporting diff --git a/docs/TESTING.md b/docs/TESTING.md index 92bc019..b54a283 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -265,7 +265,7 @@ or unreachable server delays `stop` by at most its timeout, and `cli.main`'s wiring — `status` and `ps -q` each report exactly once with stdout untouched, `--help` reports nothing, either opt-out sends nothing, and the client is stopped even when the command raises. -`tests/test_trace_client.py` is the vendored client's own suite (0.4.1), +`tests/test_trace_client.py` is the vendored client's own suite (0.5.0), unchanged apart from its import lines, against the same loopback pattern; it also covers the client-wide `TRACE_USAGE_REPORTING` / `DO_NOT_TRACK` opt-out, which `test_usage.py` checks wins over gardener's own setting. diff --git a/gardener/trace_client.py b/gardener/trace_client.py index 19fac72..3ef93ff 100644 --- a/gardener/trace_client.py +++ b/gardener/trace_client.py @@ -1,4 +1,4 @@ -"""trace-client 0.4.1 -- https://github.com/Stephenson-Software/trace-client-python +"""trace-client 0.5.0 -- https://github.com/Stephenson-Software/trace-client-python One call to report that a program was used. Copy this file into a project as is, or vendor the package; either way there is nothing else to add. Standard @@ -10,8 +10,10 @@ """ from __future__ import annotations +import decimal import json import logging +import numbers import os import queue import re @@ -21,27 +23,31 @@ import uuid from typing import Dict, Mapping, Optional, Union -__version__ = "0.4.1" +__version__ = "0.5.0" _LOG = logging.getLogger("trace") #: Environment variables that turn reporting off for every program using a -#: trace client, checked before the program's own setting. Set -#: ``TRACE_USAGE_REPORTING=off`` (also ``false``, ``0``, ``no``; case does not -#: matter) or ``DO_NOT_TRACK=1`` (also ``true``, ``yes``; see -#: https://consoledonottrack.com). +#: trace client, checked before the program's own setting. Both fail closed: +#: ``TRACE_USAGE_REPORTING`` set to anything but blank, ``true``, ``on``, +#: ``yes`` or ``1`` turns reporting off (so ``off``, ``false``, ``0``, ``no``, +#: ``disabled``, a typo, ...), and so does ``DO_NOT_TRACK`` set to anything +#: but blank, ``0``, ``false``, ``off`` or ``no`` (so ``1``, ``true``, +#: ``yes``, ...; see https://consoledonottrack.com). Case and surrounding +#: space do not matter. ENV_TRACE_USAGE_REPORTING = "TRACE_USAGE_REPORTING" ENV_DO_NOT_TRACK = "DO_NOT_TRACK" -_OFF_VALUES = frozenset(("off", "false", "0", "no")) -_DO_NOT_TRACK_VALUES = frozenset(("1", "true", "yes")) +_ON_VALUES = frozenset(("true", "on", "yes", "1")) +_NEGATIVE_VALUES = frozenset(("false", "off", "no", "0")) #: The values :attr:`TraceClient.disabled_reason` can take. First match wins. REASON_ENVIRONMENT = "environment" REASON_CONFIG = "config" REASON_NO_KEY = "no key" -#: The longest a program version may be, after trimming: the trace server's -#: limit on a tag value. +#: The longest a tag value the client sets itself -- the program version, the +#: installation ID -- may be, after trimming: the trace server's limit on a +#: tag value. MAX_TAG_LENGTH = 255 #: The most tags one event carries: the trace server's limit. The ``install`` @@ -54,18 +60,58 @@ # What install_id_from_file accepts as an ID on a line of its file. _INSTALL_ID_LINE = re.compile(r"^[A-Za-z0-9_.-]{1,%d}$" % MAX_TAG_LENGTH) +# What the User-Agent header cannot carry: everything but printable Latin-1. +_NOT_IN_A_HEADER = re.compile(r"[^\x20-\x7e\xa0-\xff]") + + +class _RedirectsNotFollowed(urllib.request.HTTPRedirectHandler): + """Declines every redirect, so the redirect itself is the answer. Following + one would re-send the key to whatever host ``Location`` names, and a 301, + 302 or 303 would turn the POST into an empty GET that loses the event + anyway. trace-client-java does not follow redirects either.""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +# Every report goes through this opener rather than urlopen: urlopen follows +# redirects, and install_opener would change the host program's urlopen too. +_OPENER = urllib.request.build_opener(_RedirectsNotFollowed) + def environment_opts_out(environ: Optional[Mapping[str, str]] = None) -> bool: - """Whether the environment asks for usage reporting to be off, via - ``TRACE_USAGE_REPORTING=off`` or ``DO_NOT_TRACK=1``. Only the listed - values count; anything else (including an empty value) leaves the - program's own setting in charge.""" - env = os.environ if environ is None else environ - if env.get(ENV_TRACE_USAGE_REPORTING, "").strip().lower() in _OFF_VALUES: + """Whether the environment asks for usage reporting to be off. Fails + closed: ``TRACE_USAGE_REPORTING`` set to anything but blank or a clear + "on" (``true``, ``on``, ``yes``, ``1``), or ``DO_NOT_TRACK`` set to + anything but blank or a clear "no" (``0``, ``false``, ``off``, ``no``), + opts out; case and surrounding space do not matter. An environment that + cannot be read -- or a value that is not a string -- opts out too: it may + hold ``DO_NOT_TRACK=1``. Never raises.""" + try: + env = os.environ if environ is None else environ + usage_reporting = (env.get(ENV_TRACE_USAGE_REPORTING) or "").strip().lower() + if usage_reporting and usage_reporting not in _ON_VALUES: + return True + do_not_track = (env.get(ENV_DO_NOT_TRACK) or "").strip().lower() + return bool(do_not_track) and do_not_track not in _NEGATIVE_VALUES + except Exception: # noqa: BLE001 - an environment that cannot be read counts as opting out return True - if env.get(ENV_DO_NOT_TRACK, "").strip().lower() in _DO_NOT_TRACK_VALUES: - return True - return False + + +def allows_reporting(setting: object) -> bool: + """Whether a program's own reporting setting, as read from its + configuration, allows reporting -- for ``enabled=``. Fails closed: only + ``True``, or a string reading ``true``, ``on``, ``yes`` or ``1`` (any + case, surrounding space ignored), allows it. Anything else turns + reporting off: ``False``, ``"false"``, ``"off"``, ``"no"``, a typo, a + number, ``None`` (a missing setting), a quoted ``'"false"'``. + + Pass the raw value, e.g. ``settings.get("usage_reporting")``, rather than + ``bool(...)`` of it: ``bool("false")`` is ``True``. The constructor reads + ``enabled=`` through this function too, so ``enabled="false"`` is off.""" + if isinstance(setting, bool): + return setting + return isinstance(setting, str) and setting.strip().lower() in _ON_VALUES class TraceClient: @@ -89,7 +135,10 @@ class TraceClient: does nothing and costs nothing. So does the environment: the constructor checks ``TRACE_USAGE_REPORTING=off`` and ``DO_NOT_TRACK=1`` before it looks at ``enabled``, so a user can switch off every trace-reporting - program at once. :attr:`disabled_reason` says which of those applied + program at once. Every switch fails closed: a value that does not clearly + mean "on" turns reporting off (see :func:`environment_opts_out` and + :func:`allows_reporting`), and nothing in this client turns a switch + back on. :attr:`disabled_reason` says which of those applied (``"environment"``, ``"config"`` or ``"no key"``; ``None`` when on) so the program can say so in its notice. Programs that run on other people's machines should expose that switch in their settings and say @@ -113,7 +162,8 @@ class TraceClient: :: trace = TraceClient("https://trace.example.org", "roam", __version__, - key=settings.usage_key, enabled=settings.usage_reporting) + key=settings.usage_key, + enabled=allows_reporting(settings.usage_reporting)) trace.report("startup") ... trace.close() # on shutdown @@ -123,7 +173,7 @@ class TraceClient: TIMEOUT_SECONDS = 5.0 def __init__(self, base_url: str, application: str, version: str, *, key: Optional[str] = None, - enabled: bool = True, install_id: Optional[str] = None, + enabled: Union[bool, str, None] = True, install_id: Optional[str] = None, install_id_file: Optional[Union[str, "os.PathLike[str]"]] = None) -> None: """A client for the program named ``application``, at ``version``, reporting to the trace server at ``base_url``. The version is sent as @@ -137,7 +187,18 @@ def __init__(self, base_url: str, application: str, version: str, *, key: Option longer than :data:`MAX_TAG_LENGTH` characters is a :class:`ValueError`. ``install_id_file`` is a path to load it from (or create it in) with :meth:`install_id_from_file`, only when the - client is enabled; an explicit ``install_id`` wins over it.""" + client is enabled; an explicit ``install_id`` wins over it. + + A value that is not a string for ``base_url``, ``application``, + ``version``, ``key`` or ``install_id`` is a :class:`ValueError` naming + the argument, even on a client that would be disabled: a settings + file that reads ``version: 1.4`` as a number should say so. An empty + one (``0``, ``False``, ``[]``) still means no value, as it did before + that check: no key, no ID, or " is required".""" + for argument, given in (("base_url", base_url), ("application", application), ("version", version), + ("key", key), ("install_id", install_id)): + if given and not isinstance(given, str): + raise ValueError("%s must be a string, not %s" % (argument, type(given).__name__)) if not base_url or not base_url.strip(): raise ValueError("base_url is required") if not application or not application.strip(): @@ -157,12 +218,13 @@ def __init__(self, base_url: str, application: str, version: str, *, key: Option self._thread: Optional[threading.Thread] = None #: Why this client reports nothing: ``"environment"`` (the #: ``TRACE_USAGE_REPORTING`` / ``DO_NOT_TRACK`` variables), - #: ``"config"`` (``enabled=False``) or ``"no key"``; ``None`` when it + #: ``"config"`` (``enabled`` not ``True`` or an "on" string -- see + #: :func:`allows_reporting`) or ``"no key"``; ``None`` when it #: reports. Decided once, here, in that order of precedence. self.disabled_reason: Optional[str] = None if environment_opts_out(): self.disabled_reason = REASON_ENVIRONMENT - elif not enabled: + elif not allows_reporting(enabled): self.disabled_reason = REASON_CONFIG elif not self._key: self.disabled_reason = REASON_NO_KEY @@ -245,7 +307,10 @@ def enabled(self) -> bool: def report(self, name: str, value: Optional[float] = None, tags: Optional[Mapping[str, str]] = None) -> None: """Report that ``name`` happened, with an optional numeric value and - optional string tags. Returns immediately; see the class docstring.""" + optional string tags. Returns immediately; see the class docstring. + A blank ``name`` sends nothing. A ``value`` that is NaN, infinite or + not a real number (a string, a bool), and any tag whose key or value + is ``None``, is left out of the event; the event is still sent.""" if self._queue is None: return try: @@ -265,8 +330,13 @@ def close(self, timeout: float = TIMEOUT_SECONDS) -> None: and then exits within milliseconds -- a CLI, a short script -- would otherwise lose its one event to the race between queueing it and the sender thread picking it up. The bound still holds: an unreachable - server costs at most ``timeout``, never a hang. Safe to call more than - once, and on a disabled client.""" + server costs at most ``timeout``, never a hang. Reports still queued + when ``timeout`` runs out are not discarded: the daemon thread keeps + sending them after ``close()`` returns, then stops, and whatever it + has not sent when the program exits is lost. On a full queue the + oldest queued report is dropped (logged at DEBUG) to make room for + the signal that stops the thread. Safe to call more than once, and + on a disabled client.""" if self._queue is None or self._thread is None: return q, thread = self._queue, self._thread @@ -278,7 +348,8 @@ def close(self, timeout: float = TIMEOUT_SECONDS) -> None: # the 257th. Drop the oldest to make room -- one lost report beats a # thread that never stops. try: - q.get_nowait() + dropped = q.get_nowait() + _LOG.debug("[trace] queue full at close, dropped %s", dropped) q.put_nowait(None) except (queue.Empty, queue.Full): pass @@ -307,9 +378,9 @@ def _send(self, body: bytes) -> None: headers={ "Content-Type": "application/json; charset=utf-8", "Authorization": "Bearer " + self._key, - "User-Agent": "trace-client-python/%s (%s)" % (__version__, self._application), + "User-Agent": _user_agent(self._application), }) - with urllib.request.urlopen(request, timeout=self.TIMEOUT_SECONDS) as response: + with _OPENER.open(request, timeout=self.TIMEOUT_SECONDS) as response: status = response.status response.read() except urllib.error.HTTPError as answered: @@ -325,6 +396,14 @@ def _send(self, body: bytes) -> None: _LOG.debug("[trace] trace server answered %s for %s", status, body) +def _user_agent(application: str) -> str: + """The ``User-Agent`` for ``application``. A header carries printable + Latin-1 and nothing else, and one it cannot carry stops the request, so + any other character becomes ``?`` here. The event itself keeps the exact + name: what a program is called must not cost it every report.""" + return "trace-client-python/%s (%s)" % (__version__, _NOT_IN_A_HEADER.sub("?", application)) + + def _with_version(tags: Optional[Mapping[str, str]], version: str) -> Dict[str, str]: """The event's own tags plus ``version``, unless the event already carries one. A copy; the caller's mapping is never modified.""" @@ -348,10 +427,28 @@ def _with_install(tags: Dict[str, str], install_id: Optional[str]) -> Dict[str, return merged +def _number(value: object) -> Optional[float]: + """``value`` as a number JSON can carry, or ``None`` for one it cannot: + anything that is not a real number (a string, a bool), NaN and infinity. + A ``Decimal`` or ``Fraction`` becomes a float rather than costing the + event its place: ``json.dumps`` would refuse it, and the event with it.""" + if isinstance(value, bool) or not isinstance(value, (numbers.Real, decimal.Decimal)): + return None + if type(value) not in (int, float): + try: + value = float(value) + except (OverflowError, ValueError): + return None + if value != value or value in (float("inf"), float("-inf")): + return None + return value # type: ignore[return-value] + + def _json(application: str, name: str, value: Optional[float], tags: Optional[Mapping[str, str]]) -> bytes: payload: Dict[str, object] = {"application": application, "name": name} - if value is not None and value == value and value not in (float("inf"), float("-inf")): - payload["value"] = value + number = _number(value) + if number is not None: + payload["value"] = number if tags: clean = {str(k): str(v) for k, v in tags.items() if k is not None and v is not None} if clean: diff --git a/gardener/usage.py b/gardener/usage.py index 4a16835..062747f 100644 --- a/gardener/usage.py +++ b/gardener/usage.py @@ -25,7 +25,8 @@ contexts where exporting an env var per invocation isn't practical), and a built-in default when neither is set. No new config mechanism is invented. - GARDENER_USAGE_REPORTING_ENABLED default true; 0/false/no/off turns it off + GARDENER_USAGE_REPORTING_ENABLED default (unset) true; anything but + true/on/yes/1 turns it off GARDENER_USAGE_REPORTING_ENDPOINT default https://trace.danielstephenson.dev GARDENER_USAGE_REPORTING_KEY default: the key issued for gardener @@ -34,7 +35,13 @@ variables only (not ``notify.env`` keys) and are checked ahead of gardener's own setting -- here in :func:`enabled` for whichever mapping is passed, and again by the client's constructor against the process environment -- so -they win even when the setting says on. Details: +they win even when the setting says on. + +Every switch fails closed, so an opt-out is never read as on: gardener's own +setting is read through the client's ``allows_reporting``, so once it is set +(in the environment or in ``notify.env``, even to a blank value) only +true/on/yes/1 keeps reporting on; and a ``notify.env`` that exists but cannot +be read turns reporting off, since it may hold the opt-out. Details: https://danielstephenson.dev/usage-reporting The key is a program identifier, not a secret that grants anything, which @@ -56,7 +63,7 @@ from typing import Dict, Mapping, Optional from gardener import __version__, notify, state -from gardener.trace_client import TraceClient, environment_opts_out +from gardener.trace_client import TraceClient, allows_reporting, environment_opts_out APPLICATION = "gardener" DEFAULT_ENDPOINT = "https://trace.danielstephenson.dev" @@ -70,21 +77,19 @@ ENV_INSTALL_ID = "TRACE_INSTALL_ID" INSTALL_ID_FILENAME = "trace-install-id" -_FALSE = {"0", "false", "no", "off"} - - -def _read_config_file(config_path: Optional[Path]) -> Dict[str, str]: - """The ``notify.env`` values, or nothing: a missing or unreadable file is - the normal "not configured" state, never an error (same posture as - `notify.load_webhook_url`).""" +def _read_config_file(config_path: Optional[Path]) -> Optional[Dict[str, str]]: + """The ``notify.env`` values; nothing for a missing file, the normal + "not configured" state; ``None`` for a file that is there but cannot be + read -- it may hold the opt-out, so :func:`enabled` reads that as off + (endpoint and key just fall back to their defaults).""" path = config_path or notify.default_webhook_config_path() try: if not path.is_file(): return {} return notify._parse_env_style_file(path) - except OSError as e: + except (OSError, ValueError) as e: print(f"usage: could not read {path}: {e}", file=sys.stderr) - return {} + return None def _setting(name: str, env: Optional[Mapping[str, str]], config_path: Optional[Path]) -> str: @@ -95,17 +100,30 @@ def _setting(name: str, env: Optional[Mapping[str, str]], config_path: Optional[ value = (source.get(name) or "").strip() if value: return value - return (_read_config_file(config_path).get(name) or "").strip() + return ((_read_config_file(config_path) or {}).get(name) or "").strip() def enabled(env: Optional[Mapping[str, str]] = None, config_path: Optional[Path] = None) -> bool: - """Whether reporting is on. Unset means on; only an explicit no turns it - off -- gardener's own ``GARDENER_USAGE_REPORTING_ENABLED`` (env var or - ``notify.env``), or the client-wide ``TRACE_USAGE_REPORTING`` / - ``DO_NOT_TRACK`` in the environment, which are consulted first.""" - if environment_opts_out(os.environ if env is None else env): + """Whether reporting is on. Fails closed. The client-wide + ``TRACE_USAGE_REPORTING`` / ``DO_NOT_TRACK`` in the environment are + consulted first. Then gardener's own ``GARDENER_USAGE_REPORTING_ENABLED``: + a non-blank env var wins, otherwise ``notify.env``; whichever value is + found is read through ``allows_reporting``, so only true/on/yes/1 keeps + reporting on. A ``notify.env`` that cannot be read is off, and so is the + setting present but blank everywhere. Only when it is set nowhere does the + default, on, apply.""" + source = os.environ if env is None else env + if environment_opts_out(source): + return False + from_env = (source.get(ENV_ENABLED) or "").strip() + if from_env: + return allows_reporting(from_env) + config = _read_config_file(config_path) + if config is None: return False - return _setting(ENV_ENABLED, env, config_path).lower() not in _FALSE + if ENV_ENABLED in config: + return allows_reporting(config[ENV_ENABLED]) + return ENV_ENABLED not in source def endpoint(env: Optional[Mapping[str, str]] = None, config_path: Optional[Path] = None) -> str: @@ -170,7 +188,7 @@ def stop(client: TraceClient, timeout: float = TraceClient.TIMEOUT_SECONDS) -> N Closing matters more here than in a long-running service: the sender is a daemon thread, so process exit would cut it off mid-request, and `gardener status`/`gardener ps` finish in milliseconds. The client's - ``close`` (0.1.1+; 0.4.1 is vendored) gives whatever is still queued up to ``timeout`` + ``close`` (0.1.1+; 0.5.0 is vendored) gives whatever is still queued up to ``timeout`` seconds in total to be sent, then stops the thread — so exit is delayed by at most the client's own timeout: an unreachable trace server is a request that times out, not a hang. Never raises, even on something diff --git a/tests/test_trace_client.py b/tests/test_trace_client.py index 0814550..6a600e2 100644 --- a/tests/test_trace_client.py +++ b/tests/test_trace_client.py @@ -13,7 +13,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from unittest import mock -from gardener.trace_client import MAX_TAG_LENGTH, MAX_TAGS, TraceClient, environment_opts_out +from gardener.trace_client import MAX_TAG_LENGTH, MAX_TAGS, TraceClient, allows_reporting, environment_opts_out _ENV_VARS = ("TRACE_USAGE_REPORTING", "DO_NOT_TRACK") @@ -175,10 +175,13 @@ def test_DO_NOT_TRACK_disables_reporting_for_every_accepted_value(self): self._assert_environment_disables("DO_NOT_TRACK", value) def test_other_environment_values_leave_the_program_setting_in_charge(self): + # 0.5.0 fails closed: only blank, or a value that clearly means "keep + # reporting", leaves the program's own setting in charge. for variable, value in (("TRACE_USAGE_REPORTING", "on"), ("TRACE_USAGE_REPORTING", ""), - ("TRACE_USAGE_REPORTING", "disabled"), ("TRACE_USAGE_REPORTING", "1"), + ("TRACE_USAGE_REPORTING", "1"), ("TRACE_USAGE_REPORTING", "TRUE"), + ("TRACE_USAGE_REPORTING", "yes"), ("DO_NOT_TRACK", "0"), ("DO_NOT_TRACK", ""), ("DO_NOT_TRACK", "false"), - ("DO_NOT_TRACK", "off")): + ("DO_NOT_TRACK", "off"), ("DO_NOT_TRACK", "no")): with mock.patch.dict(os.environ, {variable: value}): self.assertFalse(environment_opts_out(), "%s=%r is not an opt-out" % (variable, value)) client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") @@ -187,6 +190,34 @@ def test_other_environment_values_leave_the_program_setting_in_charge(self): client.close() self.assertFalse(environment_opts_out(), "an unset variable is not an opt-out") + def test_unclear_environment_values_fail_closed(self): + for variable, value in (("TRACE_USAGE_REPORTING", "disabled"), ("TRACE_USAGE_REPORTING", "nope"), + ("TRACE_USAGE_REPORTING", "of"), ("DO_NOT_TRACK", "anything"), + ("DO_NOT_TRACK", "2")): + self._assert_environment_disables(variable, value) + + def test_an_environment_that_cannot_be_read_opts_out(self): + class Unreadable(dict): + def get(self, *args, **kwargs): + raise RuntimeError("no environment") + self.assertTrue(environment_opts_out(Unreadable())) + + def test_allows_reporting_fails_closed(self): + for setting in (True, "true", "TRUE", " on ", "yes", "1"): + self.assertTrue(allows_reporting(setting), "%r allows reporting" % (setting,)) + for setting in (False, None, "", " ", "false", "off", "no", "0", "disabled", '"false"', 0, 1, [], {}): + self.assertFalse(allows_reporting(setting), "%r must not allow reporting" % (setting,)) + + def test_enabled_is_read_through_allows_reporting(self): + for enabled in ("false", "off", "", None, 1, "disabled"): + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k", enabled=enabled) + self.assertFalse(client.enabled, "enabled=%r must not enable the client" % (enabled,)) + self.assertEqual("config", client.disabled_reason) + client.close() + client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k", enabled="yes") + self.assertTrue(client.enabled) + client.close() + def test_environment_wins_over_the_config_flag_and_over_the_key(self): # enabled=True with a key, and the environment still says no. with mock.patch.dict(os.environ, {"TRACE_USAGE_REPORTING": "off"}): @@ -214,12 +245,12 @@ def test_environment_opts_out_accepts_an_explicit_mapping(self): def test_user_agent_names_the_client_version(self): from gardener.trace_client import __version__ - self.assertEqual("0.4.1", __version__) + self.assertEqual("0.5.0", __version__) client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") client.report("startup") self.assertTrue(self.capture.arrived.wait(5)) client.close() - self.assertEqual("trace-client-python/0.4.1 (MyGame)", self.capture.requests[0]["user_agent"]) + self.assertEqual("trace-client-python/0.5.0 (MyGame)", self.capture.requests[0]["user_agent"]) def test_report_ignores_a_blank_name(self): client = TraceClient(self.base_url, "MyGame", "1.2.3", key="k") diff --git a/tests/test_usage.py b/tests/test_usage.py index 8d52dd8..c4124e2 100644 --- a/tests/test_usage.py +++ b/tests/test_usage.py @@ -82,11 +82,20 @@ def test_defaults_are_on_and_point_at_the_production_service(self): self.assertEqual(usage.DEFAULT_KEY, usage.key({})) self.assertTrue(usage.DEFAULT_KEY.strip(), "the bundled key must not be blank") - def test_only_an_explicit_no_turns_it_off(self): - for value in ("0", "false", "FALSE", "no", "off", " Off "): - self.assertFalse(usage.enabled({usage.ENV_ENABLED: value}), value) - for value in ("", "1", "true", "yes", "anything"): - self.assertTrue(usage.enabled({usage.ENV_ENABLED: value}), repr(value)) + def test_the_setting_fails_closed(self): + for value in ("0", "false", "FALSE", "no", "off", " Off ", "", " ", "anything", "disabled", '"false"'): + self.assertFalse(usage.enabled({usage.ENV_ENABLED: value}, self.config_path), repr(value)) + for value in ("1", "true", " TRUE ", "yes", "on"): + self.assertTrue(usage.enabled({usage.ENV_ENABLED: value}, self.config_path), repr(value)) + + def test_the_notify_env_setting_fails_closed_too(self): + for value in ("", "anything", "off", "0"): + self.config_path.write_text(f"{usage.ENV_ENABLED}={value}\n") + self.assertFalse(usage.enabled({}, self.config_path), repr(value)) + # A blank env var falls through to the file, never past it to the default. + self.assertFalse(usage.enabled({usage.ENV_ENABLED: " "}, self.config_path), repr(value)) + self.config_path.write_text(f"{usage.ENV_ENABLED}=yes\n") + self.assertTrue(usage.enabled({}, self.config_path)) def test_the_client_wide_variables_turn_it_off_even_when_gardener_says_on(self): for variable, value in (("TRACE_USAGE_REPORTING", "off"), ("TRACE_USAGE_REPORTING", "FALSE"), @@ -94,7 +103,10 @@ def test_the_client_wide_variables_turn_it_off_even_when_gardener_says_on(self): ("DO_NOT_TRACK", "1"), ("DO_NOT_TRACK", "true"), ("DO_NOT_TRACK", "yes")): env = {usage.ENV_ENABLED: "true", variable: value} self.assertFalse(usage.enabled(env), f"{variable}={value}") - # Only the listed values count; anything else leaves gardener's setting in charge. + # Fails closed: anything but blank or a clear "keep reporting" opts out. + for variable, value in (("TRACE_USAGE_REPORTING", "disabled"), ("DO_NOT_TRACK", "anything")): + self.assertFalse(usage.enabled({usage.ENV_ENABLED: "true", variable: value}), f"{variable}={value}") + # Blank or a clear "on" leaves gardener's setting in charge. for variable, value in (("TRACE_USAGE_REPORTING", ""), ("TRACE_USAGE_REPORTING", "on"), ("DO_NOT_TRACK", "0"), ("DO_NOT_TRACK", "")): self.assertTrue(usage.enabled({variable: value}), f"{variable}={value!r}") @@ -135,19 +147,27 @@ def test_settings_fall_back_to_notify_env_under_the_state_dir(self): # And a blank env var falls through to the file rather than clearing it. self.assertEqual("file-key", usage.key({usage.ENV_KEY: " "})) - def test_a_missing_or_unreadable_config_file_means_defaults(self): + def test_a_missing_config_file_means_defaults_and_an_unreadable_one_means_off(self): self.assertFalse(self.config_path.exists()) self.assertTrue(usage.enabled({})) self.assertEqual(usage.DEFAULT_KEY, usage.key({})) self.config_path.mkdir() # a directory: is_file() is False, so "not configured" self.assertTrue(usage.enabled({})) + self.config_path.rmdir() + self.config_path.write_text(f"{usage.ENV_ENABLED}=false\n") + for error in (OSError("nope"), UnicodeDecodeError("utf-8", b"\xff", 0, 1, "bad")): + with patch("gardener.usage.notify._parse_env_style_file", side_effect=error): + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + # It may hold the opt-out (it does here), so it is read as off ... + self.assertFalse(usage.enabled({})) + # ... while endpoint and key just fall back to their defaults. + self.assertEqual(usage.DEFAULT_KEY, usage.key({})) + self.assertIn("could not read", stderr.getvalue()) + # An explicit "on" in the environment is the operator's own action and wins. with patch("gardener.usage.notify._parse_env_style_file", side_effect=OSError("nope")): - self.config_path.rmdir() - self.config_path.write_text(f"{usage.ENV_ENABLED}=false\n") - stderr = io.StringIO() - with contextlib.redirect_stderr(stderr): - self.assertTrue(usage.enabled({})) - self.assertIn("could not read", stderr.getvalue()) + with contextlib.redirect_stderr(io.StringIO()): + self.assertTrue(usage.enabled({usage.ENV_ENABLED: "true"})) def test_disabled_builds_a_client_that_sends_nothing(self): client = usage.build_client({usage.ENV_ENABLED: "false"})