From 5882a6f69b701b16edb46b4e8c4b4813c5d88d53 Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 16:58:48 +0000 Subject: [PATCH 01/23] #216 fix: a cookie jar per command, not per worker MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Operator call 1A. The fetch client's jar lived for the worker's lifetime, so one command's Set-Cookie rode every later command to the same host — a credentialed fetch's session would ride an anonymous one. CommandScopeTransport, outermost over the guard, reads the command's scope from a ContextVar the handler sets around _fetch. Cookies live in the scope for one redirect chain; the client's own jar never stores. A hop with no scope is refused (RuntimeError). Each hop goes out on a copy of the request, because httpx builds the next hop from the handed one. The §7 "no server framework" detector named the whole stdlib http package; it now names http.server, so http.cookiejar (the never-storing jar's policy) is allowed. Planted-import tests pin both halves. Co-Authored-By: Claude Opus 5.5 --- src/worker/egress.py | 84 +++++++++++++++++++++- src/worker/handler.py | 10 +-- src/worker/main.py | 16 ++++- tests/test_boundaries.py | 52 +++++++++++++- tests/worker/test_egress.py | 135 ++++++++++++++++++++++++++++++++++++ tests/worker/test_main.py | 41 +++++++++-- 6 files changed, 321 insertions(+), 17 deletions(-) diff --git a/src/worker/egress.py b/src/worker/egress.py index 5c88d10c..07ea0d96 100644 --- a/src/worker/egress.py +++ b/src/worker/egress.py @@ -48,12 +48,26 @@ sits inside the guard on the same client, for the same reason it is a transport: the driver reads every hop's body whole, and this is the one place a body passes before that. It stops reading at ``REPLICATOR_MAX_BLOB_BYTES``. + +**And what one command's hops may carry (#216).** :class:`CommandScopeTransport` +sits outside the guard and reads the command's :class:`CommandScope` from a +``ContextVar`` the handler sets around the fetch. A hop with no scope is refused, +so nothing reaches the wire unaccounted for. Cookies live in the scope, for one +command's redirect chain: the client's own jar never stores +(:func:`never_storing_cookies`), so one command's ``Set-Cookie`` never rides +another's request. A ``ContextVar`` and not a client per command because co-core's +driver builds the request and httpx follows redirects in the calling task, so the +value set around ``_fetch`` holds on every hop. """ import asyncio +import http.cookiejar import ipaddress import socket -from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Sequence +from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Iterator, Sequence +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass, field import httpx @@ -285,6 +299,74 @@ async def aclose(self) -> None: await self._inner.aclose() +@dataclass(frozen=True, slots=True) +class CommandScope: + """What one command's hops share: its cookies, and nothing past the command (#216).""" + + cookies: httpx.Cookies = field(default_factory=httpx.Cookies) + + +_COMMAND_SCOPE: ContextVar[CommandScope | None] = ContextVar("command_scope", default=None) + + +@contextmanager +def command_scope() -> Iterator[CommandScope]: + """Enter a fresh scope for one command's fetch, and leave it even when the fetch raises.""" + scope = CommandScope() + token = _COMMAND_SCOPE.set(scope) + try: + yield scope + finally: + _COMMAND_SCOPE.reset(token) + + +def never_storing_cookies() -> http.cookiejar.CookieJar: + """The client's jar: one whose policy admits no domain, so it never stores a cookie. + + The scope's cookies replace it. Left as httpx's default, it lived for the + worker's lifetime and replayed one command's session on every later command to + the same host (operator call 1A). + """ + return http.cookiejar.CookieJar(policy=http.cookiejar.DefaultCookiePolicy(allowed_domains=[])) + + +class CommandScopeTransport(httpx.AsyncBaseTransport): + """Send each hop as its command's scope allows, on a copy of the request (#216). + + **A copy, never the request handed in.** httpx builds the next hop from the + previous request's headers (``_build_redirect_request``, 0.28.1), so anything + set on the handed request would ride every later hop, a cross-origin one + included [measured 2026-11-23]. + + **Cookies** are the scope's: added before the hop with httpx's public + ``set_cookie_header``, which leaves a ``Cookie`` the issuer sent alone, as the + client's jar did, and taken from the response with ``extract_cookies``. + """ + + def __init__(self, inner: httpx.AsyncBaseTransport) -> None: + self._inner = inner + + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + scope = _COMMAND_SCOPE.get() + if scope is None: + raise RuntimeError(f"{request.url} was requested outside a command scope: refused") + outgoing = httpx.Request( + request.method, + request.url, + headers=request.headers.copy(), + stream=request.stream, + extensions=request.extensions, + ) + scope.cookies.set_cookie_header(outgoing) + response = await self._inner.handle_async_request(outgoing) + response.request = outgoing + scope.cookies.extract_cookies(response) + return response + + async def aclose(self) -> None: + await self._inner.aclose() + + class BodyCeilingTransport(httpx.AsyncBaseTransport): """Stop reading a body at the blob ceiling, rather than after its last byte (#104). diff --git a/src/worker/handler.py b/src/worker/handler.py index b1c6bae9..eabbbd76 100644 --- a/src/worker/handler.py +++ b/src/worker/handler.py @@ -38,6 +38,7 @@ from src.core.logging import get_logger from src.storage.sweeper import BlobUsage from src.worker.browser import RenderDeadlineError +from src.worker.egress import command_scope from src.worker.loop import Handler, park from src.worker.pacing import HostPacer, HostPolicy @@ -744,10 +745,11 @@ async def _fetch( to finish on its own, as #100 already accepts. """ try: - async with asyncio.timeout(deadline_seconds) as deadline: - return await fetcher.execute( - FetchContent(command.url, headers=options.headers, timeout=options.timeout) - ) + with command_scope(): + async with asyncio.timeout(deadline_seconds) as deadline: + return await fetcher.execute( + FetchContent(command.url, headers=options.headers, timeout=options.timeout) + ) except (httpx.UnsupportedProtocol, httpx.InvalidURL) as exc: raise PermanentFetchError( f"{command.url} is not fetchable: {exc}", reason=FailureReason.NOT_FETCHABLE diff --git a/src/worker/main.py b/src/worker/main.py index 86ff729f..45cd8aa8 100644 --- a/src/worker/main.py +++ b/src/worker/main.py @@ -50,9 +50,11 @@ from src.worker.checkout import checkout_refusal from src.worker.egress import ( BodyCeilingTransport, + CommandScopeTransport, DestinationGuard, GuardedTransport, blocked_networks, + never_storing_cookies, ) from src.worker.handler import build_handler from src.worker.loop import ( @@ -119,12 +121,20 @@ def build_fetch_client(settings: Settings) -> httpx.AsyncClient: ``response.content`` can no longer hold more than the handler will keep. Inside rather than outside so a refused destination is refused before any response exists to count. + + **Outside the guard, the command scope** (#216): each hop reads its command's + scope, and cookies live there for one command's redirect chain. The client's + own jar never stores, which is what makes them per command rather than per + worker. Outermost so a scope refusal costs no DNS lookup. """ return httpx.AsyncClient( - transport=GuardedTransport( - BodyCeilingTransport(httpx.AsyncHTTPTransport(), max_bytes=settings.max_blob_bytes), - blocked=blocked_networks(settings.blocked_destination_cidrs), + transport=CommandScopeTransport( + GuardedTransport( + BodyCeilingTransport(httpx.AsyncHTTPTransport(), max_bytes=settings.max_blob_bytes), + blocked=blocked_networks(settings.blocked_destination_cidrs), + ) ), + cookies=never_storing_cookies(), follow_redirects=True, ) diff --git a/tests/test_boundaries.py b/tests/test_boundaries.py index 98c5c1e6..bf69f48d 100644 --- a/tests/test_boundaries.py +++ b/tests/test_boundaries.py @@ -1203,8 +1203,32 @@ def test_the_import_time_detector_scans_class_bodies_but_not_functions(): # admin listener grows inside src/worker/ — the exact thing the rejected fourth # channel is about. SERVER_MODULES = frozenset( - {"fastapi", "uvicorn", "starlette", "aiohttp", "flask", "http", "socketserver", "wsgiref"} + {"fastapi", "uvicorn", "starlette", "aiohttp", "flask", "socketserver", "wsgiref"} ) +# The standard library's ``http`` package is half client: ``http.cookiejar`` is what +# the fetch client's never-storing jar is built from (#216). So the server half is +# named by its dotted path rather than the whole package refused. +SERVER_SUBMODULES = frozenset({"http.server"}) + + +def _server_imports(tree: ast.Module) -> set[str]: + """The server modules ``tree`` imports, by package or by dotted submodule.""" + found: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + names = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom) and node.module and not node.level: + # ``from http import server`` imports ``http.server`` too. + names = [node.module, *(f"{node.module}.{alias.name}" for alias in node.names)] + else: + continue + for name in names: + if name.split(".")[0] in SERVER_MODULES: + found.add(name.split(".")[0]) + found.update( + sub for sub in SERVER_SUBMODULES if name == sub or name.startswith(f"{sub}.") + ) + return found def test_the_worker_imports_no_server_framework(): @@ -1212,13 +1236,35 @@ def test_the_worker_imports_no_server_framework(): assert files, f"no modules found under {WORKER} — the scan is a no-op" offenders = { - path.relative_to(REPO).as_posix(): sorted(SERVER_MODULES & _imported_modules(_parse(path))) + path.relative_to(REPO).as_posix(): sorted(_server_imports(_parse(path))) for path in files - if SERVER_MODULES & _imported_modules(_parse(path)) + if _server_imports(_parse(path)) } assert not offenders +@pytest.mark.parametrize( + "source", + [ + "import http.server", + "from http import server", + "from http.server import HTTPServer", + "from http import cookiejar, server", + "import uvicorn", + "from fastapi import FastAPI", + ], +) +def test_the_server_detector_catches_a_planted_import(source): + assert _server_imports(ast.parse(source)) + + +@pytest.mark.parametrize( + "source", ["import http.cookiejar", "from http import HTTPStatus", "import httpx"] +) +def test_the_server_detector_passes_the_client_half_of_http(source): + assert not _server_imports(ast.parse(source)) + + def test_the_unit_starts_the_worker_and_binds_no_port(): unit = UNIT.read_text() diff --git a/tests/worker/test_egress.py b/tests/worker/test_egress.py index 51181209..0d9932c5 100644 --- a/tests/worker/test_egress.py +++ b/tests/worker/test_egress.py @@ -40,8 +40,11 @@ DEFAULT_BLOCKED_DESTINATIONS, RESOLVE_TIMEOUT_SECONDS, BodyCeilingTransport, + CommandScopeTransport, GuardedTransport, blocked_networks, + command_scope, + never_storing_cookies, ) from tests.worker.conftest import command @@ -863,3 +866,135 @@ async def test_an_endless_non_2xx_body_from_a_real_origin_is_cut_short(endless_o assert response.status_code == 503 assert len(response.content) == ceiling + + +# --- The command scope (#216): cookies live for one command's redirect chain --------- + + +def _scoped_client(origin) -> httpx.AsyncClient: + """The worker's stack minus the guard and the ceiling: scope over a mock origin.""" + return httpx.AsyncClient( + transport=CommandScopeTransport(httpx.MockTransport(origin)), + cookies=never_storing_cookies(), + follow_redirects=True, + ) + + +def _cookie_origin(seen: list[tuple[str, str | None]]): + """``/bounce`` sets a cookie on a 302 to ``/land``; ``/plant`` sets one on a 200.""" + + def origin(request: httpx.Request) -> httpx.Response: + seen.append((request.url.path, request.headers.get("cookie"))) + if request.url.path == "/bounce": + return httpx.Response( + 302, headers={"location": "/land", "set-cookie": "sid=abc; Path=/"} + ) + if request.url.path == "/plant": + return httpx.Response(200, headers={"set-cookie": "planted=1; Path=/"}) + return httpx.Response(200, text="ok") + + return origin + + +async def test_a_cookie_set_on_a_redirect_reaches_the_next_hop(): + """Today's behaviour, kept: a session minted on a 302 is sent on the hop it points at.""" + seen: list[tuple[str, str | None]] = [] + + async with _scoped_client(_cookie_origin(seen)) as client: + with command_scope(): + await AsyncFetchDriver(client).execute(FetchContent("https://a.example/bounce")) + + assert seen == [("/bounce", None), ("/land", "sid=abc")] + + +async def test_a_cookie_from_one_command_never_reaches_the_next(): + """The behaviour change (operator call 1A): the worker-lifetime jar is gone. + + Before, one command's ``Set-Cookie`` was replayed on every later command to the + same host, so a credentialed fetch's session would ride an anonymous one. + """ + seen: list[tuple[str, str | None]] = [] + + async with _scoped_client(_cookie_origin(seen)) as client: + driver = AsyncFetchDriver(client) + with command_scope(): + await driver.execute(FetchContent("https://a.example/plant")) + with command_scope(): + await driver.execute(FetchContent("https://a.example/later")) + + assert seen[-1] == ("/later", None) + + +async def test_the_client_jar_stores_nothing(): + """The per-command cookies are the only ones: the client's jar never fills.""" + async with _scoped_client(_cookie_origin([])) as client: + with command_scope(): + await AsyncFetchDriver(client).execute(FetchContent("https://a.example/bounce")) + + assert len(client.cookies.jar) == 0 + + +async def test_a_hop_outside_any_command_scope_is_refused(): + """Fails closed: nothing reaches the wire without a scope to read it against.""" + async with _scoped_client(_never_called) as client: + with pytest.raises(RuntimeError, match="outside a command scope"): + await client.get("https://a.example/") + + +async def test_the_scope_is_gone_after_the_command_even_when_it_raises(): + with pytest.raises(ValueError), command_scope(): + raise ValueError("the fetch failed") + + async with _scoped_client(_never_called) as client: + with pytest.raises(RuntimeError, match="outside a command scope"): + await client.get("https://a.example/") + + +async def test_the_request_handed_down_is_never_mutated(): + """httpx builds the next hop from the request it handed in, headers and all. + + So whatever the transport adds must go on a copy, or it rides every later hop + including a cross-origin one [measured 2026-11-23, httpx 0.28.1]. + """ + seen: list[httpx.Request] = [] + + def origin(request: httpx.Request) -> httpx.Response: + seen.append(request) + return httpx.Response(200) + + transport = CommandScopeTransport(httpx.MockTransport(origin)) + handed = httpx.Request("GET", "https://a.example/", headers={"accept": "text/html"}) + with command_scope() as scope: + scope.cookies.set("sid", "abc", domain="a.example") + await transport.handle_async_request(handed) + + assert seen[0].headers["cookie"] == "sid=abc" + assert seen[0].headers["accept"] == "text/html" + assert "cookie" not in handed.headers + + +async def test_an_issuers_own_cookie_header_is_sent_as_given(): + """As httpx's jar did: a ``Cookie`` already on the request is left alone.""" + seen: list[tuple[str, str | None]] = [] + + async with _scoped_client(_cookie_origin(seen)) as client: + with command_scope() as scope: + scope.cookies.set("sid", "abc", domain="a.example") + await client.get("https://a.example/land", headers={"cookie": "mine=1"}) + + assert seen == [("/land", "mine=1")] + + +async def test_every_command_the_handler_runs_has_its_own_scope(handler): + """The handler enters the scope, so the worker's client never refuses a real command. + + And it is a fresh one each time: the second command carries none of the first's cookies. + """ + seen: list[tuple[str, str | None]] = [] + + async with _scoped_client(_cookie_origin(seen)) as client: + handle = handler(AsyncFetchDriver(client)) + await handle(command(command_id="cmd-1", url="https://a.example/plant")) + await handle(command(command_id="cmd-2", url="https://a.example/later")) + + assert seen == [("/plant", None), ("/later", None)] diff --git a/tests/worker/test_main.py b/tests/worker/test_main.py index 83285341..b50c47c9 100644 --- a/tests/worker/test_main.py +++ b/tests/worker/test_main.py @@ -36,7 +36,12 @@ from src.core.logging import configure_logging from src.storage.local_store import SweepSafeLocalBlobStore from src.storage.sweeper import SweepResult -from src.worker.egress import RESOLVE_TIMEOUT_SECONDS, BodyCeilingTransport, GuardedTransport +from src.worker.egress import ( + RESOLVE_TIMEOUT_SECONDS, + BodyCeilingTransport, + CommandScopeTransport, + GuardedTransport, +) from src.worker.main import ( build_consumer, build_fetch_client, @@ -613,7 +618,8 @@ def __init__(self, client): # The run() seam passes the guarded client (#95); a stub that took # no argument would make this test pass while the worker fetched # through an unguarded one. - assert isinstance(client._transport, GuardedTransport) + assert isinstance(client._transport, CommandScopeTransport) + assert isinstance(client._transport._inner, GuardedTransport) clients.append(client) async def execute(self, effect): @@ -1646,19 +1652,42 @@ def test_the_worker_builds_its_fetch_client_behind_the_destination_guard(monkeyp # that renames it fails here loudly, which is the right failure: it means # nothing is checking that the worker's client is the guarded one. assert isinstance(client, httpx.AsyncClient) - assert isinstance(client._transport, GuardedTransport) + assert isinstance(client._transport._inner, GuardedTransport) assert client.follow_redirects is True, ( "redirects stay on — the guard checks each hop rather than refusing the feature" ) +def test_the_worker_scopes_every_hop_to_its_command_outermost(monkeypatch): + """#216: the scope transport wraps the guard, and the client's own jar never stores. + + Outermost so a credential out of scope is refused before a DNS lookup (operator + call 5). The never-storing jar is what makes cookies per command (call 1A): the + scope's cookies are then the only ones a hop carries. + """ + monkeypatch.delenv("REPLICATOR_BLOCKED_DESTINATIONS", raising=False) + + client = build_fetch_client(Settings()) + + assert isinstance(client._transport, CommandScopeTransport) + assert isinstance(client._transport._inner, GuardedTransport) + client.cookies.extract_cookies( + httpx.Response( + 200, + headers={"set-cookie": "sid=abc; Path=/"}, + request=httpx.Request("GET", "https://a.example/"), + ) + ) + assert len(client.cookies.jar) == 0 + + def test_the_operators_ranges_reach_the_worker_guard(monkeypatch): """A configured table is the one the worker enforces, not just the one it parses.""" monkeypatch.setenv("REPLICATOR_BLOCKED_DESTINATIONS", "10.0.0.0/8") client = build_fetch_client(Settings()) - assert [str(net) for net in client._transport._guard._blocked] == ["10.0.0.0/8"] + assert [str(net) for net in client._transport._inner._guard._blocked] == ["10.0.0.0/8"] def test_the_worker_guard_resolves_under_the_budgeted_cap(monkeypatch): @@ -1674,7 +1703,7 @@ def test_the_worker_guard_resolves_under_the_budgeted_cap(monkeypatch): client = build_fetch_client(Settings()) - assert client._transport._guard._resolve_timeout == RESOLVE_TIMEOUT_SECONDS + assert client._transport._inner._guard._resolve_timeout == RESOLVE_TIMEOUT_SECONDS def test_the_worker_stops_reading_a_body_at_the_blob_ceiling(monkeypatch): @@ -1687,7 +1716,7 @@ def test_the_worker_stops_reading_a_body_at_the_blob_ceiling(monkeypatch): client = build_fetch_client(Settings()) - guard = client._transport + guard = client._transport._inner assert isinstance(guard, GuardedTransport) inner = guard._inner assert isinstance(inner, BodyCeilingTransport) From a5ec7fa501c4e75188f3229c73cf5df6aaf4c1d6 Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 17:02:09 +0000 Subject: [PATCH 02/23] #216 refactor: the request-header rules move to src/worker/headers.py Unchanged rules, now public names: HEADER_NAME, HEADER_VALUE, REFUSED_HEADERS, REFUSED_HEADER_PREFIX and the two bounds. The fetch credential table checks a binding's header and value against the same rules the handler applies to `headers`, and the handler will import the table, so the rules can't stay in handler.py without a cycle. Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 1 + docs/STREAMS.md | 2 +- src/worker/handler.py | 107 +++---------------- src/worker/headers.py | 97 +++++++++++++++++ tests/worker/test_handler_request_options.py | 8 +- tests/worker/test_handler_tls.py | 2 +- 6 files changed, 117 insertions(+), 100 deletions(-) create mode 100644 src/worker/headers.py diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 37433ebf..5ad26382 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -37,6 +37,7 @@ src/worker/ — Bus consumer; the primary process src/worker/main.py — Entry point: client lifetime, consumer group, signals, backend selection src/worker/loop.py — The consume path: poll → dispatch → ack, DLQ, dedupe, recovery; one loop per command stream, parameterized by CommandSpec src/worker/handler.py — The byte path behind the Handler seam: fetch → fingerprint → store → publish +src/worker/headers.py — The request-header rules: names, values, the refused set, the count and byte bounds; shared by the handler's `headers` guards and the fetch credential table (#11, #216) src/worker/egress.py — The destination guard: a transport refusing loopback, private, tailnet and IANA special-purpose addresses per redirect hop (#95, #161); an answer it cannot check retries, never passes (#100). Beside it, the body ceiling: every hop's body counted on the wire and not read past `REPLICATOR_MAX_BLOB_BYTES` (#104) src/worker/browser.py — The renderer behind the Renderer seam: one pinned headless Chromium per render, sandboxed, scrubbed env, one at a time; a screenshot (render) or the serialized document (load, #63); says what happened to the page, never the wire reason (#138) src/worker/browser_fetch.py — BrowserFetcher, the Fetcher behind render="browser": load → a FetchResult describing the stored document, render errors in fetch's vocabulary (#63) diff --git a/docs/STREAMS.md b/docs/STREAMS.md index 44706cf1..dc1bfce5 100644 --- a/docs/STREAMS.md +++ b/docs/STREAMS.md @@ -24,7 +24,7 @@ what each stream carries is here: - **The alias is a selector and the guards are allow-lists.** `credentials_alias` names a binding an operator provisioned on *this host* (`src/worker/aliases.py`, from `REPLICATOR_REPLICATION_ALIASES_FILE`); unset means nothing is provisioned and everything is refused, which is the current state of every host and the safe default under T5. Guard order is load-bearing and asserted: alias → provider → the alias's own writer → destination → source, so every refusal happens **before any credential is touched** (T1) — observable for the first time now that there is a driver call to precede. **The writers are keyed by alias, not by provider** (CR #26): `AsyncGcsDriver` takes a bucket in its constructor and never sees another, so a driver *is* a bucket and the key has to be whatever selects one — keyed by provider, two `gcs` bindings collapsed onto a single driver and a command could land in a bucket its binding never named, outside the very T3 root `validate_destination` had just checked. A binding whose driver cannot be built (ADC resolves in that constructor) is **skipped and logged, never raised**, because `load_alias_table` promises one line earlier that a replicate misconfiguration will not take down a worker whose actual job is `content.fetch`; the alias is then refused `provider_disabled`, whose remedy is the operator act that fixes it. The blob reaches the driver as a **seekable binary stream** from `BlobStore.open_stream`, not as bytes or a path: a path would make the provider copy something already on disk, bytes would pull a whole artifact into memory, and seekable is required because the driver reads the local md5 only on the 412 path, after the failed create has moved the position. **`blob_uri` is never resolved as a path** — the fingerprint is extracted, validated as 64 lowercase hex, and compared against `uri_for()` of each store this host reads — the temp store, and since #114 the permanent store if `REPLICATOR_PERMANENT_BUCKET` names one — so the only string reaching storage is one a store built, and the bytes come from the store that matched. That is T3a, and it is sharper than the destination guard it was added beside: `file:///etc/replicator/co-pypi-reader.json` as a `blob_uri` would otherwise publish this host's GCS reader key to a permanent, public, undeletable store. `invalid_source` and `blob_expired` stay distinct because only the second is fixed by fetching again. Two charter invariants enforce the rest: the alias is a key and never a value, and no payload field feeds a credential-shaped parameter. - **The failure fact is a seam, not a call in the loop.** `FailureReporter` is injected exactly as `Handler` is, so `loop.py` stays ignorant of `content.blobs` and `blobs_topic` stays a defaulted argument a live-broker test can move. The loop owns the *decision* (`terminal` is "did this hit the delivery ceiling", which only the loop knows); the reporter owns the *publish*. `_close()` publishes then dead-letters, so **fact-before-ack** cannot be got wrong one call site at a time — `dead_letter` acks inside itself, and a fact published after it is lost outright on a crash. A failed fact-publish is **swallowed**, deliberately asymmetric with the byte path's `_publish`: there raising prevents an orphan blob, here the DLQ entry is already the durable record and raising would burn the delivery ceiling to reach the same DLQ minutes later. -- **A command shapes its own fetch, and everything unsendable is refused rather than fixed.** `headers` and `timeout_seconds` (#11, cannobserv#272 — v0.7.3) reach the driver as `FetchContent.headers` / `.timeout`; omitted means the pre-#11 wire byte-for-byte. Header names are **lower-cased before the merge** — `AsyncFetchDriver` merges `{"user-agent": DEFAULT, **effect.headers}` case-*sensitively*, and httpx does not resolve the collision: an unfolded `User-Agent` puts **two** field lines on the wire, default first, for the origin to disambiguate (measured, not inferred). That is exactly the fingerprint-continuity case Watcher needs at cutover. Refusals are **`PermanentFetchError(INVALID_REQUEST_OPTIONS)` raised before the fetch**: hop-by-hop and httpx-derived names (`host`, `content-length`, `proxy-*`, …), non-token names (padding included — OWS is a *value* rule, not a name one), values outside **printable US-ASCII**, case-collisions, over `MAX_REQUEST_HEADERS`/`MAX_REQUEST_HEADER_BYTES`, and a timeout that is non-finite, ≤ 0, or over `REPLICATOR_MAX_FETCH_TIMEOUT_SECONDS`. The timeout is httpx's, so it bounds each operation, not the fetch; the whole fetch is bounded separately by the operator's `REPLICATOR_MAX_FETCH_SECONDS` (#104), and exceeding that retries like any timeout. Refused, never stripped or clamped — same argument as dropping an over-long passthrough rather than truncating it: a change to the fetch the issuer cannot see is one it cannot account for in its own fingerprints. **The value charset is pinned to what httpx can actually send, not to RFC 9110** — see `_HEADER_VALUE`'s comment for why each edge sits where it does (CR #1). The rule the guard exists to enforce: a value httpx refuses does not fail as a classified fetch error, so an unguarded one closes the command under the wrong reason or retries forever. `tests/worker/test_handler_request_options.py` walks the whole single-byte range against `httpx.Request` so the two cannot drift again. Validation runs **ahead of the storage ceiling** so a permanently-bad command does not park in the PEL waiting for a sweep. Header **names only** are logged, never values. `src/worker/handler.py::_request_options`. +- **A command shapes its own fetch, and everything unsendable is refused rather than fixed.** `headers` and `timeout_seconds` (#11, cannobserv#272 — v0.7.3) reach the driver as `FetchContent.headers` / `.timeout`; omitted means the pre-#11 wire byte-for-byte. Header names are **lower-cased before the merge** — `AsyncFetchDriver` merges `{"user-agent": DEFAULT, **effect.headers}` case-*sensitively*, and httpx does not resolve the collision: an unfolded `User-Agent` puts **two** field lines on the wire, default first, for the origin to disambiguate (measured, not inferred). That is exactly the fingerprint-continuity case Watcher needs at cutover. Refusals are **`PermanentFetchError(INVALID_REQUEST_OPTIONS)` raised before the fetch**: hop-by-hop and httpx-derived names (`host`, `content-length`, `proxy-*`, …), non-token names (padding included — OWS is a *value* rule, not a name one), values outside **printable US-ASCII**, case-collisions, over `MAX_REQUEST_HEADERS`/`MAX_REQUEST_HEADER_BYTES`, and a timeout that is non-finite, ≤ 0, or over `REPLICATOR_MAX_FETCH_TIMEOUT_SECONDS`. The timeout is httpx's, so it bounds each operation, not the fetch; the whole fetch is bounded separately by the operator's `REPLICATOR_MAX_FETCH_SECONDS` (#104), and exceeding that retries like any timeout. Refused, never stripped or clamped — same argument as dropping an over-long passthrough rather than truncating it: a change to the fetch the issuer cannot see is one it cannot account for in its own fingerprints. **The value charset is pinned to what httpx can actually send, not to RFC 9110** — see `HEADER_VALUE`'s comment (`src/worker/headers.py`) for why each edge sits where it does (CR #1). The rule the guard exists to enforce: a value httpx refuses does not fail as a classified fetch error, so an unguarded one closes the command under the wrong reason or retries forever. `tests/worker/test_handler_request_options.py` walks the whole single-byte range against `httpx.Request` so the two cannot drift again. Validation runs **ahead of the storage ceiling** so a permanently-bad command does not park in the PEL waiting for a sweep. Header **names only** are logged, never values. `src/worker/handler.py::_request_options`. - **Per-host politeness is enforced here and decided elsewhere, and `content.fetch-policy` — the third stream kind, read groupless — carries the numbers.** How a wait is spent, how the policy stream is replayed and tailed, and when a 429 or 503 escalates a host: [POLITENESS.md](POLITENESS.md). - **The timeout ceiling and the unit's `TimeoutStopSec` are one decision.** A command's own timeout replaced the driver's fixed 30 s as the handler's worst-case budget, and SIGTERM waits out the message in flight, so `TimeoutStopSec` must exceed a poll, a pacing sleep, the slowest fetch and a store (#7). **The fetch term is `REPLICATOR_MAX_FETCH_SECONDS` since #104**, one deadline around the whole fetch — the guard's resolve (#100) included, which was a fifth term until then. Before it the sum carried the per-operation timeout, which httpx applies to each read separately, so a trickling body or a redirect chain ran past the sum and a deploy SIGKILLed it partway. `tests/test_deploy.py` sums the four, 160 s of 180. An in-flight sweep is not summed: it runs only on `local`, the store term only on `gcs`. diff --git a/src/worker/handler.py b/src/worker/handler.py index eabbbd76..95558600 100644 --- a/src/worker/handler.py +++ b/src/worker/handler.py @@ -9,7 +9,6 @@ import asyncio import math -import re import ssl from collections.abc import Awaitable from datetime import UTC, datetime, timedelta @@ -39,6 +38,14 @@ from src.storage.sweeper import BlobUsage from src.worker.browser import RenderDeadlineError from src.worker.egress import command_scope +from src.worker.headers import ( + HEADER_NAME, + HEADER_VALUE, + MAX_REQUEST_HEADER_BYTES, + MAX_REQUEST_HEADERS, + REFUSED_HEADER_PREFIX, + REFUSED_HEADERS, +) from src.worker.loop import Handler, park from src.worker.pacing import HostPacer, HostPolicy @@ -112,94 +119,6 @@ # sent on the document alone, it would silently fall off at the first redirect. _BROWSER_HEADERS = frozenset({"user-agent"}) -# How many request headers a command may carry, and how many bytes they may add -# up to on the wire (#11). -# -# Deliberately not MAX_HEADER_VALUE_LENGTH, which reasons about *response* -# passthroughs riding a broadcast stream nothing trims — a different argument -# that happens to land on a similar number. This bound is about what an origin -# will accept: 8 KiB is the common server-side limit (nginx's -# large_client_header_buffers, Apache's LimitRequestFieldSize), so exceeding it -# earns an opaque 400 from the far end. Refusing locally turns that into a named -# reason on a fact the issuer already consumes. -# -# Constants rather than settings: these bound an unauthenticated capability, and -# a per-deployment knob is an invitation to loosen the one thing standing between -# a bus writer and an arbitrary request. -MAX_REQUEST_HEADERS = 32 -MAX_REQUEST_HEADER_BYTES = 8192 - -# Request headers Replicator will not send on an issuer's behalf. -# -# Two groups, refused for different reasons and listed together because the -# refusal is the same. The hop-by-hop set (RFC 9110 §7.6.1) describes a single -# connection, not the request — httpx and h11 own it, and an issuer's value is -# either ignored or corrupts the framing. `host` and `content-length` are not -# hop-by-hop: httpx derives both, and overriding `host` in particular points the -# request at one origin while addressing another (domain fronting) — precisely -# the widening the contract's trust model says the broker, not this list, is -# holding back. -# -# **Refused, not stripped.** Silently dropping one changes what the origin saw -# with nothing the issuer can observe, which is the same failure the -# reject-not-truncate rule exists to prevent, applied to the request side. It is -# also the conservative direction: relaxing a refusal to a strip later stays -# compatible, tightening a strip into a refusal does not. -REFUSED_HEADERS = frozenset( - { - "connection", - "content-length", - "host", - "keep-alive", - "proxy-connection", - "te", - "trailer", - "transfer-encoding", - "upgrade", - } -) - -# Every Proxy-* header, refused as a family: they configure the hop rather than -# the request, and enumerating them would date the list. -_REFUSED_HEADER_PREFIX = "proxy-" - -# A field name is an RFC 9110 token. Matched against the *folded* name, so the -# alphabetic range is lowercase only. -# -# **`\Z`, never `$`.** Python's `$` also matches immediately before a trailing -# newline, so `^token+$` accepts `"accept\n"` — and httpx passes that straight -# through to the wire as a header name containing a bare LF, which is header -# injection by any other name. `\Z` is the absolute end of the string and the -# only correct anchor for a validator (CR #14). The same trap applies to the -# value pattern below, where `.strip()` happens to hide it; relying on that -# would make one guard's correctness depend on another's ordering. -_HEADER_NAME = re.compile(r"\A[!#$%&'*+\-.^_`|~0-9a-z]+\Z") - -# A field value here is printable US-ASCII and SP — narrower than RFC 9110's -# VCHAR / obs-text on both edges, and deliberately so on each. -# -# **obs-text (\x80-\xff) is excluded because httpx cannot send it.** It encodes -# header values as ASCII and raises UnicodeEncodeError, which — unlike the -# LocalProtocolError a CRLF earns — is *not* an httpx.HTTPError, so it would slip -# past _fetch's mapping entirely and land in the loop's unclassified branch: -# retried to the delivery ceiling and finally closed as `handler_error` minutes -# later, instead of the immediate `invalid_request_options` this guard exists to -# produce. RFC 9110 deprecates obs-text anyway (CR #1). -# -# **HTAB (\x09) is excluded even though httpx accepts it.** RFC 9110 permits it -# as internal whitespace, but a tab inside a header value is nobody's intent and -# survives no round trip worth having. Refused on purpose, not by oversight -# (CR #3). -# -# What the guard is really for is CR and LF: a CRLF in a value is request -# splitting, and everything else here is the cheap part of drawing that line. -# -# Anchored `\A`/`\Z` for the reason spelled out on `_HEADER_NAME` above — `$` -# would admit a trailing newline. Unreachable here (the value is stripped before -# it is matched) and fixed anyway: one guard's correctness must not rest on -# another's ordering. -_HEADER_VALUE = re.compile(r"\A[\x20-\x7e]*\Z") - class RequestOptions(NamedTuple): """What the command asked the fetch itself to look like (#11). @@ -635,17 +554,17 @@ def _request_headers(headers: dict[str, str] | None) -> dict[str, str] | None: total = 0 for name, value in headers.items(): key = name.lower() - if not _HEADER_NAME.match(key): + if not HEADER_NAME.match(key): raise _invalid_options(f"{name!r} is not a valid header name") # Every refusal names the header as the *issuer* spelled it, not as the # fold left it: the message is read by somebody grepping their own # publishing code, where `Host` will not be found under `host` (CR #12). - if key in REFUSED_HEADERS or key.startswith(_REFUSED_HEADER_PREFIX): + if key in REFUSED_HEADERS or key.startswith(REFUSED_HEADER_PREFIX): raise _invalid_options(f"{name!r} is not a header Replicator will send") if key in folded: raise _invalid_options(f"{name!r} was given more than once, differing only in case") stripped = value.strip() - if not _HEADER_VALUE.match(stripped): + if not HEADER_VALUE.match(stripped): raise _invalid_options(f"{name!r} has a value that cannot be sent verbatim") # +4 for the ": " and the CRLF the value costs on the wire, so the bound # measures what the origin will measure rather than the payload alone. @@ -1140,7 +1059,7 @@ def _replayable(headers: dict[str, str], name: str) -> str | None: The publish path and the request guard must agree on what a header value may be, or Replicator emits a validator it will itself refuse (#60). ``etag`` and ``last_modified`` exist to be replayed in a conditional GET's - ``If-None-Match`` / ``If-Modified-Since``, and :data:`_HEADER_VALUE` refuses + ``If-None-Match`` / ``If-Modified-Since``, and :data:`HEADER_VALUE` refuses anything outside printable US-ASCII on the way out — obs-text because httpx encodes header values as ASCII and raises rather than sending them, interior HTAB because ``.strip()`` reaches only the ends. @@ -1159,7 +1078,7 @@ def _replayable(headers: dict[str, str], name: str) -> str | None: time. See :data:`MAX_HEADER_VALUE_LENGTH` for that argument in full. """ value = _passthrough(headers, name) - if value is None or not _HEADER_VALUE.match(value): + if value is None or not HEADER_VALUE.match(value): return None return value diff --git a/src/worker/headers.py b/src/worker/headers.py new file mode 100644 index 00000000..90facc6f --- /dev/null +++ b/src/worker/headers.py @@ -0,0 +1,97 @@ +"""The request-header rules every header Replicator sends on a command's behalf obeys. + +Shared by the handler's ``headers`` guards (#11) and the fetch credential table +(#216), whose bindings name a header and whose values are header values: one rule +for both, so a binding can't provision a header the handler would refuse to send. +Moved out of ``handler.py`` unchanged, because the handler imports the table. +""" + +import re + +# How many request headers a command may carry, and how many bytes they may add +# up to on the wire (#11). +# +# Deliberately not MAX_HEADER_VALUE_LENGTH, which reasons about *response* +# passthroughs riding a broadcast stream nothing trims — a different argument +# that happens to land on a similar number. This bound is about what an origin +# will accept: 8 KiB is the common server-side limit (nginx's +# large_client_header_buffers, Apache's LimitRequestFieldSize), so exceeding it +# earns an opaque 400 from the far end. Refusing locally turns that into a named +# reason on a fact the issuer already consumes. +# +# Constants rather than settings: these bound an unauthenticated capability, and +# a per-deployment knob is an invitation to loosen the one thing standing between +# a bus writer and an arbitrary request. +MAX_REQUEST_HEADERS = 32 +MAX_REQUEST_HEADER_BYTES = 8192 + +# Request headers Replicator will not send on an issuer's behalf. +# +# Two groups, refused for different reasons and listed together because the +# refusal is the same. The hop-by-hop set (RFC 9110 §7.6.1) describes a single +# connection, not the request — httpx and h11 own it, and an issuer's value is +# either ignored or corrupts the framing. `host` and `content-length` are not +# hop-by-hop: httpx derives both, and overriding `host` in particular points the +# request at one origin while addressing another (domain fronting) — precisely +# the widening the contract's trust model says the broker, not this list, is +# holding back. +# +# **Refused, not stripped.** Silently dropping one changes what the origin saw +# with nothing the issuer can observe, which is the same failure the +# reject-not-truncate rule exists to prevent, applied to the request side. It is +# also the conservative direction: relaxing a refusal to a strip later stays +# compatible, tightening a strip into a refusal does not. +REFUSED_HEADERS = frozenset( + { + "connection", + "content-length", + "host", + "keep-alive", + "proxy-connection", + "te", + "trailer", + "transfer-encoding", + "upgrade", + } +) + +# Every Proxy-* header, refused as a family: they configure the hop rather than +# the request, and enumerating them would date the list. +REFUSED_HEADER_PREFIX = "proxy-" + +# A field name is an RFC 9110 token. Matched against the *folded* name, so the +# alphabetic range is lowercase only. +# +# **`\Z`, never `$`.** Python's `$` also matches immediately before a trailing +# newline, so `^token+$` accepts `"accept\n"` — and httpx passes that straight +# through to the wire as a header name containing a bare LF, which is header +# injection by any other name. `\Z` is the absolute end of the string and the +# only correct anchor for a validator (CR #14). The same trap applies to the +# value pattern below, where `.strip()` happens to hide it; relying on that +# would make one guard's correctness depend on another's ordering. +HEADER_NAME = re.compile(r"\A[!#$%&'*+\-.^_`|~0-9a-z]+\Z") + +# A field value here is printable US-ASCII and SP — narrower than RFC 9110's +# VCHAR / obs-text on both edges, and deliberately so on each. +# +# **obs-text (\x80-\xff) is excluded because httpx cannot send it.** It encodes +# header values as ASCII and raises UnicodeEncodeError, which — unlike the +# LocalProtocolError a CRLF earns — is *not* an httpx.HTTPError, so it would slip +# past _fetch's mapping entirely and land in the loop's unclassified branch: +# retried to the delivery ceiling and finally closed as `handler_error` minutes +# later, instead of the immediate `invalid_request_options` this guard exists to +# produce. RFC 9110 deprecates obs-text anyway (CR #1). +# +# **HTAB (\x09) is excluded even though httpx accepts it.** RFC 9110 permits it +# as internal whitespace, but a tab inside a header value is nobody's intent and +# survives no round trip worth having. Refused on purpose, not by oversight +# (CR #3). +# +# What the guard is really for is CR and LF: a CRLF in a value is request +# splitting, and everything else here is the cheap part of drawing that line. +# +# Anchored `\A`/`\Z` for the reason spelled out on `HEADER_NAME` above — `$` +# would admit a trailing newline. Unreachable here (the value is stripped before +# it is matched) and fixed anyway: one guard's correctness must not rest on +# another's ordering. +HEADER_VALUE = re.compile(r"\A[\x20-\x7e]*\Z") diff --git a/tests/worker/test_handler_request_options.py b/tests/worker/test_handler_request_options.py index 440eafec..21f78c86 100644 --- a/tests/worker/test_handler_request_options.py +++ b/tests/worker/test_handler_request_options.py @@ -18,12 +18,12 @@ from src.core.errors import FailureReason, PermanentFetchError, TransientFetchError from src.storage.sweeper import BlobUsage from src.worker import handler as handler_module -from src.worker.handler import ( - _HEADER_VALUE, # the guard under test, pinned to httpx +from src.worker.headers import ( + HEADER_VALUE, # the guard under test, pinned to httpx MAX_REQUEST_HEADER_BYTES, MAX_REQUEST_HEADERS, ) -from src.worker.handler import REFUSED_HEADERS as REFUSED +from src.worker.headers import REFUSED_HEADERS as REFUSED from src.worker.loop import Outcome, poll_once from tests.worker.conftest import ( GROUP, @@ -227,7 +227,7 @@ async def test_the_value_guard_covers_everything_httpx_cannot_send(): 95 is the printable US-ASCII range ``\\x20``–``\\x7e`` inclusive, so this fails on a narrowing as loudly as on a widening. """ - accepted = [chr(code) for code in range(256) if _HEADER_VALUE.match(chr(code))] + accepted = [chr(code) for code in range(256) if HEADER_VALUE.match(chr(code))] assert len(accepted) == 95 assert accepted[0] == " " and accepted[-1] == "~" diff --git a/tests/worker/test_handler_tls.py b/tests/worker/test_handler_tls.py index f40bc142..7817b712 100644 --- a/tests/worker/test_handler_tls.py +++ b/tests/worker/test_handler_tls.py @@ -6,7 +6,7 @@ ``ssl.SSLError`` — not an ``httpx.HTTPError``, and not the builtin ``ConnectionError`` the loop retries. Left there it lands in the loop's unclassified branch, the one ``UnicodeEncodeError`` would have reached before -``_HEADER_VALUE``: retried to the delivery ceiling, then closed ``handler_error``. +``HEADER_VALUE``: retried to the delivery ceiling, then closed ``handler_error``. Measured on a real socket for #173, with a forged record before the status line and after part of the body. A mock here, because a forged record needs a TLS From a549d9dd79f87bb8a6596b4b575abf6d121191dd Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 17:06:33 +0000 Subject: [PATCH 03/23] #216 feat: the fetch credential table src/worker/credentials.py, in the alias table's shape: a JSON table at REPLICATOR_FETCH_CREDENTIALS_FILE, read once at boot with every value file it names, frozen behind MappingProxyType. A binding pins its header (call 3), names its hosts in PolicyHost's form (exact, no wildcard), and holds its value in a SecretStr (call 2). An unusable binding is dropped with the rule it broke; neither a value nor an off-rule reference is ever logged. Unset provisions nothing. The setting joins PRODUCTION_ENV, as the credential scrub requires. Loaded at boot; the handler takes the table in a later commit. Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 1 + src/core/config.py | 9 + src/worker/credentials.py | 281 +++++++++++++++++++++++++ src/worker/main.py | 5 + tests/conftest.py | 3 + tests/worker/test_credentials.py | 346 +++++++++++++++++++++++++++++++ tests/worker/test_main.py | 30 +++ 7 files changed, 675 insertions(+) create mode 100644 src/worker/credentials.py create mode 100644 tests/worker/test_credentials.py diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5ad26382..1b454117 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -56,6 +56,7 @@ src/core/ — Shared domain logic, logging, config src/core/errors.py — TransientError / PermanentError (what the loop catches) + the *Fetch/*Replicate leaves + FailureReason / ReplicateReason / PersistReason / CaptureReason src/worker/replicate.py — The content.replicate handler: alias resolve, T3/T3a guards, refusals; upload or server-side copy src/worker/aliases.py — The provisioned destination set, read once from env-referenced host config +src/worker/credentials.py — The fetch credential table: `fetch-` → header, hosts and a `SecretStr` value read from a host file, once at boot (#216) src/worker/replicate_reporter.py — replication_failed on content.artifacts src/worker/persist.py — The content.persist handler: T3a, the digest check, the copy into the permanent store (#114) src/worker/persist_reporter.py — blob_persisted / persist_failed on content.artifacts diff --git a/src/core/config.py b/src/core/config.py index 8bf611b2..7c843304 100644 --- a/src/core/config.py +++ b/src/core/config.py @@ -393,6 +393,15 @@ class Settings(BaseSettings): default=None, validation_alias="REPLICATOR_REPLICATION_ALIASES_FILE" ) + # Where the fetch credential table lives, or None on a host that sends none + # (#216). The alias table's shape and reasoning: a path in env, a table in the + # file, each value in a file of its own (src/worker/credentials.py). Unset is + # the safe default: every command carrying credential_headers is refused + # credential_unknown, so sending a credential is an operator act on the host. + fetch_credentials_file: Path | None = Field( + default=None, validation_alias="REPLICATOR_FETCH_CREDENTIALS_FILE" + ) + # How long one conditional create may run before the provider gives up. # # Surfaced rather than inherited (CR #38): the SDK's own default is 120s and diff --git a/src/worker/credentials.py b/src/worker/credentials.py new file mode 100644 index 00000000..4cc943c2 --- /dev/null +++ b/src/worker/credentials.py @@ -0,0 +1,281 @@ +"""The fetch credential table: which references this host resolves, and to what (#216). + +``ContentFetchCommand.credential_headers`` (cannobserv#577) maps a header name to a +``fetch-`` reference. The reference is a **key, never a value** (C1): it names +a binding an operator provisioned on this host, or it names nothing. The binding says +which header the value may ride (operator call 3), to which hosts (C2), and where on +this host the value lives. The value never travels on the bus. + +**``aliases.py``'s shape, for its reasons.** The provisioned set is host state, so env +carries the table's path (``REPLICATOR_FETCH_CREDENTIALS_FILE``) and the file carries +the table. It's read once, at boot, and frozen behind ``MappingProxyType``: no path +from the consume loop can add a binding. Unset means nothing is provisioned, which is +the safe default: every credentialed command closes ``credential_unknown``. + +**Values are read at boot, too** (operator call 2). A bad value file drops its binding +in the boot log rather than at the first fetch, the hot path does no file I/O, and +rotation is a restart, as it is for the writers' keys. Each value is held in a +``SecretStr`` on a frozen, slotted :class:`FetchCredential`, so ``repr`` and ``str`` +show ``**********``; ``get_secret_value()`` is called in one place, the transport +that builds the outgoing hop (``egress.py``), and ``tests/test_boundaries.py`` pins +that. + +**Never raises, and never quotes a value.** An unreadable table provisions nothing +(ERROR); an unusable binding drops itself (WARNING) with the rule it broke. Neither +names a value, and a reference off the rule isn't named either: the likeliest wrong +key, like the likeliest wrong ``credentials_file``, is a pasted secret. +""" + +import json +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from types import MappingProxyType +from typing import Any + +from co_core.pure.models.changes import PolicyHost +from co_core.pure.util.aliases import FETCH_CREDENTIAL_PATTERN, validate_fetch_credential +from pydantic import SecretStr, TypeAdapter, ValidationError + +from src.core.logging import get_logger +from src.worker.headers import ( + HEADER_NAME, + HEADER_VALUE, + MAX_REQUEST_HEADER_BYTES, + REFUSED_HEADER_PREFIX, + REFUSED_HEADERS, +) + +logger = get_logger(__name__) + +# One message for unset and for a path with no file behind it, as the alias table +# has it, so one grep answers "is this host provisioned?". +_UNPROVISIONED = "no fetch credential table on this host — fetch credentials are not provisioned" +_DROPPED = "ignoring an unusable fetch credential binding" + +# co-core's E5 (cannobserv#577): headers a credential may never name. ``user-agent`` +# is the driver's default and the fingerprint-continuity lever; the two validators are +# what a revalidating issuer replays from ``blob_available`` (#17). None is a secret. +UNCREDENTIALED_HEADERS = frozenset({"user-agent", "if-none-match", "if-modified-since"}) + +_POLICY_HOST = TypeAdapter(PolicyHost) + + +@dataclass(frozen=True, slots=True) +class FetchCredential: + """One binding: the header it rides, the hosts it may reach, and its value. + + ``header`` is folded to lower case, as the handler folds every header it sends. + ``hosts`` are in ``PolicyHost``'s canonical form (lower case, punycode, no + trailing dot), the spelling ``content.fetch-policy`` uses. ``value_file`` is the + path the value was read from, for the boot line; never the value. + + ``slots=True`` drops a stray field in the table rather than carrying it, as + ``AliasBinding``'s does. + """ + + header: str + hosts: frozenset[str] + value: SecretStr + value_file: str + + def __post_init__(self) -> None: + if not isinstance(self.value, SecretStr): + raise TypeError("a FetchCredential's value is a SecretStr, never a plain string") + + +@dataclass(frozen=True, slots=True) +class FetchCredentialTable: + """The provisioned set, read once at boot. A command can resolve it and never change it.""" + + bindings: Mapping[str, FetchCredential] + + def resolve(self, reference: str) -> FetchCredential | None: + """The binding for ``reference``, or ``None`` if nobody provisioned it here.""" + return self.bindings.get(reference) + + @property + def provisioned(self) -> tuple[str, ...]: + """Every reference this host resolves, sorted: logged once at boot.""" + return tuple(sorted(self.bindings)) + + +def _empty() -> FetchCredentialTable: + return FetchCredentialTable(MappingProxyType({})) + + +def load_fetch_credentials(path: Path | None) -> FetchCredentialTable: + """Read the table and every value it names, failing **closed** at every step. + + - **no path, or no file**: nothing is provisioned, INFO, one message for both; + - **an unreadable table**: nothing is provisioned, ERROR; + - **one unusable binding**: that binding alone is dropped, WARNING, with the rule. + + Never raises: a fetch misconfiguration must not stop a worker whose other + commands are fine. Each refusal reports per command, as ``credential_unknown``. + """ + if path is None: + logger.info( + _UNPROVISIONED, + extra={ + "detail": "REPLICATOR_FETCH_CREDENTIALS_FILE is unset; " + "every credentialed content.fetch command is refused credential_unknown" + }, + ) + return _empty() + try: + raw = json.loads(Path(path).read_text()) + except FileNotFoundError: + logger.info( + _UNPROVISIONED, + extra={ + "path": str(path), + "detail": "no file at that path; " + "every credentialed content.fetch command is refused credential_unknown", + }, + ) + return _empty() + except Exception as exc: + # The exception's type, never its message: a JSON error's message quotes no + # content today, and a refusal that never quotes must not rest on that. + logger.error( + "fetch credential table is unreadable", + extra={ + "path": str(path), + "error": type(exc).__name__, + "detail": "nothing is provisioned; every credentialed command will be refused", + }, + ) + return _empty() + if not isinstance(raw, dict): + logger.error( + "fetch credential table is unreadable", + extra={"path": str(path), "detail": "expected an object of reference -> binding"}, + ) + return _empty() + + bindings: dict[str, FetchCredential] = {} + for position, (reference, entry) in enumerate(raw.items()): + credential = _credential_or_none(str(reference), entry, position) + if credential is not None: + bindings[str(reference)] = credential + table = FetchCredentialTable(MappingProxyType(bindings)) + logger.info( + "fetch credentials loaded", + extra={ + "path": str(path), + "provisioned": { + reference: { + "header": credential.header, + "hosts": sorted(credential.hosts), + "value_file": credential.value_file, + } + for reference, credential in sorted(bindings.items()) + }, + }, + ) + return table + + +def _credential_or_none(reference: str, entry: Any, position: int) -> FetchCredential | None: + """One binding, or ``None`` with the rule it broke in the journal.""" + try: + validate_fetch_credential(reference) + except ValueError: + # Not named: a key off the rule is likeliest a pasted secret. Its position + # in the table is what the operator finds it by. + logger.warning( + _DROPPED, + extra={ + "position": position, + "detail": f"the reference is not fetch- ({FETCH_CREDENTIAL_PATTERN}); " + "not quoted, in case it is a pasted secret", + }, + ) + return None + why, credential = _why_unusable(entry) + if why is not None: + extra: dict[str, Any] = {"reference": reference, "detail": why} + if isinstance(entry, dict) and isinstance(entry.get("value_file"), str): + extra["value_file"] = entry["value_file"] + logger.warning(_DROPPED, extra=extra) + return None + return credential + + +def _why_unusable(entry: Any) -> tuple[str | None, FetchCredential | None]: + """Why this entry can't be provisioned, or the credential it provisions.""" + if not isinstance(entry, dict): + return "the binding is not an object", None + header = entry.get("header") + why = _why_unusable_header(header) + if why is not None: + return why, None + hosts, why = _canonical_hosts(entry.get("hosts")) + if why is not None: + return why, None + value_file = entry.get("value_file") + if not isinstance(value_file, str) or not value_file.startswith("/"): + return "value_file must be an absolute host path to the value", None + value, why = _read_value(value_file, header.lower()) + if why is not None: + return why, None + return None, FetchCredential( + header=header.lower(), hosts=hosts, value=SecretStr(value), value_file=value_file + ) + + +def _why_unusable_header(header: Any) -> str | None: + """The handler's name rules for ``headers`` (``headers.py``), plus co-core's E5.""" + if not isinstance(header, str) or not header: + return "the binding names no header" + folded = header.lower() + if not HEADER_NAME.match(folded): + return "header is not an RFC 9110 token" + if folded in REFUSED_HEADERS or folded.startswith(REFUSED_HEADER_PREFIX): + return f"{header!r} is not a header Replicator will send" + if folded in UNCREDENTIALED_HEADERS: + return f"{header!r} is never a credential (co-core E5)" + return None + + +def _canonical_hosts(hosts: Any) -> tuple[frozenset[str], str | None]: + """Each host in ``PolicyHost``'s form; a binding matches hosts exactly.""" + if not isinstance(hosts, list) or not hosts: + return frozenset(), "hosts must be a non-empty list of hostnames" + canonical: set[str] = set() + for host in hosts: + if not isinstance(host, str): + return frozenset(), "every entry in hosts must be a hostname" + if "*" in host: + return frozenset(), f"host {host!r} is a wildcard; a binding matches hosts exactly" + try: + canonical.add(_POLICY_HOST.validate_python(host)) + except ValidationError as exc: + return frozenset(), f"host {host!r} is not a bare hostname: {exc.errors()[0]['msg']}" + return frozenset(canonical), None + + +def _read_value(value_file: str, header: str) -> tuple[str, str | None]: + """The value, minus one trailing ``\\n``, or why it can't be sent verbatim. Never quoted.""" + try: + content = Path(value_file).read_bytes() + except OSError as exc: + return "", f"value_file is unreadable ({type(exc).__name__})" + try: + value = content.decode("ascii") + except UnicodeDecodeError: + return "", "the value is not printable US-ASCII" + value = value.removesuffix("\n") + if not value: + return "", "the value is empty" + if not HEADER_VALUE.match(value): + return "", "the value is not printable US-ASCII on one line" + if value != value.strip(): + # The handler strips an issuer's value; a credential's is refused instead, + # because a stripped secret is a different secret. + return "", "the value has leading or trailing whitespace" + # The handler's measure: name, ": ", value, CRLF (``headers.py``). + if len(header) + len(value) + 4 > MAX_REQUEST_HEADER_BYTES: + return "", f"the value exceeds the {MAX_REQUEST_HEADER_BYTES}-byte header bound" + return value, None diff --git a/src/worker/main.py b/src/worker/main.py index 45cd8aa8..85498670 100644 --- a/src/worker/main.py +++ b/src/worker/main.py @@ -48,6 +48,7 @@ from src.worker.capture import build_capture_handler from src.worker.capture_reporter import build_capture_reporter, build_captured_publisher from src.worker.checkout import checkout_refusal +from src.worker.credentials import load_fetch_credentials from src.worker.egress import ( BodyCeilingTransport, CommandScopeTransport, @@ -969,6 +970,10 @@ async def run( # replicate command is refused — the safe default (contract T5), and # every host's state until an operator writes the table (this VM's # until #86 provisioned `primary`). + # The fetch credential table, the same kind of host state (#216): read once, + # values included, so a bad value file drops its binding here and not at the + # first credentialed fetch. Never raises; unset provisions nothing. + load_fetch_credentials(settings.fetch_credentials_file) aliases = load_alias_table( settings.replication_aliases_file, # No alias may bind a bucket this host keeps blobs in (#114). diff --git a/tests/conftest.py b/tests/conftest.py index 45991b0a..62de321f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -57,6 +57,9 @@ # same backend a fresh clone does. PRODUCTION_ENV = ( "REPLICATOR_REPLICATION_ALIASES_FILE", + # Production will set it (#216); a test that inherited it would load the host's + # real bindings. test_every_credential_setting_is_scrubbed requires it by name. + "REPLICATOR_FETCH_CREDENTIALS_FILE", "GOOGLE_APPLICATION_CREDENTIALS", "REPLICATOR_BLOB_BACKEND", "REPLICATOR_BLOB_BUCKET", diff --git a/tests/worker/test_credentials.py b/tests/worker/test_credentials.py new file mode 100644 index 00000000..591ebcd4 --- /dev/null +++ b/tests/worker/test_credentials.py @@ -0,0 +1,346 @@ +"""The fetch credential table: which references this host resolves, and to what (#216). + +``ContentFetchCommand.credential_headers`` maps a header name to a ``fetch-`` +reference. The reference is a **key, never a value** (cannobserv#577, C1): it names +a binding an operator provisioned here, and the binding says which header the value +may ride, to which hosts, and where on this host the value lives. + +These tests pin the table's half of that, the half that is host state: + +- the table is read once, at boot, and nothing a command carries reaches it; +- a bad entry is dropped with the rule it broke and **never the value**; +- the value sits in a ``SecretStr`` and no ``repr`` or log line shows it. + +The planted value below is the test's tripwire: it must appear in no log record, no +``repr`` and no ``str`` of anything the loader returns. +""" + +import json +import logging + +import pytest +from pydantic import SecretStr + +from src.worker.credentials import ( + UNCREDENTIALED_HEADERS, + FetchCredential, + FetchCredentialTable, + load_fetch_credentials, +) +from src.worker.headers import MAX_REQUEST_HEADER_BYTES + +VALUE = "planted-test-value-3f9c2b" # never a real credential; a tripwire for leaks +UNPROVISIONED = "no fetch credential table on this host — fetch credentials are not provisioned" + + +def write_value(tmp_path, content: str = VALUE + "\n", name: str = "fetch-wa-leg-api"): + directory = tmp_path / "fetch-credentials" + directory.mkdir(exist_ok=True) + path = directory / name + path.write_text(content) + return path + + +def binding(path, **overrides): + return { + "header": "X-Api-Key", + "hosts": ["api.leg.wa.gov"], + "value_file": str(path), + **overrides, + } + + +def write_table(tmp_path, mapping): + path = tmp_path / "fetch-credentials.json" + path.write_text(json.dumps(mapping)) + return path + + +def load(tmp_path, mapping, caplog=None): + path = write_table(tmp_path, mapping) + if caplog is None: + return load_fetch_credentials(path) + with caplog.at_level(logging.INFO, logger="src.worker.credentials"): + return load_fetch_credentials(path) + + +def assert_no_value_in(caplog): + for record in caplog.records: + assert VALUE not in record.getMessage() + assert VALUE not in json.dumps(record.__dict__, default=str) + + +# --- Unprovisioned: the safe default ---------------------------------------------- + + +def test_an_unset_path_provisions_nothing(caplog): + with caplog.at_level(logging.INFO, logger="src.worker.credentials"): + table = load_fetch_credentials(None) + + assert table.provisioned == () + assert table.resolve("fetch-wa-leg-api") is None + assert [r.message for r in caplog.records] == [UNPROVISIONED] + assert "REPLICATOR_FETCH_CREDENTIALS_FILE is unset" in caplog.records[0].detail + + +def test_a_missing_file_provisions_nothing_under_the_same_message(tmp_path, caplog): + with caplog.at_level(logging.INFO, logger="src.worker.credentials"): + table = load_fetch_credentials(tmp_path / "absent.json") + + assert table.provisioned == () + assert [(r.levelname, r.message) for r in caplog.records] == [("INFO", UNPROVISIONED)] + + +@pytest.mark.parametrize("raw", ["{not json", "[]", '"a string"', "null"]) +def test_an_unreadable_table_provisions_nothing_and_says_so(tmp_path, caplog, raw): + """Refusing everything is recoverable; provisioning whatever parsed first is not.""" + path = tmp_path / "fetch-credentials.json" + path.write_text(raw) + + with caplog.at_level(logging.INFO, logger="src.worker.credentials"): + table = load_fetch_credentials(path) + + assert table.provisioned == () + assert [(r.levelname, r.message) for r in caplog.records] == [ + ("ERROR", "fetch credential table is unreadable") + ] + + +# --- A good binding ----------------------------------------------------------------- + + +def test_a_binding_resolves_to_its_header_hosts_and_value(tmp_path): + value_file = write_value(tmp_path) + + table = load(tmp_path, {"fetch-wa-leg-api": binding(value_file)}) + credential = table.resolve("fetch-wa-leg-api") + + assert table.provisioned == ("fetch-wa-leg-api",) + assert credential.header == "x-api-key" + assert credential.hosts == frozenset({"api.leg.wa.gov"}) + assert credential.value_file == str(value_file) + assert isinstance(credential.value, SecretStr) + assert credential.value.get_secret_value() == VALUE + + +def test_one_trailing_newline_is_the_files_not_the_values(tmp_path): + """``echo`` and every editor end a file with one; it is never part of the value.""" + value_file = write_value(tmp_path, content=VALUE) + + credential = load(tmp_path, {"fetch-wa-leg-api": binding(value_file)}).resolve( + "fetch-wa-leg-api" + ) + + assert credential.value.get_secret_value() == VALUE + + +def test_hosts_are_held_in_policy_hosts_canonical_form(tmp_path): + """One spelling per host, the one ``content.fetch-policy`` uses (co-core's ``PolicyHost``).""" + value_file = write_value(tmp_path) + + credential = load( + tmp_path, + { + "fetch-wa-leg-api": binding( + value_file, hosts=["API.Leg.WA.gov.", "xn--bcher-kva.example"] + ) + }, + ).resolve("fetch-wa-leg-api") + + assert credential.hosts == frozenset({"api.leg.wa.gov", "xn--bcher-kva.example"}) + + +def test_the_boot_line_names_references_headers_hosts_and_paths_never_values(tmp_path, caplog): + value_file = write_value(tmp_path) + + load(tmp_path, {"fetch-wa-leg-api": binding(value_file)}, caplog) + + [loaded] = [r for r in caplog.records if r.message == "fetch credentials loaded"] + assert loaded.provisioned == { + "fetch-wa-leg-api": { + "header": "x-api-key", + "hosts": ["api.leg.wa.gov"], + "value_file": str(value_file), + } + } + assert_no_value_in(caplog) + + +# --- The value never shows ---------------------------------------------------------- + + +def test_neither_a_binding_nor_the_table_shows_the_value(tmp_path): + value_file = write_value(tmp_path) + table = load(tmp_path, {"fetch-wa-leg-api": binding(value_file)}) + credential = table.resolve("fetch-wa-leg-api") + + for shown in (repr(credential), str(credential), repr(table), str(table)): + assert VALUE not in shown + + +def test_a_stray_field_never_reaches_an_attribute(tmp_path): + """Only the declared fields are read: a value pasted into the table is dropped.""" + value_file = write_value(tmp_path) + + credential = load( + tmp_path, {"fetch-wa-leg-api": binding(value_file, value=VALUE, secret=VALUE)} + ).resolve("fetch-wa-leg-api") + + assert not hasattr(credential, "secret") + assert VALUE not in repr(credential) + + +# --- Immutable host state ----------------------------------------------------------- + + +def test_the_mapping_cannot_be_mutated_through(tmp_path): + table = load(tmp_path, {"fetch-wa-leg-api": binding(write_value(tmp_path))}) + + with pytest.raises(TypeError): + table.bindings["fetch-smuggled"] = table.resolve("fetch-wa-leg-api") + + +def test_a_binding_and_the_table_are_frozen(tmp_path): + table = load(tmp_path, {"fetch-wa-leg-api": binding(write_value(tmp_path))}) + credential = table.resolve("fetch-wa-leg-api") + + with pytest.raises(AttributeError): + credential.hosts = frozenset({"elsewhere.example"}) # type: ignore[misc] + with pytest.raises(AttributeError): + table.bindings = {} # type: ignore[misc] + + +def test_every_construction_path_returns_an_immutable_table(tmp_path): + for table in ( + load_fetch_credentials(None), + load_fetch_credentials(tmp_path / "absent.json"), + load(tmp_path, {}), + ): + assert isinstance(table, FetchCredentialTable) + with pytest.raises(TypeError): + table.bindings["fetch-x"] = None # type: ignore[index] + + +# --- A bad entry drops itself, never the table, and never quotes the value ------------ + + +def _dropped(tmp_path, caplog, reference, entry, why): + good = write_value(tmp_path, name="fetch-good") + table = load(tmp_path, {"fetch-good": binding(good), reference: entry}, caplog) + + assert table.provisioned == ("fetch-good",) + warnings = [r for r in caplog.records if r.levelname == "WARNING"] + assert [r.message for r in warnings] == ["ignoring an unusable fetch credential binding"] + assert why in warnings[0].detail, warnings[0].detail + assert_no_value_in(caplog) + return warnings[0] + + +@pytest.mark.parametrize( + "reference", + ["gcs-publication", "fetch-", "FETCH-x", "fetch_x", VALUE], +) +def test_a_reference_off_the_rule_is_dropped_and_not_quoted(tmp_path, caplog, reference): + """The likeliest wrong key is a pasted secret, so the log carries the rule, not the key.""" + warning = _dropped(tmp_path, caplog, reference, binding(write_value(tmp_path)), "fetch-") + + assert getattr(warning, "reference", None) is None + + +@pytest.mark.parametrize( + ("overrides", "why"), + [ + pytest.param({"header": None}, "header", id="no-header"), + pytest.param({"header": "X Api Key"}, "token", id="not-a-token"), + pytest.param({"header": "X-Api-Key\n"}, "token", id="trailing-newline"), + pytest.param({"header": "Host"}, "not a header Replicator will send", id="refused"), + pytest.param({"header": "Proxy-Authorization"}, "not a header", id="proxy-family"), + pytest.param({"header": "User-Agent"}, "never a credential", id="E5-user-agent"), + pytest.param({"header": "If-None-Match"}, "never a credential", id="E5-validator"), + pytest.param({"header": "if-modified-since"}, "never a credential", id="E5-validator-2"), + pytest.param({"hosts": []}, "hosts", id="no-hosts"), + pytest.param({"hosts": "api.leg.wa.gov"}, "hosts", id="hosts-a-string"), + pytest.param({"hosts": ["https://api.leg.wa.gov"]}, "host", id="host-with-scheme"), + pytest.param({"hosts": ["api.leg.wa.gov:443"]}, "host", id="host-with-port"), + pytest.param({"hosts": ["bücher.example"]}, "host", id="host-not-punycode"), + pytest.param({"hosts": ["*.leg.wa.gov"]}, "wildcard", id="wildcard"), + pytest.param({"hosts": [""]}, "host", id="empty-host"), + pytest.param({"value_file": "relative/path"}, "absolute", id="relative-path"), + pytest.param({"value_file": 7}, "absolute", id="not-a-string"), + ], +) +def test_an_unusable_binding_is_dropped_with_the_rule_it_broke(tmp_path, caplog, overrides, why): + entry = binding(write_value(tmp_path), **overrides) + if overrides.get("header", "") is None: + del entry["header"] + + warning = _dropped(tmp_path, caplog, "fetch-wa-leg-api", entry, why) + + assert warning.reference == "fetch-wa-leg-api" + + +def test_a_binding_that_is_not_an_object_is_dropped(tmp_path, caplog): + _dropped(tmp_path, caplog, "fetch-wa-leg-api", "x-api-key", "not an object") + + +@pytest.mark.parametrize( + ("content", "why"), + [ + pytest.param("", "empty", id="empty"), + pytest.param("\n", "empty", id="only-a-newline"), + pytest.param(f"{VALUE}\r\n", "printable", id="crlf"), + pytest.param(f"{VALUE}\n\n", "printable", id="two-newlines"), + pytest.param(f"{VALUE}\nsplit", "printable", id="embedded-newline"), + pytest.param(f"{VALUE}\tx", "printable", id="tab"), + pytest.param(f"{VALUE}é", "printable", id="non-ascii"), + pytest.param(f" {VALUE}", "whitespace", id="leading-space"), + pytest.param(f"{VALUE} \n", "whitespace", id="trailing-space"), + pytest.param("v" * MAX_REQUEST_HEADER_BYTES, "byte", id="over-the-bound"), + ], +) +def test_an_unsendable_value_drops_the_binding_and_is_never_quoted(tmp_path, caplog, content, why): + """A value httpx would refuse, or send altered, is refused at boot rather than at a fetch.""" + value_file = write_value(tmp_path, content=content) + + _dropped(tmp_path, caplog, "fetch-wa-leg-api", binding(value_file), why) + + +def test_a_value_exactly_at_the_byte_bound_is_kept(tmp_path): + """The bound counts the field line: name, ``": "``, value, CRLF — the handler's measure.""" + content = "v" * (MAX_REQUEST_HEADER_BYTES - len("x-api-key") - 4) + + table = load(tmp_path, {"fetch-wa-leg-api": binding(write_value(tmp_path, content=content))}) + + assert table.provisioned == ("fetch-wa-leg-api",) + + +def test_an_unreadable_value_file_drops_the_binding(tmp_path, caplog): + warning = _dropped( + tmp_path, + caplog, + "fetch-wa-leg-api", + binding(tmp_path / "fetch-credentials" / "absent"), + "unreadable", + ) + + assert warning.value_file.endswith("absent") + + +def test_a_value_file_that_is_not_utf8_drops_the_binding(tmp_path, caplog): + value_file = write_value(tmp_path) + value_file.write_bytes(b"\xff\xfe" + VALUE.encode()) + + _dropped(tmp_path, caplog, "fetch-wa-leg-api", binding(value_file), "printable") + + +def test_the_names_that_are_never_credentials_are_e5s(): + """co-core's E5: the driver's default and the two validators the handler replays.""" + assert UNCREDENTIALED_HEADERS == frozenset({"user-agent", "if-none-match", "if-modified-since"}) + + +def test_a_credential_is_constructed_only_with_a_secret(): + """``value`` is typed ``SecretStr``: a plain string on the field is a type error.""" + with pytest.raises(TypeError): + FetchCredential( + header="x-api-key", hosts=frozenset({"a.example"}), value=VALUE, value_file="/v" + ) diff --git a/tests/worker/test_main.py b/tests/worker/test_main.py index b50c47c9..22725075 100644 --- a/tests/worker/test_main.py +++ b/tests/worker/test_main.py @@ -1874,3 +1874,33 @@ def refuse(): assert record["worker_memory_low"] == "claim failed" errors = [r for r in lines if r.get("level") == "ERROR"] assert any("memory.low" in r["message"] for r in errors), errors + + +async def test_the_boot_reads_the_fetch_credential_table(monkeypatch, fake_redis, tmp_path, capsys): + """#216: the table is read at boot and its line names references, never values.""" + value = "planted-boot-value-7d1e" + value_file = tmp_path / "fetch-wa-leg-api" + value_file.write_text(value + "\n") + table = tmp_path / "fetch-credentials.json" + table.write_text( + json.dumps( + { + "fetch-wa-leg-api": { + "header": "X-Api-Key", + "hosts": ["api.leg.wa.gov"], + "value_file": str(value_file), + } + } + ) + ) + monkeypatch.setenv("REPLICATOR_BLOB_DIR", str(tmp_path / "blobs")) + monkeypatch.setenv("REPLICATOR_FETCH_CREDENTIALS_FILE", str(table)) + monkeypatch.setattr("src.worker.main.Redis.from_url", lambda *a, **kw: fake_redis) + + await run(_stopped()) + + out = capsys.readouterr().out + lines = [json.loads(line) for line in out.splitlines() if line.strip()] + [loaded] = [line for line in lines if line.get("message") == "fetch credentials loaded"] + assert list(loaded["provisioned"]) == ["fetch-wa-leg-api"] + assert value not in out From d8e34cc4b3a5956300360e40fc457bbb3431059e Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 17:06:57 +0000 Subject: [PATCH 04/23] #216 feat: credential_unknown and credential_refused MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two content.fetch reason tokens, both terminal with status_code and attempts unset (D6). credential_unknown: no usable binding for the reference. credential_refused: the binding exists, but the header, host, scheme or port is outside it — pre-flight or at the redirect hop. Co-Authored-By: Claude Opus 5.5 --- src/core/errors.py | 20 ++++++++++++++++++++ tests/core/test_errors.py | 2 ++ 2 files changed, 22 insertions(+) diff --git a/src/core/errors.py b/src/core/errors.py index 8579dcf3..9537f40d 100644 --- a/src/core/errors.py +++ b/src/core/errors.py @@ -106,6 +106,26 @@ class FailureReason(StrEnum): only way the issuer can tell the two cases apart. """ + CREDENTIAL_UNKNOWN = "credential_unknown" + """A ``credential_headers`` reference this host has no usable binding for (#216). + + Never provisioned, dropped at load, or off the ``fetch-`` rule. Terminal, + pre-flight: nothing was sent. The remedy is to provision the binding on the + host, or fix the reference in the issuer's policy. ``detail`` names the header + and the reference, never a value. + """ + + CREDENTIAL_REFUSED = "credential_refused" + """The binding exists, but this use of it is outside it (#216). + + A hop whose host isn't in every binding's ``hosts``, that isn't ``https``, or + isn't on port 443; or a header name that isn't the binding's. ``destination_refused``'s + shape: pre-flight on the submitted URL, or **at the redirect hop**, before that + hop is sent, so the value never leaves the binding's scope (C2, C3). Out of scope + *and* in a refused range gives this token (operator call 5). An origin's 401 or + 403 when a credential was sent stays ``http_status``. + """ + NOT_MODIFIED = "not_modified" """A conditional GET that succeeded: 304, and the issuer's bytes still stand. diff --git a/tests/core/test_errors.py b/tests/core/test_errors.py index 717b0d3c..0c6ab6b9 100644 --- a/tests/core/test_errors.py +++ b/tests/core/test_errors.py @@ -105,6 +105,8 @@ def test_the_reason_tokens_are_the_wire_tokens(): here rather than silently change what Watcher branches on. """ assert {reason.value for reason in FailureReason} == { + "credential_refused", + "credential_unknown", "destination_refused", "http_status", "invalid_request_options", From 713057acb8d42e88e4ba1476fbe6a8c678953d62 Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 17:17:20 +0000 Subject: [PATCH 05/23] #216 feat: guard the credential headers and resolve them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit D4 steps 1 and 2, both pure and both ahead of the ceiling and the pacer. Step 1, in _request_options: credential_headers' names get the headers guards, folded with headers — a name in both maps (E3) or twice by case (E4) is a duplicate — plus E5's names, the count bound over the union, and E1 (any credential under render="browser"). invalid_request_options. Step 2, _resolve_credentials against the boot table: a reference off fetch- (checked whole, with co-core's validator) or never provisioned is credential_unknown; the wrong header for its binding is credential_refused (call 3); the byte bound over both maps, resolved values counted, is invalid_request_options; a submitted URL outside any binding's scope (https, port 443, the host in every binding) is credential_refused. An off-rule reference is never quoted. The resolved (reference, binding) pairs ride the command scope to the transport; FetchContent never holds a value. The worker passes the boot table to the fetch handler; unset provisions nothing. Co-Authored-By: Claude Opus 5.5 --- src/worker/credentials.py | 24 +- src/worker/egress.py | 47 ++- src/worker/handler.py | 155 ++++++++- src/worker/main.py | 3 +- tests/worker/conftest.py | 17 +- tests/worker/test_credentials.py | 1 + tests/worker/test_handler_credentials.py | 423 +++++++++++++++++++++++ tests/worker/test_main.py | 10 + 8 files changed, 664 insertions(+), 16 deletions(-) create mode 100644 tests/worker/test_handler_credentials.py diff --git a/src/worker/credentials.py b/src/worker/credentials.py index 4cc943c2..0c23d4d7 100644 --- a/src/worker/credentials.py +++ b/src/worker/credentials.py @@ -31,7 +31,7 @@ from dataclasses import dataclass from pathlib import Path from types import MappingProxyType -from typing import Any +from typing import Any, NamedTuple from co_core.pure.models.changes import PolicyHost from co_core.pure.util.aliases import FETCH_CREDENTIAL_PATTERN, validate_fetch_credential @@ -84,6 +84,17 @@ def __post_init__(self) -> None: raise TypeError("a FetchCredential's value is a SecretStr, never a plain string") +class Resolved(NamedTuple): + """A reference the handler resolved, beside its binding: what a command scope holds. + + The reference rides along so a hop refusal can name it; the table's key stays the + one owner of the name, as the alias table's does (``AliasBinding``'s CR #39). + """ + + reference: str + credential: FetchCredential + + @dataclass(frozen=True, slots=True) class FetchCredentialTable: """The provisioned set, read once at boot. A command can resolve it and never change it.""" @@ -100,7 +111,8 @@ def provisioned(self) -> tuple[str, ...]: return tuple(sorted(self.bindings)) -def _empty() -> FetchCredentialTable: +def unprovisioned() -> FetchCredentialTable: + """The nothing-provisioned table: every reference resolves to ``None``.""" return FetchCredentialTable(MappingProxyType({})) @@ -122,7 +134,7 @@ def load_fetch_credentials(path: Path | None) -> FetchCredentialTable: "every credentialed content.fetch command is refused credential_unknown" }, ) - return _empty() + return unprovisioned() try: raw = json.loads(Path(path).read_text()) except FileNotFoundError: @@ -134,7 +146,7 @@ def load_fetch_credentials(path: Path | None) -> FetchCredentialTable: "every credentialed content.fetch command is refused credential_unknown", }, ) - return _empty() + return unprovisioned() except Exception as exc: # The exception's type, never its message: a JSON error's message quotes no # content today, and a refusal that never quotes must not rest on that. @@ -146,13 +158,13 @@ def load_fetch_credentials(path: Path | None) -> FetchCredentialTable: "detail": "nothing is provisioned; every credentialed command will be refused", }, ) - return _empty() + return unprovisioned() if not isinstance(raw, dict): logger.error( "fetch credential table is unreadable", extra={"path": str(path), "detail": "expected an object of reference -> binding"}, ) - return _empty() + return unprovisioned() bindings: dict[str, FetchCredential] = {} for position, (reference, entry) in enumerate(raw.items()): diff --git a/src/worker/egress.py b/src/worker/egress.py index 07ea0d96..9291b430 100644 --- a/src/worker/egress.py +++ b/src/worker/egress.py @@ -72,6 +72,7 @@ import httpx from src.core.errors import FailureReason, PermanentFetchError, TransientFetchError +from src.worker.credentials import Resolved # What a fetch may not reach. Every range here is this host, this host's private # network, the tailnet the bus rides, or an IANA special-purpose range (#161) — @@ -301,8 +302,14 @@ async def aclose(self) -> None: @dataclass(frozen=True, slots=True) class CommandScope: - """What one command's hops share: its cookies, and nothing past the command (#216).""" + """What one command's hops share, and nothing past the command (#216). + ``credentials`` are the bindings the handler resolved; empty for an anonymous + command, whose hops go out as they always have. ``cookies`` live for the + command's redirect chain. + """ + + credentials: tuple[Resolved, ...] = () cookies: httpx.Cookies = field(default_factory=httpx.Cookies) @@ -310,9 +317,9 @@ class CommandScope: @contextmanager -def command_scope() -> Iterator[CommandScope]: +def command_scope(credentials: tuple[Resolved, ...] = ()) -> Iterator[CommandScope]: """Enter a fresh scope for one command's fetch, and leave it even when the fetch raises.""" - scope = CommandScope() + scope = CommandScope(credentials=credentials) token = _COMMAND_SCOPE.set(scope) try: yield scope @@ -320,6 +327,40 @@ def command_scope() -> Iterator[CommandScope]: _COMMAND_SCOPE.reset(token) +# The one port a credential may be sent to (operator call 4). ``PolicyHost`` has no +# port, so a host-only scope would admit ``https`` on any port of that host; +# relaxing this later stays compatible, tightening it would not. +CREDENTIAL_PORT = 443 + + +def scope_refusal(url: httpx.URL, credentials: Iterable[Resolved]) -> str | None: + """Why ``url`` is outside a credential's scope, or ``None`` if every one admits it (C2). + + Pure, so the handler checks the submitted URL with it before the ceiling, and the + transport checks every hop with it before DNS. ``https`` only, port 443 only, and + the host in **every** binding's ``hosts``: a hop out of scope for one credential + sends none of them. The host is ``raw_host`` (punycode), never ``host`` (IDNA + decoded), less one trailing dot, so it compares in ``PolicyHost``'s form. + """ + credentials = tuple(credentials) + if not credentials: + return None + named = ", ".join(f"{c.credential.header} ({c.reference})" for c in credentials) + if url.scheme != "https": + return f"{url} is {url.scheme}, not https; {named} is sent over https only" + port = url.port if url.port is not None else _default_port(url) + if port != CREDENTIAL_PORT: + return f"{url} is port {port}; {named} is sent to port {CREDENTIAL_PORT} only" + host = url.raw_host.decode("ascii").lower().removesuffix(".") + for reference, credential in credentials: + if host not in credential.hosts: + return ( + f"{url} is outside {credential.header} ({reference})'s scope: " + f"{host} is not one of {', '.join(sorted(credential.hosts))}" + ) + return None + + def never_storing_cookies() -> http.cookiejar.CookieJar: """The client's jar: one whose policy admits no domain, so it never stores a cookie. diff --git a/src/worker/handler.py b/src/worker/handler.py index 95558600..932a224d 100644 --- a/src/worker/handler.py +++ b/src/worker/handler.py @@ -21,6 +21,7 @@ from co_core.pure.adapters.bus import streams from co_core.pure.adapters.bus.envelope import to_wire from co_core.pure.models.changes import BlobAvailableEvent, ContentFetchCommand +from co_core.pure.util.aliases import validate_fetch_credential from co_core.pure.util.blobstore import BlobStore from co_core.pure.util.hashing import sha256 from co_core_aio.bus import AsyncBusPublisher @@ -37,7 +38,13 @@ from src.core.logging import get_logger from src.storage.sweeper import BlobUsage from src.worker.browser import RenderDeadlineError -from src.worker.egress import command_scope +from src.worker.credentials import ( + UNCREDENTIALED_HEADERS, + FetchCredentialTable, + Resolved, + unprovisioned, +) +from src.worker.egress import command_scope, scope_refusal from src.worker.headers import ( HEADER_NAME, HEADER_VALUE, @@ -131,6 +138,9 @@ class RequestOptions(NamedTuple): headers: dict[str, str] | None timeout: float | None render: str = RENDER_HTTP + # Header name, as the issuer spelled it, to a ``fetch-`` reference (#216). + # References only: values are resolved from the host's table, never carried here. + credential_headers: dict[str, str] | None = None class Fetcher(Protocol): @@ -163,6 +173,7 @@ def build_handler( stop: asyncio.Event | None = None, blobs_topic: str = streams.CONTENT_BLOBS, browser_fetcher: Fetcher | None = None, + credentials: FetchCredentialTable | None = None, ) -> Handler: """Wire the byte path into a handler the loop can dispatch to. @@ -212,8 +223,13 @@ def build_handler( ``browser_fetcher`` is where a ``render="browser"`` command goes (#63), and ``None`` means this worker has no browser: the flag is off, or the boot preflight failed. Such a command is parked, **never** fetched over HTTP. + + ``credentials`` is the host's fetch credential table (#216), read at boot. + ``None`` means nothing is provisioned: a command carrying ``credential_headers`` + is refused ``credential_unknown``, never fetched without them. """ publisher = AsyncBusPublisher(client) + credentials = credentials if credentials is not None else unprovisioned() usage = usage if usage is not None else BlobUsage() ceiling = ( settings.blob_max_total_bytes if ceiling_bytes is _CEILING_FROM_SETTINGS else ceiling_bytes @@ -231,6 +247,9 @@ async def handle(command: ContentFetchCommand) -> None: # sweep frees space. A command that can never succeed must not wait a # sweep interval to reach a conclusion available immediately. options = _request_options(command, settings.max_fetch_timeout_seconds) + # Pure too, against the frozen table, and ahead of the ceiling for the same + # reason: a reference nobody provisioned stays unprovisioned until a restart. + scoped = _resolve_credentials(options, command, credentials) selected = _select_fetcher(options, command, fetcher, browser_fetcher) raise_for_ceiling(usage, ceiling) # Last of the three, and after the ceiling on purpose: spending a wait to @@ -240,7 +259,11 @@ async def handle(command: ContentFetchCommand) -> None: # and the ceiling is an inter-sweep estimate either way (CR #9). paced_seconds = await pace(pacer, command, stop=stop, park_above_seconds=park_above_seconds) result = await _fetch( - selected, command, options, deadline_seconds=settings.max_fetch_seconds + selected, + command, + options, + deadline_seconds=settings.max_fetch_seconds, + credentials=scoped, ) # Stamped here rather than at publish: occurred_at is when the fact went # onto the bus, which under a reclaim is minutes after the bytes were on @@ -367,6 +390,8 @@ async def handle(command: ContentFetchCommand) -> None: # exposure one layer down, in a journal a wider set of people # read than can write to the bus. "request_headers": sorted(options.headers or {}), + # Name -> reference: a key, never a value (#216). + "credential_headers": dict(options.credential_headers or {}), "request_timeout_seconds": options.timeout, "render": options.render, # Politeness, on the line that already exists rather than one of @@ -442,14 +467,126 @@ def _request_options(command: ContentFetchCommand, max_timeout: float) -> Reques bytes fetched under conditions it did not ask for. """ headers = _request_headers(command.headers) + credential_headers = _request_credential_names(command.credential_headers, headers) return RequestOptions( headers=headers, timeout=_request_timeout(command.timeout_seconds, max_timeout), - render=_request_render(command.render, headers), + render=_request_render(command.render, headers, credential_headers), + credential_headers=credential_headers, ) -def _request_render(render: str | None, headers: dict[str, str] | None) -> str: +def _request_credential_names( + credential_headers: dict[str, str] | None, headers: dict[str, str] | None +) -> dict[str, str] | None: + """Guard ``credential_headers``' names with ``headers``' rules, folded with them (#216). + + C4: the request-option guards cover the union of both maps. So a name in both + (co-core E3) or twice by case (E4) is a duplicate, and the count bound is over + both. E5's names (``UNCREDENTIALED_HEADERS``) are refused too. The byte bound + needs the resolved values, so it waits for :func:`_resolve_credentials`. + + ``None`` and ``{}`` both mean no credential, and both return ``None``: today's + path. References aren't checked here; resolution closes an unknown one with its + own token. + """ + if not credential_headers: + return None + issued = headers or {} + if len(issued) + len(credential_headers) > MAX_REQUEST_HEADERS: + raise _invalid_options( + f"{len(issued)} headers and {len(credential_headers)} credential headers, " + f"over the {MAX_REQUEST_HEADERS} allowed" + ) + seen: set[str] = set() + for name in credential_headers: + key = name.lower() + if not HEADER_NAME.match(key): + raise _invalid_options(f"credential_headers: {name!r} is not a valid header name") + if key in REFUSED_HEADERS or key.startswith(REFUSED_HEADER_PREFIX): + raise _invalid_options( + f"credential_headers: {name!r} is not a header Replicator will send" + ) + if key in UNCREDENTIALED_HEADERS: + raise _invalid_options(f"credential_headers: {name!r} is never a credential header") + if key in issued: + raise _invalid_options(f"{name!r} is in both headers and credential_headers") + if key in seen: + raise _invalid_options( + f"credential_headers: {name!r} was given more than once, differing only in case" + ) + seen.add(key) + return dict(credential_headers) + + +def _resolve_credentials( + options: RequestOptions, command: ContentFetchCommand, table: FetchCredentialTable +) -> tuple[Resolved, ...]: + """Each reference against the host's table, then the byte bound and the first hop. + + D4 step 2, in order: + + - a reference off ``fetch-``, never provisioned, or dropped at load is + ``credential_unknown``. An off-rule one isn't quoted: ``detail`` is published, + and the likeliest wrong value where a reference belongs is a pasted secret; + - a header other than the binding's is ``credential_refused`` (operator call 3); + - the byte bound over both maps, **the resolved values counted** (C4), is + ``invalid_request_options``. ``len()`` of a ``SecretStr`` reads no value; + - the submitted URL outside any binding's scope is ``credential_refused``. The + transport checks every hop again; this check closes the command before the + ceiling and the pacer spend anything on a request that would never go out. + """ + if not options.credential_headers: + return () + resolved: list[Resolved] = [] + for name, reference in options.credential_headers.items(): + # co-core's validator, which ``fullmatch``es: its exported pattern ends in + # ``$``, which ``match`` would let a trailing newline past. + try: + validate_fetch_credential(reference) + except ValueError: + raise PermanentFetchError( + f"credential_headers[{name!r}] is not a fetch- reference " + "(not quoted: a wrong value here is most often a pasted secret)", + reason=FailureReason.CREDENTIAL_UNKNOWN, + ) from None + credential = table.resolve(reference) + if credential is None: + raise PermanentFetchError( + f"credential_headers[{name!r}] names {reference}, " + "which this host has not provisioned", + reason=FailureReason.CREDENTIAL_UNKNOWN, + ) + if name.lower() != credential.header: + raise PermanentFetchError( + f"credential_headers[{name!r}] names {reference}, " + f"which is bound to the {credential.header!r} header only", + reason=FailureReason.CREDENTIAL_REFUSED, + ) + resolved.append(Resolved(reference, credential)) + total = sum(len(key) + len(value) + 4 for key, value in (options.headers or {}).items()) + total += sum(len(r.credential.header) + len(r.credential.value) + 4 for r in resolved) + if total > MAX_REQUEST_HEADER_BYTES: + raise _invalid_options( + f"headers and credential headers exceed the {MAX_REQUEST_HEADER_BYTES}-byte " + "bound, the resolved values counted" + ) + try: + url = httpx.URL(command.url) + except httpx.InvalidURL as exc: + raise PermanentFetchError( + f"{command.url} is not fetchable: {exc}", reason=FailureReason.NOT_FETCHABLE + ) from exc + if (why := scope_refusal(url, resolved)) is not None: + raise PermanentFetchError(why, reason=FailureReason.CREDENTIAL_REFUSED) + return tuple(resolved) + + +def _request_render( + render: str | None, + headers: dict[str, str] | None, + credential_headers: dict[str, str] | None = None, +) -> str: """The command's render mode, or the refusal that closes it (#63). Two refusals, both co-core's (``FetchFailedEvent``'s docstring lists them), and @@ -470,6 +607,13 @@ def _request_render(render: str | None, headers: dict[str, str] | None) -> str: return RENDER_HTTP if render != RENDER_BROWSER: raise _invalid_options(f"render={render!r} is not one of {sorted(_RENDER_MODES)}") + if credential_headers: + # co-core's E1 (D5): a browser sends a header to every host the page + # contacts, and no per-hop scope exists inside a browser. + raise _invalid_options( + "credential_headers beside render='browser': a browser would send them " + "to every host the page contacts" + ) names = set(headers or {}) if validators := sorted(names & _VALIDATOR_HEADERS): raise _invalid_options( @@ -621,6 +765,7 @@ async def _fetch( options: RequestOptions, *, deadline_seconds: float, + credentials: tuple[Resolved, ...] = (), ) -> FetchResult: """Fetch the command's URL, mapping httpx's failures into the loop's vocabulary. @@ -664,7 +809,7 @@ async def _fetch( to finish on its own, as #100 already accepts. """ try: - with command_scope(): + with command_scope(credentials): async with asyncio.timeout(deadline_seconds) as deadline: return await fetcher.execute( FetchContent(command.url, headers=options.headers, timeout=options.timeout) diff --git a/src/worker/main.py b/src/worker/main.py index 85498670..d1675a48 100644 --- a/src/worker/main.py +++ b/src/worker/main.py @@ -973,7 +973,7 @@ async def run( # The fetch credential table, the same kind of host state (#216): read once, # values included, so a bad value file drops its binding here and not at the # first credentialed fetch. Never raises; unset provisions nothing. - load_fetch_credentials(settings.fetch_credentials_file) + fetch_credentials = load_fetch_credentials(settings.fetch_credentials_file) aliases = load_alias_table( settings.replication_aliases_file, # No alias may bind a bucket this host keeps blobs in (#114). @@ -1187,6 +1187,7 @@ async def run( stop=stop, # render="browser" (#63). None: parked, never fetched over HTTP. browser_fetcher=browser_fetcher, + credentials=fetch_credentials, ), # The other outcome of a command, on the same stream: an issuer # closes a pending entry off one consumer group either way (#9, diff --git a/tests/worker/conftest.py b/tests/worker/conftest.py index 5c3818f9..25faf987 100644 --- a/tests/worker/conftest.py +++ b/tests/worker/conftest.py @@ -30,6 +30,7 @@ from src.core.config import get_settings from src.storage.sweeper import BlobUsage +from src.worker.credentials import FetchCredentialTable from src.worker.handler import build_handler from src.worker.loop import FETCH_SPEC, FailureReport, process_message, run_loop from src.worker.main import build_consumer @@ -185,6 +186,7 @@ def command( timeout_seconds: float | None = None, info_source_id: str = INFO_SOURCE_ID, render: str | None = None, + credential_headers: dict[str, str] | None = None, ) -> ContentFetchCommand: """A decoded ``content.fetch`` command, as the handler receives it. @@ -202,6 +204,7 @@ def command( timeout_seconds=timeout_seconds, info_source_id=info_source_id, render=render, + credential_headers=credential_headers, ) @@ -240,6 +243,7 @@ def build( ceiling_bytes: int | None = _UNSET, browser_fetcher=None, pacer: HostPacer | None = None, + credentials: FetchCredentialTable | None = None, ): return build_handler( fetcher=fetcher or FakeFetcher(), @@ -254,6 +258,7 @@ def build( **({} if blobs_topic is None else {"blobs_topic": blobs_topic}), browser_fetcher=browser_fetcher, pacer=pacer, + **({} if credentials is None else {"credentials": credentials}), ) return build @@ -291,9 +296,19 @@ def make_command( headers: dict[str, str] | None = None, timeout_seconds: float | None = None, info_source_id: str = INFO_SOURCE_ID, + credential_headers: dict[str, str] | None = None, ) -> dict[str, str]: """A well-formed ``content.fetch`` wire frame.""" - return to_wire(command(command_id, url, headers, timeout_seconds, info_source_id)) + return to_wire( + command( + command_id, + url, + headers, + timeout_seconds, + info_source_id, + credential_headers=credential_headers, + ) + ) @pytest.fixture diff --git a/tests/worker/test_credentials.py b/tests/worker/test_credentials.py index 591ebcd4..df6ee5a2 100644 --- a/tests/worker/test_credentials.py +++ b/tests/worker/test_credentials.py @@ -260,6 +260,7 @@ def test_a_reference_off_the_rule_is_dropped_and_not_quoted(tmp_path, caplog, re pytest.param({"header": "if-modified-since"}, "never a credential", id="E5-validator-2"), pytest.param({"hosts": []}, "hosts", id="no-hosts"), pytest.param({"hosts": "api.leg.wa.gov"}, "hosts", id="hosts-a-string"), + pytest.param({"hosts": [7]}, "hostname", id="host-not-a-string"), pytest.param({"hosts": ["https://api.leg.wa.gov"]}, "host", id="host-with-scheme"), pytest.param({"hosts": ["api.leg.wa.gov:443"]}, "host", id="host-with-port"), pytest.param({"hosts": ["bücher.example"]}, "host", id="host-not-punycode"), diff --git a/tests/worker/test_handler_credentials.py b/tests/worker/test_handler_credentials.py new file mode 100644 index 00000000..daf9f0c7 --- /dev/null +++ b/tests/worker/test_handler_credentials.py @@ -0,0 +1,423 @@ +"""The handler's half of fetch credential references (#216, D4 steps 1 and 2). + +``credential_headers`` maps a header name to a ``fetch-`` reference. Before the +ceiling, the pacer or any byte on the wire, the handler: + +1. guards the names with the ``headers`` rules, folded **with** ``headers``, so a + name in both maps (co-core E3) or twice by case (E4) is a duplicate; refuses E5's + names and any credential under ``render="browser"`` (E1). All + ``invalid_request_options``. +2. resolves each reference against the host's frozen table: unknown or off the rule is + ``credential_unknown``; the wrong header for its binding, or a submitted URL + outside every binding's scope, is ``credential_refused``; the byte bound, measured + over the resolved values, is ``invalid_request_options``. + +Every refusal is terminal, before the fetch, and names the header and the reference, +never a value. The per-hop half (redirects) is ``test_egress.py``'s. +""" + +from types import MappingProxyType + +import httpx +import pytest +from co_core.pure.models.changes import FetchFailedEvent +from pydantic import SecretStr + +from src.core.errors import FailureReason, PermanentFetchError, TransientFetchError +from src.storage.sweeper import BlobUsage +from src.worker import egress +from src.worker.credentials import FetchCredential, FetchCredentialTable, Resolved +from src.worker.headers import MAX_REQUEST_HEADER_BYTES, MAX_REQUEST_HEADERS +from src.worker.loop import Outcome, poll_once +from src.worker.reporter import build_failure_reporter +from tests.worker.conftest import ( + GROUP, + TOPIC, + FakeFetcher, + command, + decoded_facts, + make_command, + process_one, +) + +VALUE = "planted-handler-value-91ab" # never a real credential; a tripwire for leaks +URL = "https://api.leg.wa.gov/bills" + + +def credential(header="x-api-key", hosts=("api.leg.wa.gov",), value=VALUE) -> FetchCredential: + return FetchCredential( + header=header, hosts=frozenset(hosts), value=SecretStr(value), value_file="/v" + ) + + +def table(**bindings: FetchCredential) -> FetchCredentialTable: + return FetchCredentialTable( + MappingProxyType({name.replace("_", "-"): cred for name, cred in bindings.items()}) + ) + + +WA = table(fetch_wa_leg_api=credential()) + + +class ScopeRecordingFetcher(FakeFetcher): + """A ``FakeFetcher`` that also records the command scope its fetch ran under. + + Reads the transport's ``ContextVar`` directly: the scope is what the transport + will read on every hop, so it is what the handler is responsible for. + """ + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self.scopes: list[egress.CommandScope | None] = [] + + async def execute(self, effect): + self.scopes.append(egress._COMMAND_SCOPE.get()) + return await super().execute(effect) + + +async def refused(handler, cmd, reason, *, credentials=WA, **build) -> PermanentFetchError: + fetcher = FakeFetcher() + with pytest.raises(PermanentFetchError) as caught: + await handler(fetcher, credentials=credentials, **build)(cmd) + assert caught.value.reason is reason + assert fetcher.effects == [], "refused before the fetch, not after" + assert VALUE not in str(caught.value) + return caught.value + + +# --- None and {} are today's path --------------------------------------------------- + + +@pytest.mark.parametrize("credential_headers", [None, {}]) +async def test_no_credentials_is_todays_path(handler, credential_headers): + fetcher = ScopeRecordingFetcher() + + await handler(fetcher, credentials=WA)(command(credential_headers=credential_headers)) + + assert fetcher.effect.headers is None + [scope] = fetcher.scopes + assert scope is not None and scope.credentials == () + + +async def test_a_resolved_credential_rides_the_scope_and_never_the_effect(handler): + """The value goes to the transport through the scope; ``FetchContent`` never holds it.""" + fetcher = ScopeRecordingFetcher() + + await handler(fetcher, credentials=WA)( + command(url=URL, credential_headers={"X-Api-Key": "fetch-wa-leg-api"}) + ) + + assert fetcher.effect.headers is None + [scope] = fetcher.scopes + assert scope.credentials == (Resolved("fetch-wa-leg-api", WA.resolve("fetch-wa-leg-api")),) + assert VALUE not in repr(fetcher.effect) + + +async def test_the_scope_is_reset_after_the_fetch(handler): + await handler(ScopeRecordingFetcher(), credentials=WA)( + command(url=URL, credential_headers={"X-Api-Key": "fetch-wa-leg-api"}) + ) + + assert egress._COMMAND_SCOPE.get() is None + + +# --- Step 1: the name guards, folded with headers ----------------------------------- + + +@pytest.mark.parametrize( + ("credential_headers", "headers", "names"), + [ + pytest.param({"X Api Key": "fetch-wa-leg-api"}, None, "X Api Key", id="not-a-token"), + pytest.param({"Host": "fetch-wa-leg-api"}, None, "Host", id="refused"), + pytest.param( + {"Proxy-Authorization": "fetch-wa-leg-api"}, None, "Proxy-Authorization", id="proxy" + ), + pytest.param( + {"X-Api-Key": "fetch-wa-leg-api"}, {"x-api-key": "plain"}, "X-Api-Key", id="E3" + ), + pytest.param( + {"X-Api-Key": "fetch-wa-leg-api", "x-api-key": "fetch-wa-leg-api"}, + None, + "x-api-key", + id="E4", + ), + pytest.param({"User-Agent": "fetch-wa-leg-api"}, None, "User-Agent", id="E5-ua"), + pytest.param({"If-None-Match": "fetch-wa-leg-api"}, None, "If-None-Match", id="E5-inm"), + pytest.param( + {"if-modified-since": "fetch-wa-leg-api"}, None, "if-modified-since", id="E5-ims" + ), + ], +) +async def test_an_unsendable_credential_name_is_refused( + handler, credential_headers, headers, names +): + error = await refused( + handler, + command(url=URL, headers=headers, credential_headers=credential_headers), + FailureReason.INVALID_REQUEST_OPTIONS, + ) + + assert names in str(error) + + +async def test_the_count_bound_is_over_both_maps(handler): + headers = {f"x-h{index}": "v" for index in range(MAX_REQUEST_HEADERS)} + + await refused( + handler, + command(url=URL, headers=headers, credential_headers={"X-Api-Key": "fetch-wa-leg-api"}), + FailureReason.INVALID_REQUEST_OPTIONS, + ) + + +async def test_any_credential_under_browser_is_refused_before_the_table(handler): + """E1 (D5): a browser sends a header to every host a page contacts; no hop scope exists.""" + error = await refused( + handler, + command(url=URL, render="browser", credential_headers={"X-Api-Key": "fetch-wa-leg-api"}), + FailureReason.INVALID_REQUEST_OPTIONS, + browser_fetcher=FakeFetcher(), + ) + + assert "browser" in str(error) + + +async def test_an_unsendable_name_is_refused_even_with_nothing_provisioned(handler): + """Step 1 is pure and comes first: the issuer hears the shape error, not the table's.""" + await refused( + handler, + command(url=URL, credential_headers={"Host": "fetch-wa-leg-api"}), + FailureReason.INVALID_REQUEST_OPTIONS, + credentials=table(), + ) + + +# --- Step 2: resolution against the table ------------------------------------------- + + +async def test_an_unprovisioned_reference_is_credential_unknown(handler): + error = await refused( + handler, + command(url=URL, credential_headers={"X-Api-Key": "fetch-or-leg-api"}), + FailureReason.CREDENTIAL_UNKNOWN, + ) + + assert "X-Api-Key" in str(error) + assert "fetch-or-leg-api" in str(error) + + +async def test_nothing_provisioned_by_default(handler): + """``build_handler`` without a table provisions nothing: refused, never sent bare.""" + fetcher = FakeFetcher() + with pytest.raises(PermanentFetchError) as caught: + await handler(fetcher)( + command(url=URL, credential_headers={"X-Api-Key": "fetch-wa-leg-api"}) + ) + + assert caught.value.reason is FailureReason.CREDENTIAL_UNKNOWN + assert fetcher.effects == [] + + +@pytest.mark.parametrize("reference", ["gcs-publication", "sk_live_51HpastedSecret", ""]) +async def test_a_reference_off_the_rule_is_unknown_and_never_quoted(handler, reference): + """The likeliest off-rule reference is a pasted secret, and ``detail`` is published.""" + error = await refused( + handler, + command(url=URL, credential_headers={"X-Api-Key": reference}), + FailureReason.CREDENTIAL_UNKNOWN, + ) + + assert "X-Api-Key" in str(error) + if reference: + assert reference not in str(error) + + +async def test_a_header_other_than_the_bindings_is_credential_refused(handler): + """Operator call 3: a binding pins its header, so the value can't ride an echoed one.""" + error = await refused( + handler, + command(url=URL, credential_headers={"Referer": "fetch-wa-leg-api"}), + FailureReason.CREDENTIAL_REFUSED, + ) + + assert "Referer" in str(error) and "fetch-wa-leg-api" in str(error) + assert "x-api-key" in str(error) + + +async def test_the_bindings_header_matches_whatever_the_case(handler): + fetcher = ScopeRecordingFetcher() + + await handler(fetcher, credentials=WA)( + command(url=URL, credential_headers={"X-API-KEY": "fetch-wa-leg-api"}) + ) + + assert fetcher.scopes[0].credentials == ( + Resolved("fetch-wa-leg-api", WA.resolve("fetch-wa-leg-api")), + ) + + +async def test_the_byte_bound_counts_the_resolved_values(handler): + """C4: measured over what goes on the wire, so the reference's length is beside the point.""" + big = table(fetch_wa_leg_api=credential(value="v" * (MAX_REQUEST_HEADER_BYTES - 20))) + + error = await refused( + handler, + command( + url=URL, + headers={"accept": "a" * 40}, + credential_headers={"X-Api-Key": "fetch-wa-leg-api"}, + ), + FailureReason.INVALID_REQUEST_OPTIONS, + credentials=big, + ) + + assert "byte" in str(error) + + +@pytest.mark.parametrize( + "url", + [ + pytest.param("http://api.leg.wa.gov/bills", id="http"), + pytest.param("https://api.leg.wa.gov:8443/bills", id="another-port"), + pytest.param("https://www.leg.wa.gov/bills", id="another-host"), + pytest.param("https://leg.wa.gov/bills", id="the-parent-domain"), + pytest.param("https://evil.api.leg.wa.gov/bills", id="a-subdomain"), + ], +) +async def test_a_submitted_url_outside_the_scope_is_credential_refused(handler, url): + error = await refused( + handler, + command(url=url, credential_headers={"X-Api-Key": "fetch-wa-leg-api"}), + FailureReason.CREDENTIAL_REFUSED, + ) + + assert "fetch-wa-leg-api" in str(error) + + +@pytest.mark.parametrize( + "url", + [ + "https://API.Leg.WA.gov/bills", + "https://api.leg.wa.gov./bills", + "https://api.leg.wa.gov:443/bills", + ], +) +async def test_the_scope_compares_the_canonical_host(handler, url): + fetcher = ScopeRecordingFetcher() + + await handler(fetcher, credentials=WA)( + command(url=url, credential_headers={"X-Api-Key": "fetch-wa-leg-api"}) + ) + + assert fetcher.effects + + +async def test_an_idna_host_is_compared_in_punycode(handler): + bucher = table(fetch_books=credential(hosts=("xn--bcher-kva.example",))) + fetcher = ScopeRecordingFetcher() + + await handler(fetcher, credentials=bucher)( + command(url="https://Bücher.example/x", credential_headers={"X-Api-Key": "fetch-books"}) + ) + + assert fetcher.effects + + +async def test_every_binding_must_cover_the_host(handler): + """Two credentials on one command: the hop must be in scope for both, or neither is sent.""" + two = table( + fetch_wa_leg_api=credential(), + fetch_other=credential(header="x-other", hosts=("other.example",)), + ) + + error = await refused( + handler, + command( + url=URL, + credential_headers={"X-Api-Key": "fetch-wa-leg-api", "X-Other": "fetch-other"}, + ), + FailureReason.CREDENTIAL_REFUSED, + credentials=two, + ) + + assert "fetch-other" in str(error) + + +# --- Ordering: before the ceiling and the pacer ------------------------------------- + + +async def test_a_credential_refusal_comes_before_the_ceiling(handler): + """A full store parks a command transiently; a refused one must close now, not wait.""" + usage = BlobUsage() + usage.add(10) + + with pytest.raises(PermanentFetchError) as caught: + await handler(FakeFetcher(), credentials=WA, usage=usage, ceiling_bytes=1)( + command(url=URL, credential_headers={"X-Api-Key": "fetch-or-leg-api"}) + ) + + assert caught.value.reason is FailureReason.CREDENTIAL_UNKNOWN + assert not isinstance(caught.value, TransientFetchError) + + +# --- The fact the issuer hears ------------------------------------------------------ + + +async def test_a_refusal_closes_with_a_terminal_fact_that_names_no_value( + fake_redis, consumer, settings, handler, caplog +): + """Terminal, no status, no attempts; the header and reference named; no value anywhere.""" + await fake_redis.xadd( + TOPIC, + make_command( + command_id="cmd-cred", + url="https://www.leg.wa.gov/x", + credential_headers={"X-Api-Key": "fetch-wa-leg-api"}, + ), + ) + message = (await poll_once(fake_redis, consumer, settings, group=GROUP))[0] + + with caplog.at_level("DEBUG"): + outcome = await process_one( + fake_redis, + consumer, + settings, + message, + handler(credentials=WA), + reporter=build_failure_reporter(client=fake_redis), + ) + + assert outcome is Outcome.DEAD_LETTERED + raw = await fake_redis.xrange("content.blobs") + assert VALUE not in str(raw) + [fact] = await decoded_facts(fake_redis, "content.blobs") + assert isinstance(fact, FetchFailedEvent) + assert fact.reason == "credential_refused" + assert fact.terminal is True + assert fact.status_code is None + assert fact.attempts is None + assert "x-api-key" in fact.detail.lower() and "fetch-wa-leg-api" in fact.detail + assert VALUE not in caplog.text + + +async def test_a_reference_with_a_trailing_newline_is_off_the_rule(handler): + """co-core's pattern ends in ``$``; the rule is checked whole, so ``\\n`` can't ride it.""" + await refused( + handler, + command(url=URL, credential_headers={"X-Api-Key": "fetch-wa-leg-api\n"}), + FailureReason.CREDENTIAL_UNKNOWN, + ) + + +async def test_an_unparseable_url_with_credentials_is_not_fetchable(handler): + """The scope check parses the URL first; one httpx can't parse closes as ``_fetch`` would.""" + await refused( + handler, + command(url="https://a.example:abc/", credential_headers={"X-Api-Key": "fetch-wa-leg-api"}), + FailureReason.NOT_FETCHABLE, + ) + + +def test_no_credentials_are_never_out_of_scope(): + """An anonymous hop has no scope to leave: any scheme, port and host pass.""" + assert egress.scope_refusal(httpx.URL("http://127.0.0.1:8080/"), ()) is None diff --git a/tests/worker/test_main.py b/tests/worker/test_main.py index 22725075..ff331a5d 100644 --- a/tests/worker/test_main.py +++ b/tests/worker/test_main.py @@ -1896,9 +1896,19 @@ async def test_the_boot_reads_the_fetch_credential_table(monkeypatch, fake_redis monkeypatch.setenv("REPLICATOR_BLOB_DIR", str(tmp_path / "blobs")) monkeypatch.setenv("REPLICATOR_FETCH_CREDENTIALS_FILE", str(table)) monkeypatch.setattr("src.worker.main.Redis.from_url", lambda *a, **kw: fake_redis) + seen = {} + real_build_handler = src.worker.main.build_handler + + def recording_build_handler(**kwargs): + seen["credentials"] = kwargs.get("credentials") + return real_build_handler(**kwargs) + + monkeypatch.setattr("src.worker.main.build_handler", recording_build_handler) await run(_stopped()) + # The table the boot read is the one the fetch handler resolves against. + assert seen["credentials"].provisioned == ("fetch-wa-leg-api",) out = capsys.readouterr().out lines = [json.loads(line) for line in out.splitlines() if line.strip()] [loaded] = [line for line in lines if line.get("message") == "fetch credentials loaded"] From 5616960635935f55ae7c26c1cacd5d378593e708 Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 17:20:14 +0000 Subject: [PATCH 06/23] #216 feat: scope each credential per hop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit D3. CommandScopeTransport, outermost, checks every hop against every credential in the command's scope before anything below it runs: https only, port 443 only (call 4), the host — raw_host, canonical — in every binding's hosts. A hop out of scope raises credential_refused and is never sent; out of scope and in a refused range is credential_refused, with no DNS lookup (call 5). A hop in scope carries each credential on the copy it sends; the request httpx holds is never mutated, so a later hop starts without it. This is the only get_secret_value() call site. A Cookie credential is followed by the command's jar cookies in the same field. A forced mid-fetch failure's logged traceback, and the facts, carry no value; both mutations (a leaking error message, an in-place header) fail the tests. Co-Authored-By: Claude Opus 5.5 --- src/worker/egress.py | 32 ++++- tests/worker/test_egress.py | 254 +++++++++++++++++++++++++++++++++++- 2 files changed, 283 insertions(+), 3 deletions(-) diff --git a/src/worker/egress.py b/src/worker/egress.py index 9291b430..73bb1874 100644 --- a/src/worker/egress.py +++ b/src/worker/egress.py @@ -379,9 +379,18 @@ class CommandScopeTransport(httpx.AsyncBaseTransport): set on the handed request would ride every later hop, a cross-origin one included [measured 2026-11-23]. + **Credentials** (C2, C3): with any in scope, a hop that :func:`scope_refusal` + refuses raises ``credential_refused`` before anything below runs, the guard's + DNS lookup included (operator call 5). A hop in scope carries each credential + header; this is the one place a value is read (``get_secret_value``), and + ``tests/test_boundaries.py`` pins that. + **Cookies** are the scope's: added before the hop with httpx's public ``set_cookie_header``, which leaves a ``Cookie`` the issuer sent alone, as the - client's jar did, and taken from the response with ``extract_cookies``. + client's jar did, and taken from the response with ``extract_cookies``. A + ``Cookie`` credential is followed by the jar's cookies in the same field + (``; ``), so a session the origin mints on top of it survives + the redirect chain. """ def __init__(self, inner: httpx.AsyncBaseTransport) -> None: @@ -391,6 +400,8 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response: scope = _COMMAND_SCOPE.get() if scope is None: raise RuntimeError(f"{request.url} was requested outside a command scope: refused") + if (why := scope_refusal(request.url, scope.credentials)) is not None: + raise PermanentFetchError(why, reason=FailureReason.CREDENTIAL_REFUSED) outgoing = httpx.Request( request.method, request.url, @@ -398,7 +409,13 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response: stream=request.stream, extensions=request.extensions, ) - scope.cookies.set_cookie_header(outgoing) + for _, credential in scope.credentials: + outgoing.headers[credential.header] = credential.value.get_secret_value() + if "cookie" in {credential.header for _, credential in scope.credentials}: + if jar := _jar_cookies(scope.cookies, outgoing): + outgoing.headers["cookie"] = f"{outgoing.headers['cookie']}; {jar}" + else: + scope.cookies.set_cookie_header(outgoing) response = await self._inner.handle_async_request(outgoing) response.request = outgoing scope.cookies.extract_cookies(response) @@ -408,6 +425,17 @@ async def aclose(self) -> None: await self._inner.aclose() +def _jar_cookies(cookies: httpx.Cookies, request: httpx.Request) -> str | None: + """The ``Cookie`` field the jar would add to ``request``, worked out on a bare probe. + + ``set_cookie_header`` adds nothing to a request that already carries a ``Cookie``, + and a ``Cookie`` credential is one; so the jar's half is computed apart, then joined. + """ + probe = httpx.Request(request.method, request.url) + cookies.set_cookie_header(probe) + return probe.headers.get("cookie") + + class BodyCeilingTransport(httpx.AsyncBaseTransport): """Stop reading a body at the blob ceiling, rather than after its last byte (#104). diff --git a/tests/worker/test_egress.py b/tests/worker/test_egress.py index 0d9932c5..5204b09e 100644 --- a/tests/worker/test_egress.py +++ b/tests/worker/test_egress.py @@ -21,13 +21,16 @@ import asyncio import ipaddress +import logging import re import socket +from types import MappingProxyType import httpx import pytest from co_core.effects.fetch import FetchContent from co_core_aio.fetch import AsyncFetchDriver +from pydantic import SecretStr from src.core.errors import ( FailureReason, @@ -36,6 +39,7 @@ TransientError, TransientFetchError, ) +from src.worker.credentials import FetchCredential, FetchCredentialTable, Resolved from src.worker.egress import ( DEFAULT_BLOCKED_DESTINATIONS, RESOLVE_TIMEOUT_SECONDS, @@ -46,7 +50,9 @@ command_scope, never_storing_cookies, ) -from tests.worker.conftest import command +from src.worker.loop import poll_once +from src.worker.reporter import build_failure_reporter +from tests.worker.conftest import GROUP, TOPIC, command, make_command, process_one def _never_called(request: httpx.Request) -> httpx.Response: # pragma: no cover - asserts @@ -998,3 +1004,249 @@ async def test_every_command_the_handler_runs_has_its_own_scope(handler): await handle(command(command_id="cmd-2", url="https://a.example/later")) assert seen == [("/plant", None), ("/later", None)] + + +# --- Credentials per hop (#216, D3): in scope or not sent, and never by mutation ------- + +VALUE = "planted-egress-value-c4d2" # never a real credential; a tripwire for leaks + + +def _resolved(header="x-api-key", hosts=("api.leg.wa.gov",), reference="fetch-wa-leg-api"): + return Resolved( + reference, + FetchCredential( + header=header, hosts=frozenset(hosts), value=SecretStr(VALUE), value_file="/v" + ), + ) + + +def _recording_origin(seen: list[httpx.Request], routes: dict[str, httpx.Response] | None = None): + def origin(request: httpx.Request) -> httpx.Response: + seen.append(request) + for path, response in (routes or {}).items(): + if request.url.path == path: + return response + return httpx.Response(200, text="ok") + + return origin + + +async def _get(origin, url: str, *credentials: Resolved) -> httpx.Response: + async with _scoped_client(origin) as client: + with command_scope(credentials): + return await AsyncFetchDriver(client).execute(FetchContent(url)) + + +async def test_an_in_scope_credential_is_sent_on_every_hop(): + seen: list[httpx.Request] = [] + origin = _recording_origin(seen, {"/a": httpx.Response(302, headers={"location": "/b"})}) + + await _get(origin, "https://api.leg.wa.gov/a", _resolved()) + + assert [r.url.path for r in seen] == ["/a", "/b"] + assert [r.headers.get("x-api-key") for r in seen] == [VALUE, VALUE] + + +async def test_a_cross_origin_redirect_is_refused_before_the_hop_is_sent(): + """C2, C3: the hop is refused, not sent bare. The other host receives nothing at all.""" + seen: list[httpx.Request] = [] + origin = _recording_origin( + seen, {"/a": httpx.Response(302, headers={"location": "https://other.example/land"})} + ) + + with pytest.raises(PermanentFetchError) as raised: + await _get(origin, "https://api.leg.wa.gov/a", _resolved()) + + assert raised.value.reason is FailureReason.CREDENTIAL_REFUSED + assert [str(r.url) for r in seen] == ["https://api.leg.wa.gov/a"] + assert "other.example" in str(raised.value) and "fetch-wa-leg-api" in str(raised.value) + assert VALUE not in str(raised.value) + + +@pytest.mark.parametrize( + "location", + [ + pytest.param("http://api.leg.wa.gov/b", id="https-to-http"), + pytest.param("https://api.leg.wa.gov:8443/b", id="another-port"), + pytest.param("https://evil.api.leg.wa.gov/b", id="a-subdomain"), + ], +) +async def test_a_redirect_off_the_scheme_port_or_host_is_refused(location): + seen: list[httpx.Request] = [] + origin = _recording_origin(seen, {"/a": httpx.Response(302, headers={"location": location})}) + + with pytest.raises(PermanentFetchError) as raised: + await _get(origin, "https://api.leg.wa.gov/a", _resolved()) + + assert raised.value.reason is FailureReason.CREDENTIAL_REFUSED + assert len(seen) == 1 + + +async def test_a_first_hop_over_http_is_refused_at_the_transport_too(): + """The handler checks the submitted URL; the transport doesn't rely on it.""" + with pytest.raises(PermanentFetchError) as raised: + await _get(_never_called, "http://api.leg.wa.gov/a", _resolved()) + + assert raised.value.reason is FailureReason.CREDENTIAL_REFUSED + + +@pytest.mark.parametrize( + ("url", "hosts"), + [ + pytest.param("https://Bücher.example/a", ("xn--bcher-kva.example",), id="idna"), + pytest.param("https://api.leg.wa.gov./a", ("api.leg.wa.gov",), id="trailing-dot"), + pytest.param("https://API.LEG.WA.GOV/a", ("api.leg.wa.gov",), id="upper-case"), + ], +) +async def test_the_hop_host_is_compared_in_its_canonical_form(url, hosts): + seen: list[httpx.Request] = [] + + await _get(_recording_origin(seen), url, _resolved(hosts=hosts)) + + assert seen[0].headers["x-api-key"] == VALUE + + +async def test_the_unicode_host_is_never_what_is_compared(): + """``url.host`` is IDNA-decoded; a binding written in unicode would never match it.""" + with pytest.raises(PermanentFetchError): + await _get(_never_called, "https://Bücher.example/a", _resolved(hosts=("bücher.example",))) + + +async def test_every_credential_must_admit_the_hop(): + seen: list[httpx.Request] = [] + + with pytest.raises(PermanentFetchError) as raised: + await _get( + _recording_origin(seen), + "https://api.leg.wa.gov/a", + _resolved(), + _resolved(header="x-other", hosts=("other.example",), reference="fetch-other"), + ) + + assert raised.value.reason is FailureReason.CREDENTIAL_REFUSED + assert "fetch-other" in str(raised.value) + assert seen == [] + + +async def test_the_credential_never_lands_on_the_request_httpx_holds(): + """httpx builds the next hop from the handed request: the credential must not be on it.""" + seen: list[httpx.Request] = [] + transport = CommandScopeTransport(httpx.MockTransport(_recording_origin(seen))) + handed = httpx.Request("GET", "https://api.leg.wa.gov/a") + + with command_scope((_resolved(),)): + await transport.handle_async_request(handed) + + assert seen[0].headers["x-api-key"] == VALUE + assert "x-api-key" not in handed.headers + + +async def test_a_cookie_credential_keeps_the_session_minted_on_top_of_it(): + """``; ``: the origin's session cookie survives the redirect chain.""" + seen: list[httpx.Request] = [] + origin = _recording_origin( + seen, + {"/a": httpx.Response(302, headers={"location": "/b", "set-cookie": "sid=abc; Path=/"})}, + ) + + await _get(origin, "https://api.leg.wa.gov/a", _resolved(header="cookie")) + + assert [r.headers.get("cookie") for r in seen] == [VALUE, f"{VALUE}; sid=abc"] + + +async def test_an_anonymous_scope_sends_what_a_plain_client_sends(): + """No credential, no cookie: the hop goes out header for header as it did before #216.""" + plain: list[httpx.Request] = [] + scoped: list[httpx.Request] = [] + + async with httpx.AsyncClient(transport=httpx.MockTransport(_recording_origin(plain))) as client: + await AsyncFetchDriver(client).execute(FetchContent("https://a.example/x")) + await _get(_recording_origin(scoped), "https://a.example/x") + + assert list(scoped[0].headers.multi_items()) == list(plain[0].headers.multi_items()) + assert scoped[0].url == plain[0].url + + +async def test_out_of_scope_and_in_a_refused_range_is_credential_refused(): + """Operator call 5: the scope check is pure and outermost, so it answers before DNS.""" + resolved_hosts: list[str] = [] + + async def resolve(host: str, port: int) -> list[str]: # pragma: no cover - asserts + resolved_hosts.append(host) + return ["127.0.0.1"] + + client = httpx.AsyncClient( + transport=CommandScopeTransport( + GuardedTransport( + httpx.MockTransport(_never_called), blocked=blocked_networks(None), resolve=resolve + ) + ), + cookies=never_storing_cookies(), + ) + async with client: + with command_scope((_resolved(),)), pytest.raises(PermanentFetchError) as raised: + await client.get("https://shelley.invalid/") + + assert raised.value.reason is FailureReason.CREDENTIAL_REFUSED + assert resolved_hosts == [] + + +async def test_a_hop_refusal_reaches_the_handler_through_the_real_driver(handler): + """Out through httpx's redirect loop and ``_fetch`` unchanged: terminal, not transient.""" + seen: list[httpx.Request] = [] + origin = _recording_origin( + seen, {"/a": httpx.Response(302, headers={"location": "https://other.example/"})} + ) + table = FetchCredentialTable(MappingProxyType({"fetch-wa-leg-api": _resolved().credential})) + + async with _scoped_client(origin) as client: + with pytest.raises(PermanentFetchError) as raised: + await handler(AsyncFetchDriver(client), credentials=table)( + command( + url="https://api.leg.wa.gov/a", + credential_headers={"X-Api-Key": "fetch-wa-leg-api"}, + ) + ) + + assert raised.value.reason is FailureReason.CREDENTIAL_REFUSED + assert len(seen) == 1 and seen[0].headers["x-api-key"] == VALUE + + +async def test_no_value_in_the_journal_when_the_wire_fails_mid_fetch( + fake_redis, consumer, settings, handler, caplog +): + """A forced, unclassified failure after the credential is attached: the traceback the + loop logs names the error, and never the value the request carried.""" + + def exploding(request: httpx.Request) -> httpx.Response: + raise ValueError(f"the origin broke on {request.url}") + + table = FetchCredentialTable(MappingProxyType({"fetch-wa-leg-api": _resolved().credential})) + await fake_redis.xadd( + TOPIC, + make_command( + command_id="cmd-boom", + url="https://api.leg.wa.gov/a", + credential_headers={"X-Api-Key": "fetch-wa-leg-api"}, + ), + ) + message = (await poll_once(fake_redis, consumer, settings, group=GROUP))[0] + + async with _scoped_client(exploding) as client: + with caplog.at_level("DEBUG"): + await process_one( + fake_redis, + consumer, + settings, + message, + handler(AsyncFetchDriver(client), credentials=table), + reporter=build_failure_reporter(client=fake_redis), + ) + + assert any(r.exc_info or r.exc_text for r in caplog.records), "no traceback was logged" + journal = caplog.text + "".join( + logging.Formatter().formatException(r.exc_info) for r in caplog.records if r.exc_info + ) + assert "the origin broke" in journal + assert VALUE not in journal + assert VALUE not in str(await fake_redis.xrange("content.blobs")) From a0372c881f8499a031ed28dad7e66b3908216b9c Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 17:22:25 +0000 Subject: [PATCH 07/23] #216 test: the reference is a key, the value is the transport's MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The charter's §2c, mirroring §2b's alias scan with one deliberate difference: a refusal's detail names the reference, so the issuer knows which binding to provision. So the legal uses of a reference bound by the credential_headers .items() loop are a lookup, the validator, Resolved, or a placeholder in a PermanentFetchError message; a compare, a store or a path built from one fails. The map's values are reachable no other way, the field is read in handler.py alone, and get_secret_value() has one call site: the scope transport. Planted-violation tests for each detector; mutations of the real handler (a startswith on a reference, a second secret read) fail it. The charter gains the credential-reference paragraph, the taxonomy rows, and both enforcement rows. Co-Authored-By: Claude Opus 5.5 --- docs/contracts/replicator-boundaries.md | 15 +- tests/test_boundaries.py | 257 ++++++++++++++++++++++++ 2 files changed, 269 insertions(+), 3 deletions(-) diff --git a/docs/contracts/replicator-boundaries.md b/docs/contracts/replicator-boundaries.md index f6b6918e..42eee350 100644 --- a/docs/contracts/replicator-boundaries.md +++ b/docs/contracts/replicator-boundaries.md @@ -102,8 +102,8 @@ written line rather than into a vacuum. | Channel | Carries | Examples | |---|---|---| -| **env** | facts about *this host* | blob TTL, disk ceiling, claim cadence, dedupe TTL | -| **command** | this occasion | `headers`, `timeout_seconds`, later a fetch `strategy` | +| **env** | facts about *this host* | blob TTL, disk ceiling, claim cadence, dedupe TTL, the paths to the alias and fetch credential tables | +| **command** | this occasion | `headers`, `timeout_seconds`, `render`, a `credential_headers` reference | | **config stream** | cluster policy needing cross-command state | per-host politeness | Env settings carry the `REPLICATOR_` prefix so they never collide with a sibling service's — the @@ -112,6 +112,14 @@ cohort convention, kept from when four services shared one VM (#88). **`BUILD_ID mean a per-service variable name for one git SHA. It is exempted by name in the test, not waved through — an exemption list that grows is this convention ending quietly. +**A credential reference is a key, and the value never travels (#216, cannobserv#577).** +`credential_headers` maps a header name to a `fetch-` reference; the binding it names, and +the secret, are host state read at boot, as the alias table is. So env carries the table's path, +the command carries this occasion's reference, and the value rides neither. It passes the three +tests: no per-resource history (cookies now live *shorter*, one command), coordination over a +resource only the fetcher can see (the secret, and the redirect hops only the transport sees), and +no domain vocabulary (a header name, a reference, hostnames). Its scan is §2c of the tests. + **The fourth channel is rejected by name: an inbound admin HTTP API.** It is the easy path for every future config need and it ends the property that makes this service testable and relocatable. @@ -351,7 +359,8 @@ is failing a PR, not documenting an intention. | No domain vocabulary | AST scan of `src/`: `info_source`, `info_item`, `watched_item`, `tenant`, `aspect` appear in no identifier and no string literal — exact `info_source_id` and `info_item_rep_spec_id` exempted in the emit-path modules only, per token | | The echoed keys are never interpreted | AST scan of `src/`: every occurrence of either echoed field is a field declaration, a parameter, the keyword named for **itself**, or that keyword's value; all else fails | | Ingress is read-only | recursive route walk: every path in the allowlist, every method in `{GET, HEAD}` | -| The deployed process has no ingress | `src/worker/` imports no server framework; the unit runs `src.worker.main` with no `uvicorn` and no `--port` | +| The credential reference is a key; the value is the transport's | AST scan of `src/`: `credential_headers` is read in `handler.py` alone; a reference bound by its `.items()` loop is only a lookup, validator or `Resolved` argument, or a placeholder in a `PermanentFetchError` message — never compared, stored or made a path; the map's values are reached no other way; `get_secret_value()` has one call site, `CommandScopeTransport.handle_async_request` (#216) | +| The deployed process has no ingress | `src/worker/` imports no server framework — `http.server` by name, so `http.cookiejar` (the fetch client's never-storing jar, #216) stays legal; the unit runs `src.worker.main` with no `uvicorn` and no `--port` | | No locally-defined wire models | no class in `src/` declares an `event_type` field — every wire payload comes from co-core | | No issuer SDK | no dependency on a sibling repo's client in the lock | | Config surface | every `Settings` field is `REPLICATOR_*`-prefixed except `build_id`, exempted by name; no `env_file`; no configuration or network call at import time | diff --git a/tests/test_boundaries.py b/tests/test_boundaries.py index bf69f48d..9b8d0155 100644 --- a/tests/test_boundaries.py +++ b/tests/test_boundaries.py @@ -893,6 +893,263 @@ def test_the_credential_detector_passes_a_host_resolved_credential(): assert not _credential_feeds(ast.parse(source)) +# -------------------------------------------------------------------------- +# 2c. The credential reference is a key; the value is the transport's (#216) +# -------------------------------------------------------------------------- + +# §2b's mirror for ``content.fetch``'s ``credential_headers`` (cannobserv#577, C1). +# The map's *values* are references: ``fetch-`` names of bindings an operator +# provisioned on this host. The binding holds the secret; the bus never does. +# +# Not §2b's scan reused, because one rule differs on purpose: a refusal's +# ``detail`` **names** the reference, so the issuer can tell which binding to +# provision. A reference is a key and safe to show; what must never happen is +# Replicator *interpreting* one — comparing it, storing it, or building a path from +# it — instead of looking it up in the host's table. So the legal uses of a +# reference are: the argument to a lookup, the validator, or ``Resolved``, and a +# placeholder in a ``PermanentFetchError`` message. Everything else is flagged. +CREDENTIAL_FIELD = "credential_headers" + +# Where the field may be read at all. The handler alone: ``credentials.py`` deals +# in bindings read from host config, and ``egress.py`` in resolved pairs. +CREDENTIAL_FIELD_MODULES = frozenset({"src/worker/handler.py"}) + +REFERENCE_LOOKUPS = frozenset({"resolve", "validate_fetch_credential", "Resolved"}) +REFERENCE_MESSAGES = frozenset({"PermanentFetchError"}) + +# The one function that reads a value (D2): the transport, as it builds a hop. +SECRET_READER = ("src/worker/egress.py", "CommandScopeTransport.handle_async_request") + + +def _call_name(call: ast.Call) -> str | None: + func = call.func + if isinstance(func, ast.Attribute): + return func.attr + if isinstance(func, ast.Name): + return func.id + return None + + +def _is_items_of_the_field(node: ast.AST) -> bool: + return ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "items" + and isinstance(node.func.value, ast.Attribute) + and node.func.value.attr == CREDENTIAL_FIELD + ) + + +def _reference_loops(tree: ast.AST) -> list[tuple[ast.For, str]]: + """Each ``for name, reference in .credential_headers.items()``, with its reference name.""" + loops = [] + for node in ast.walk(tree): + if ( + isinstance(node, ast.For) + and _is_items_of_the_field(node.iter) + and isinstance(node.target, ast.Tuple) + and len(node.target.elts) == 2 + and isinstance(node.target.elts[1], ast.Name) + ): + loops.append((node, node.target.elts[1].id)) + return loops + + +def _reference_use_is_legal(node: ast.Name, parent: dict[int, ast.AST]) -> bool: + context = parent.get(id(node)) + if isinstance(context, ast.Call) and node in context.args: + return _call_name(context) in REFERENCE_LOOKUPS + if isinstance(context, ast.FormattedValue): + joined = parent.get(id(context)) + call = parent.get(id(joined)) + return ( + isinstance(call, ast.Call) + and joined in call.args + and _call_name(call) in REFERENCE_MESSAGES + ) + return False + + +def _reference_violations(tree: ast.AST) -> list[str]: + """Every use of a reference, or read of the map's values, that isn't a lookup. + + Two shapes are flagged: + + 1. a reference bound by the ``.items()`` loop and then used other than as a + lookup argument or a refusal message's placeholder; + 2. the map's values reached any other way — a subscript, ``.values()``, + ``.get()`` — which would put a reference somewhere this scan can't follow. + """ + parent = _parents(tree) + violations: list[str] = [] + for node in ast.walk(tree): + if isinstance(node, ast.Attribute) and node.attr == CREDENTIAL_FIELD: + context = parent.get(id(node)) + if isinstance(context, ast.Subscript) and context.value is node: + violations.append(f"line {node.lineno}: .{CREDENTIAL_FIELD}[...] reads a reference") + elif isinstance(context, ast.Attribute) and context.attr in { + "values", + "get", + "pop", + "setdefault", + "popitem", + }: + violations.append( + f"line {node.lineno}: .{CREDENTIAL_FIELD}.{context.attr} reads a reference" + ) + for loop, reference in _reference_loops(tree): + for statement in loop.body: + for node in ast.walk(statement): + if ( + isinstance(node, ast.Name) + and node.id == reference + and isinstance(node.ctx, ast.Load) + and not _reference_use_is_legal(node, parent) + ): + violations.append(f"line {node.lineno}: {reference} used as a value") + return violations + + +def _qualified_functions(tree: ast.AST) -> dict[int, str]: + """Each node's enclosing ``Class.function`` name, for nodes inside a function.""" + owner: dict[int, str] = {} + + def visit(node: ast.AST, prefix: str) -> None: + for child in ast.iter_child_nodes(node): + if isinstance(child, ast.ClassDef): + visit(child, f"{prefix}{child.name}.") + elif isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)): + name = f"{prefix}{child.name}" + for inner in ast.walk(child): + owner.setdefault(id(inner), name) + else: + visit(child, prefix) + + visit(tree, "") + return owner + + +def _secret_reads(path: Path) -> list[tuple[str, str]]: + tree = _parse(path) + owner = _qualified_functions(tree) + return [ + (path.relative_to(REPO).as_posix(), owner.get(id(node), "")) + for node in ast.walk(tree) + if isinstance(node, ast.Call) and _call_name(node) == "get_secret_value" + ] + + +def test_the_credential_reference_is_a_key_never_a_value(): + """C1, made mechanical: the reference selects a binding; Replicator never reads it.""" + offenders = {} + for path in _python_files(SRC): + name = path.relative_to(REPO).as_posix() + tree = _parse(path) + reads_field = any( + isinstance(node, ast.Attribute) and node.attr == CREDENTIAL_FIELD + for node in ast.walk(tree) + ) + if reads_field and name not in CREDENTIAL_FIELD_MODULES: + offenders[name] = [f"reads .{CREDENTIAL_FIELD} at all"] + elif violations := _reference_violations(tree): + offenders[name] = violations + assert not offenders + + +def test_the_reference_scan_has_a_subject(): + """A scan whose loop pattern stopped matching would pass on nothing.""" + loops = [ + loop + for module in CREDENTIAL_FIELD_MODULES + for loop in _reference_loops(_parse(REPO / module)) + ] + assert loops, "no `for name, reference in ....credential_headers.items()` loop found" + + +def test_the_value_is_read_in_the_transport_alone(): + """D2: ``get_secret_value()`` has one call site, where the outgoing hop is built.""" + reads = [read for path in _python_files(SRC) for read in _secret_reads(path)] + + assert reads == [SECRET_READER] + + +@pytest.mark.parametrize( + "source", + [ + pytest.param( + "for n, ref in o.credential_headers.items():\n if ref == 'fetch-x': pass", + id="compared", + ), + pytest.param("for n, ref in o.credential_headers.items():\n seen.add(ref)", id="stored"), + pytest.param( + "for n, ref in o.credential_headers.items():\n open(f'/etc/creds/{ref}')", + id="a-path-from-it", + ), + pytest.param( + "for n, ref in o.credential_headers.items():\n p = Path('/etc') / ref", + id="a-path-joined", + ), + pytest.param( + "for n, ref in o.credential_headers.items():\n logger.info(f'{ref}')", + id="logged-outside-a-refusal", + ), + pytest.param("r = command.credential_headers['X-Api-Key']", id="subscript"), + pytest.param("rs = list(command.credential_headers.values())", id="values"), + pytest.param("r = command.credential_headers.get('X-Api-Key')", id="get"), + ], +) +def test_the_reference_detector_sees_a_planted_read(source): + assert _reference_violations(ast.parse(source)) + + +@pytest.mark.parametrize( + "source", + [ + pytest.param( + "for n, ref in o.credential_headers.items():\n b = table.resolve(ref)", + id="lookup", + ), + pytest.param( + "for n, ref in o.credential_headers.items():\n validate_fetch_credential(ref)", + id="validator", + ), + pytest.param( + "for n, ref in o.credential_headers.items():\n out.append(Resolved(ref, b))", + id="paired", + ), + pytest.param( + "for n, ref in o.credential_headers.items():\n" + " raise PermanentFetchError(f'{n} names {ref}', reason=r)", + id="named-in-a-refusal", + ), + ], +) +def test_the_reference_detector_passes_a_lookup(source): + assert not _reference_violations(ast.parse(source)) + + +def test_the_secret_read_detector_sees_a_second_reader(tmp_path): + planted = tmp_path / "planted.py" + planted.write_text( + "class T:\n def f(self, c):\n return c.value.get_secret_value()\n" + "def leak(c):\n print(c.value.get_secret_value())\n" + ) + original = REPO + try: + globals()["REPO"] = tmp_path + reads = _secret_reads(planted) + finally: + globals()["REPO"] = original + + assert reads == [("planted.py", "T.f"), ("planted.py", "leak")] + + +def test_the_credential_field_modules_list_names_files_that_exist(): + for module in CREDENTIAL_FIELD_MODULES: + assert (REPO / module).is_file(), module + assert (REPO / SECRET_READER[0]).is_file() + + # -------------------------------------------------------------------------- # 3. Ingress is read-only # -------------------------------------------------------------------------- From 736483e6a94f40a8c854a561b4691d72e399c027 Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 17:25:52 +0000 Subject: [PATCH 08/23] #216 docs: fetch credential references in the contracts, env and fetch path - issuer reference: a credential_headers section (what a reference is, what a binding pins, per-hop scope, the refusal table and tokens, the per-command cookie lifetime), the bounds row pointing at headers.py, and the version-history line; - outcome reference: the two tokens, and their taxonomy rows; - issuer contract: the rule in brief, linking the section; - ENVIRONMENT: REPLICATOR_FETCH_CREDENTIALS_FILE, its format, rules, file posture, boot lines, and rotation-is-a-restart; - ARCHITECTURE, STREAMS: the command scope outside the guard; - seed_fetch.py --credential-header, with COMMANDS.md. Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 2 +- docs/COMMANDS.md | 5 ++ docs/ENVIRONMENT.md | 8 +++ docs/STREAMS.md | 4 +- .../content-fetch-issuer-contract.md | 6 +++ .../content-fetch-issuer-reference.md | 54 ++++++++++++++++++- .../content-fetch-outcome-reference.md | 7 ++- scripts/seed_fetch.py | 29 +++++++++- tests/test_seed_fetch.py | 47 ++++++++++++++++ 9 files changed, 153 insertions(+), 9 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1b454117..f8f74ab7 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -38,7 +38,7 @@ src/worker/main.py — Entry point: client lifetime, consumer group, signals, src/worker/loop.py — The consume path: poll → dispatch → ack, DLQ, dedupe, recovery; one loop per command stream, parameterized by CommandSpec src/worker/handler.py — The byte path behind the Handler seam: fetch → fingerprint → store → publish src/worker/headers.py — The request-header rules: names, values, the refused set, the count and byte bounds; shared by the handler's `headers` guards and the fetch credential table (#11, #216) -src/worker/egress.py — The destination guard: a transport refusing loopback, private, tailnet and IANA special-purpose addresses per redirect hop (#95, #161); an answer it cannot check retries, never passes (#100). Beside it, the body ceiling: every hop's body counted on the wire and not read past `REPLICATOR_MAX_BLOB_BYTES` (#104) +src/worker/egress.py — The destination guard: a transport refusing loopback, private, tailnet and IANA special-purpose addresses per redirect hop (#95, #161); an answer it cannot check retries, never passes (#100). Beside it, the body ceiling: every hop's body counted on the wire and not read past `REPLICATOR_MAX_BLOB_BYTES` (#104). Outside both, the command scope (#216): every hop reads its command's scope from a `ContextVar` the handler sets, carries that command's cookies only, and carries a fetch credential only when `https`, port 443 and the host are in every binding's scope — otherwise `credential_refused`, never sent bare src/worker/browser.py — The renderer behind the Renderer seam: one pinned headless Chromium per render, sandboxed, scrubbed env, one at a time; a screenshot (render) or the serialized document (load, #63); says what happened to the page, never the wire reason (#138) src/worker/browser_fetch.py — BrowserFetcher, the Fetcher behind render="browser": load → a FetchResult describing the stored document, render errors in fetch's vocabulary (#63) src/worker/browser_egress.py — The browser's egress guard: a per-render SOCKS5 listener vetting every connection a page opens with egress.py's DestinationGuard, dialling the address it checked (#138) diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md index 3c0b9d8b..595f2e39 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -101,6 +101,11 @@ worker refuses it before any request goes out, closing the command as `fetch_fai worth knowing before seeding a local test server. The full list is in [`docs/contracts/content-fetch-issuer-reference.md`](contracts/content-fetch-issuer-reference.md). +`--credential-header 'X-Api-Key: fetch-wa-leg-api'` attaches a fetch credential **reference** +(#216), repeatable, to every command: a `fetch-` name the worker resolves from its host's +table, never a value. Unchecked here too, so an unprovisioned reference seeds `credential_unknown` +and a header the binding doesn't pin seeds `credential_refused`. + Watch the live side with `sudo journalctl -u replicator -f`: each `stored a blob and published blob_available` is one of Watcher's commands closing. diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md index 73dd032a..52c2dfd6 100644 --- a/docs/ENVIRONMENT.md +++ b/docs/ENVIRONMENT.md @@ -84,6 +84,14 @@ In `/etc/replicator/.env` (read by the service): A binding names **where**, and at most *which key file* — the credential itself is resolved locally, from ADC or that file. A `credentials_file` that is not an absolute path drops the binding without quoting the value; a key that will not load withholds the writer and never falls back to ADC. `alias table loaded` lists `credentials_files`, alias to path. Fields the binding does not declare are dropped at load, so a key pasted in here never reaches the worker's memory. An unreadable file provisions nothing (logged ERROR); one unusable entry drops only itself (logged WARNING). **Unset, and a path with no file behind it, both log `no alias table on this host — replication is not provisioned` at INFO** — `detail` names the variable in the first case, `path` names the file it looked for in the second — and a loaded table logs `alias table loaded` with its `provisioned` list, so one grep of a boot answers whether this host is provisioned. Until #86 the unset case returned silently, and the only evidence was `replication_aliases` on the `worker ready` line, which still carries it. **Each alias gets its own writer, so two aliases may safely name two buckets.** The worker builds one `AsyncGcsDriver` per binding at startup and keys them by alias — a driver *is* a bucket, and keying them by provider once let a command land in a bucket its binding never named (CR #26). A binding whose driver cannot be built — ADC resolves inside that constructor, so an expired key file or a revoked SA raises there — is **skipped and logged at ERROR**, never fatal: commands naming it are refused `provider_disabled`, and the fetch path keeps running. Grep the journal for `could not build a provider writer` after any credential change. +- `REPLICATOR_FETCH_CREDENTIALS_FILE` — path to the JSON fetch credential table (#216); **unset by default, and that is the safe posture**: every `content.fetch` command carrying `credential_headers` is refused `credential_unknown`, never fetched without its credential. The alias table's shape and reasoning: env carries the path, the table carries the bindings, and each **value** sits in a file of its own. Format: + + ```json + { "fetch-wa-leg-api": { "header": "X-Api-Key", "hosts": ["api.leg.wa.gov"], + "value_file": "/etc/replicator/fetch-credentials/fetch-wa-leg-api" } } + ``` + + The key is a `fetch-` reference (co-core's `validate_fetch_credential`). `header` is the one header the value may ride (operator call 3): a token `headers` would send, and not `user-agent`, `if-none-match` or `if-modified-since`. `hosts` is a non-empty list of exact hostnames in `content.fetch-policy`'s form (lower case, punycode, no trailing dot, no port, no wildcard); a hop is sent the value only over `https`, on port 443, to a host in **every** binding the command names. `value_file` is an absolute path; its content, less one trailing newline, must be non-empty printable US-ASCII without surrounding whitespace, and fit the 8192-byte header bound. **Values are read at boot** (operator call 2), so rotating one is `sudo systemctl restart replicator`. Posture: the directory `root:replicator 0750`, each value file and the table `root:replicator 0640`, as the writers' keys are. An unusable binding drops itself (WARNING) with the rule it broke; neither a value nor an off-rule reference is ever logged. **Unset, and a path with no file behind it, both log `no fetch credential table on this host — fetch credentials are not provisioned` at INFO**; a loaded table logs `fetch credentials loaded` with each reference's header, hosts and value-file **path**. - `REPLICATOR_LOG_LEVEL` — default `INFO`. Governs the **root** logger only, which is the whole tree for the worker. Under the dev server's `--log-config`, uvicorn's own `uvicorn` / `uvicorn.access` / `uvicorn.error` loggers are pinned `INFO` by `src/core/log_config.json` and do not follow it (nor did they under uvicorn's built-in config), so setting `WARNING` will not silence access lines; root itself is `INFO` from boot until the lifespan's `configure_logging()` applies this value - `BUILD_ID` — git SHA stamped by the systemd unit's `ExecStartPre`; defaults to `"dev"` outside systemd diff --git a/docs/STREAMS.md b/docs/STREAMS.md index dc1bfce5..74e24666 100644 --- a/docs/STREAMS.md +++ b/docs/STREAMS.md @@ -6,12 +6,12 @@ The rules that hold for *every* stream — idempotency posture, validation, DLQ, what each stream carries is here: - **The issuer contract is written down and lives here.** `docs/contracts/content-fetch-issuer-contract.md` is the normative statement of what a `content.fetch` producer must do — per-occasion `command_id`, `url` is not a correlation key, persist the `command_id → domain` map before publishing, correlate idempotently, and keep a reaper as a backstop for the outcomes no fact can carry. Its companions `docs/contracts/content-fetch-issuer-reference.md` (#24, the request side) and `docs/contracts/content-fetch-outcome-reference.md` (the result side) carry the lookup half and are equally normative. Issuer-side repos (Watcher, Phase 4) link to the contract rather than copying it. Anything asserted in either is asserted about this repo's code; change one, change both (#8). -- **What Replicator is allowed to become is also written down.** `docs/contracts/replicator-boundaries.md` is the sibling charter: mechanism to Replicator, policy to the issuer, config over the bus, and an inbound admin HTTP API rejected by name. Run its three tests against any proposed capability, field, or setting before writing code — a database, domain vocabulary, or a write route is reached one defensible step at a time, not in one commit. `tests/test_boundaries.py` enforces eight invariants in CI, including the one that catches the regression review misses: an AST scan of `src/` for domain nouns in identifiers *and* string literals. Known violation tracked to closure (2026-08-20) rather than omitted — `blob_uri` *was* host-local `file://`; the deployment now announces `gs://`, and the compiled-in default stays `local` deliberately (#7). Change the charter and the tests together (#12). +- **What Replicator is allowed to become is also written down.** `docs/contracts/replicator-boundaries.md` is the sibling charter: mechanism to Replicator, policy to the issuer, config over the bus, and an inbound admin HTTP API rejected by name. Run its three tests against any proposed capability, field, or setting before writing code — a database, domain vocabulary, or a write route is reached one defensible step at a time, not in one commit. `tests/test_boundaries.py` enforces the charter's invariants in CI, including the one that catches the regression review misses: an AST scan of `src/` for domain nouns in identifiers *and* string literals. Known violation tracked to closure (2026-08-20) rather than omitted — `blob_uri` *was* host-local `file://`; the deployment now announces `gs://`, and the compiled-in default stays `local` deliberately (#7). Change the charter and the tests together (#12). - **`content.blobs` carries both outcomes.** `blob_available` on success, `fetch_failed` on a command closed without bytes (#9, co-core cannobserv#270 — v0.7.2). One stream so an issuer's single consumer group sees either. The reason is named at the *raise site* (`PermanentFetchError.reason`), never recovered from a message string, because three unrelated permanent conditions share one exception type. Three rows stay DLQ-only and permanently silent, and only one of them for want of an id: a frame that did not decode, a command whose `command_id` is blank (refused before the fetch — an empty id would otherwise take the stream's empty-id dedupe key `replicator:cmd:fetch:` and make every later blank-id command on that stream a silent no-op, CR #6), and a frame that decoded to a **non-command payload** — the last is unreportable not because it lacks a `command_id` but because any it carries is *another command's* (`BlobAvailableEvent`'s names one that succeeded), so a terminal fact keyed on it would contradict a fact the issuer already applied (CR #1). `_close` refuses a correlator-less report at the one choke point rather than at each call site. Non-terminal facts are deferred (#9 §3): the stream is broadcast and nothing trims it, so a fact per reclaim during an origin outage is unbounded growth. `src/worker/reporter.py`. - **`blob_available` carries the fetch, not just the bytes.** Seven optional fields beyond the blob itself: six describing the *fetch* (#10, cannobserv#271 + #279 — v0.7.5) — `final_url`, `status_code`, `fetched_at`, `content_type_raw`, `etag`, `last_modified` — and `blob_expires_at`, which describes the *store* (cannobserv#301, populated by #28: `stored_at + REPLICATOR_BLOB_TTL_SECONDS`, read before the store so the announced horizon can only fall earlier than the real reap; see [STORAGE.md](STORAGE.md)). Each is what Replicator holds at publish time and a broadcast consumer cannot recover now that fetching lives here rather than in Watcher. **`None` means nobody said it** — never a stand-in: `final_url` is never backfilled from `command.url` (an issuer could no longer tell "landed where I asked" from "nobody knows"), and `content_type_raw` is never backfilled with `DEFAULT_MEDIA_TYPE` (which is the value a consumer reads as "unknown, guess from the URL"). `media_type` keeps its normalized semantics beside the raw channel; the two are not interchangeable. `fetched_at` is stamped where the fetch *returns*, not at publish — `occurred_at` under a reclaim is minutes late. `status_code` is always 2xx on this fact, so it distinguishes 200 from 203/206 and is not a success branch. The passthroughs are **dropped, never repaired**, on two conditions: over `MAX_HEADER_VALUE_LENGTH`, because a truncated ETag replayed in an `If-None-Match` is a validator that can never match; and — `etag` and `last_modified` only, in `_replayable` — outside the printable US-ASCII the request guard accepts, because one Replicator would refuse to send wedges the issuer that stores it (#60). `content_type_raw` takes only the first — never replayed. `src/worker/handler.py::_passthrough`. - **One loop, N command streams (#29).** Everything in `loop.py` is the same decision for every command stream — read `count=1`, refuse a foreign payload, branch on `schema_version` before destructuring, dedupe on `command_id`, ack after the handler, retry the transient and dead-letter the deterministic, fact before ack. What differs is injected as a `CommandSpec`: the payload type its `isinstance` gate accepts, the segment its dedupe keys are namespaced under, the label its journal lines carry, the builder that turns a command plus a cause into *that stream's* failure report, and `describe`, which names a frame in the journal when the correlator cannot (a blank `command_id` is the one dead-letter with nothing to correlate on, so the stream's own identifier — fetch's URL, replicate's destination — is load-bearing there). **A builder that raises degrades to no-fact rather than propagating**: it is called from inside the delivery-ceiling path, so an unguarded raise would escape before anything dead-letters, strand the entry in the PEL, and jam the stream permanently with the ceiling unable to fire — the frame still dead-letters and MUST-6's reaper is the backstop for the missing fact. So `content.replicate` is another `run_loop` with another spec, not a second copy of the module with four differences edited in and nine invariants free to drift. **Dedupe keys are namespaced per stream** (`replicator:cmd::`) — issuer-assigned ids make a cross-stream collision unlikely rather than impossible, and its shape is the worst available: the second command acks having done nothing. **The report is per stream and deliberately not a shared superset** — `ReplicationFailedEvent` models no `status_code` and `FetchFailedEvent` has no `info_item_rep_spec_id`, so one dataclass with everything optional would put fields on the wire path that one of its two producers can never fill. `tests/worker/test_loop_spec.py` drives the loop over a real `ContentReplicateCommand` against a second spec, because a generic seam with one instantiation is untested generality. -- **A fetch is bounded by where it may point, not only by who may issue it (#89, #95).** `content.fetch` is unauthenticated and its bytes are announced on `content.blobs`, so an unbounded destination made the capability *read whatever this node reaches and republish it cluster-wide*; loopback here includes an agent UI answering 200 unauthenticated. `src/worker/egress.py` refuses loopback, RFC 1918, link-local, ULA, multicast/reserved, IANA special-purpose ranges (#161) and the tailnet's CGNAT `100.64.0.0/10`, against **every** address the host resolves to, and any IPv4 address one embeds (NAT64, 6to4, #156) (one public answer beside a loopback one is the cheap half of rebinding). **It is an `httpx` transport, not a check on `command.url`**: redirects are followed by default and the transport runs once per hop, so the obvious pre-flight implementation passes every unit test while a 302 walks around it. A `render="browser"` fetch (#63) goes through capture's per-connection SOCKS guard instead, and since that proxy never sees `file:`, the URL is checked as `http(s)` with a host before the launch (CR 1). Composed in at `build_fetch_client` over an injected client, so `run()` closes it and env proxies no longer apply (CR 1, CR 4). Resolving here owns its failure vocabulary: an unresolvable name is **transient**, an unencodable one terminal, because the loop classifies by exception type (CR 2). An answer the check cannot run on — empty in any shape, not an address, or none within `RESOLVE_TIMEOUT_SECONDS` — is transient too, **never a pass** (#100). The table is env, unset meaning the deny set and no value spelling "off". Left open: rebinding's TOCTOU window. #89 declined a URL allowlist (a second copy of Watcher's `Domain` table) and message signing (CannObserv/broker#14 narrows the too-wide grant). Trust posture and residual: [the request reference](contracts/content-fetch-issuer-reference.md); refusal row: [the outcome reference](contracts/content-fetch-outcome-reference.md). +- **A fetch is bounded by where it may point, not only by who may issue it (#89, #95).** `content.fetch` is unauthenticated and its bytes are announced on `content.blobs`, so an unbounded destination made the capability *read whatever this node reaches and republish it cluster-wide*; loopback here includes an agent UI answering 200 unauthenticated. `src/worker/egress.py` refuses loopback, RFC 1918, link-local, ULA, multicast/reserved, IANA special-purpose ranges (#161) and the tailnet's CGNAT `100.64.0.0/10`, against **every** address the host resolves to, and any IPv4 address one embeds (NAT64, 6to4, #156) (one public answer beside a loopback one is the cheap half of rebinding). **It is an `httpx` transport, not a check on `command.url`**: redirects are followed by default and the transport runs once per hop, so the obvious pre-flight implementation passes every unit test while a 302 walks around it. A `render="browser"` fetch (#63) goes through capture's per-connection SOCKS guard instead, and since that proxy never sees `file:`, the URL is checked as `http(s)` with a host before the launch (CR 1). Composed in at `build_fetch_client` over an injected client, so `run()` closes it and env proxies no longer apply (CR 1, CR 4). **Since #216 a command scope sits outside it**: the handler sets the command's scope around the fetch, and each hop refuses without one, carries that command's cookies alone (the client's jar never stores, so one command's `Set-Cookie` never rides another's request), and carries a resolved `credential_headers` binding only when the hop is `https`, port 443 and a host in every binding — else `credential_refused`, before DNS, never sent without it. Each hop goes out on a copy of the request, because httpx builds the next hop from the one it handed in. Resolving here owns its failure vocabulary: an unresolvable name is **transient**, an unencodable one terminal, because the loop classifies by exception type (CR 2). An answer the check cannot run on — empty in any shape, not an address, or none within `RESOLVE_TIMEOUT_SECONDS` — is transient too, **never a pass** (#100). The table is env, unset meaning the deny set and no value spelling "off". Left open: rebinding's TOCTOU window. #89 declined a URL allowlist (a second copy of Watcher's `Domain` table) and message signing (CannObserv/broker#14 narrows the too-wide grant). Trust posture and residual: [the request reference](contracts/content-fetch-issuer-reference.md); refusal row: [the outcome reference](contracts/content-fetch-outcome-reference.md). - **`content.replicate` is the second command loop, and it writes for `gcs` (#29).** Same `run_loop`, `REPLICATE_SPEC` instead of `FETCH_SPEC`, its own consumer group (`replicator.replicate`), its own PEL, its own dedupe namespace. Both outcomes go to **`content.artifacts`**, not `content.blobs` — a fact on the wrong stream reaches a consumer group that will never match it. The write goes through `AsyncGcsDriver.create_if_absent` (co-core-aio's `[gcs]` extra), which is T4's primitive: `ifGenerationMatch=0`, then an md5 comparison on the 412. **A blob already in a bucket is copied server-side instead** (#114 item 5): `copy_if_absent`, a `rewrite` under the same precondition, with the two objects' reported md5s compared on the 412 — the bytes never transit this host, and the journal's `method` says `copy` or `upload`. **`REPLICATOR_REPLICATE_WRITE_TIMEOUT_SECONDS` bounds each rewrite call, not the copy**: co-core loops on the rewrite token, and a rewrite that changes location or storage class may need several calls, each with the full timeout, while the handler holds the group. The three buckets are all `US-WEST1` ([INFRASTRUCTURE.md](INFRASTRUCTURE.md)), so location does not trigger it here — but an issuer's `object_options.storage_class` can. It runs as the alias's writer, which therefore reads the source buckets ([INFRASTRUCTURE.md](INFRASTRUCTURE.md)). Both carry the `co-content-sha256` stamp (#114 item 4). **Four outcomes, three facts** — `WROTE` and `ALREADY_IDENTICAL` both emit `replication_complete` with the same `public_url` (a redelivery onto matching bytes is a no-op that still tells the issuer), `CONFLICT` is a terminal `destination_conflict`, and **`INDETERMINATE` does not close the command** — a 412 whose confirming read found *no object* is a race, not a conflict, and closing it terminally would tell an issuer no artifact is coming about a destination that would accept the next attempt. **Not closing it publishes nothing**: `TransientReplicateError` is exempt from the delivery ceiling, so the entry simply stays pending and `build_replicate_reporter` still stamps `terminal=True` on every fact it does emit — the absence of a fact is what "still trying" looks like on this wire, and MUST-6's reaper bounds it. Emitting a `terminal=false` fact instead would be a contract change, not an implementation detail. **Provider failures are classified by HTTP status, not caught as a class** (CR #27): 5xx, 408, 429 and anything with no status stay open, because T4 makes the retry safe; every other 4xx *closes* — a 400 is the issuer's rendered key or `object_options` (`invalid_destination`), the rest are the host's missing bucket or permission (`provider_disabled`). Classifying them all as transient meant a 403 retried forever and published no fact at all, and `object_options` being an opaque dict made that reachable from the wire. `gdrive` and `ia` have no conditional create yet and take the `provider_disabled` path, the same one a host with no binding takes. diff --git a/docs/contracts/content-fetch-issuer-contract.md b/docs/contracts/content-fetch-issuer-contract.md index 5ebc4ede..56e3ca3e 100644 --- a/docs/contracts/content-fetch-issuer-contract.md +++ b/docs/contracts/content-fetch-issuer-contract.md @@ -107,6 +107,12 @@ The refusal list itself — hop-by-hop and derived headers, the rules on names a ceilings, the timeout bounds, the header-name folding rule, and the reasoning behind each — is in [the reference](content-fetch-issuer-reference.md#request-options-what-replicator-will-send-and-what-it-refuses-11). +`credential_headers` (#216) carries **references, never values**: a header name to a +`fetch-` binding the Replicator operator provisioned. A reference resolves only where it was +provisioned, the binding pins its header, hosts and `https`:443, and every redirect hop is held to +it. Its refusals (`invalid_request_options`, `credential_unknown`, `credential_refused`) are in +[the reference](content-fetch-issuer-reference.md#credential_headers-fetch-credential-references-216). + ### The facts Both outcomes arrive on `content.blobs` — **`blob_available`** (`BlobAvailableEvent`) on success, diff --git a/docs/contracts/content-fetch-issuer-reference.md b/docs/contracts/content-fetch-issuer-reference.md index e19153d7..3f6131d0 100644 --- a/docs/contracts/content-fetch-issuer-reference.md +++ b/docs/contracts/content-fetch-issuer-reference.md @@ -62,7 +62,7 @@ own fingerprints. | A name that is not an RFC 9110 token | `user agent`, `user:agent`, an empty name, anything non-ASCII — and a name with surrounding whitespace, which RFC 9110 forbids before the colon and which is therefore malformed rather than trimmable | | A value with any byte outside `\x20`–`\x7e` | Printable US-ASCII and SP only. Excludes CR, LF, NUL, every other control character, HTAB, and all of `obs-text` (`\x80`–`\xff`) — narrower than RFC 9110 permits, deliberately. A CRLF here is request splitting | | Two names differing only in case | Folding them would silently discard one. Refused even when the values agree — the rule is about the shape, not the values | -| More than **32** headers, or more than **8192 bytes** of them | 8 KiB is the common origin-side limit (nginx, Apache), so past it the far end answers an opaque 400. The constants in [`src/worker/handler.py`](../../src/worker/handler.py) are authoritative | +| More than **32** headers, or more than **8192 bytes** of them | 8 KiB is the common origin-side limit (nginx, Apache), so past it the far end answers an opaque 400. The constants in [`src/worker/headers.py`](../../src/worker/headers.py) are authoritative. Since #216 both bounds cover `headers` and `credential_headers` together | | `timeout_seconds` that is zero, negative, NaN, or infinite | Not a duration | | `timeout_seconds` over `REPLICATOR_MAX_FETCH_TIMEOUT_SECONDS` (default **120**) | Replicator's consume path is serial, so your timeout is a lien on every *other* issuer's commands too. Ask an operator if 120 s is genuinely too short for a target. It bounds each *operation* (the connect, each read); the whole fetch is bounded by `REPLICATOR_MAX_FETCH_SECONDS` (default **120**, never less than this), and a fetch past that is retried, not refused (#104) | @@ -131,6 +131,54 @@ checks on **every connection the page opens**, not only on the URL and its redir same URL, so the first fetch after a flip reads as a content change. Whether to re-baseline is the issuer's call (archiver#379). +### `credential_headers`: fetch credential references (#216) + +**What it is.** `credential_headers` (co-core **0.51.1**, cannobserv#577) maps a header name to a +`fetch-` **reference**, e.g. `{"X-Api-Key": "fetch-wa-leg-api"}`. The reference names a +binding an operator provisioned on Replicator's host; the binding holds the value. **The value never +travels on the bus**, and Replicator never echoes it: not on a fact, not in `detail`, not in the +journal. `None` and `{}` both mean no credential, which is today's path, byte for byte. + +**A reference resolves only where it was provisioned.** Agree the binding with the Replicator +operator before emitting the reference; until then every such command closes `credential_unknown`. +A binding pins three things, and a command can widen none of them: + +- **the header** it rides. A command naming another header for the reference closes + `credential_refused`: an in-scope endpoint that echoes request headers must not be handed the + value under a header it reflects; +- **the hosts** it may reach, exactly: no wildcard, no subdomain, compared in punycode; +- **`https` on port 443**, the only scheme and port a credential is sent to. + +**Scoped per hop, and refused rather than stripped (C2, C3).** Every redirect hop is checked against +every credential on the command, before the hop is sent. A hop out of scope closes the command +`credential_refused`; it is **never** sent without the credential instead, because a fetch that +quietly went out anonymous is a different fetch from the one you asked for. A hop that is out of +scope *and* in a range the destination guard refuses reports `credential_refused`: the scope is +checked first, with no DNS lookup. + +| Refused | Token | +|---|---| +| A credential name that `headers` would refuse (not a token, hop-by-hop, derived, `proxy-*`) | `invalid_request_options` | +| A name in both `headers` and `credential_headers` (E3), or twice by case (E4) | `invalid_request_options` | +| `user-agent`, `if-none-match` or `if-modified-since` as a credential name (E5) | `invalid_request_options` | +| Any credential under `render="browser"` (E1): a browser sends a header to every host the page contacts | `invalid_request_options` | +| The header count, or the byte total **with the resolved values counted**, over the bounds above | `invalid_request_options` | +| A reference off `fetch-`, never provisioned, or dropped at the host's boot | `credential_unknown` | +| A header other than the one the binding pins | `credential_refused` | +| The URL, or any redirect hop, not `https`, not on port 443, or not one of every binding's hosts | `credential_refused` | + +All are terminal with `status_code` and `attempts` unset, and arrive before the request (or the hop) +goes out. `detail` names the header and the reference, never the value; a reference off the rule isn't +quoted at all, because the likeliest wrong value where a reference belongs is a pasted secret. Like +`invalid_request_options`, both credential tokens are decided from the command and the host's table, so +re-issuing the same command is refused identically until one of them changes: fix the policy, or ask +the operator to provision the binding. An origin's 401 or 403 when a credential **was** sent stays +`http_status`. + +**Cookies live for one command since #216.** A `Set-Cookie` on one hop is sent on the later hops of +the same redirect chain, as before, and on nothing after it: one command's session no longer rides +another command to the same host. That applies to every command, credentialed or not. + ### `invalid_request_options` and stored values **This is the one refusal an issuer can wedge itself on.** Every other terminal outcome describes @@ -285,7 +333,9 @@ three payloads and `command_id` on `blob_available`, re-keyed `blob_available` t `content_fingerprint:command_id` (cannobserv#300), and added `blob_expires_at` (cannobserv#301). **v0.40.1** added `render` (cannobserv#602), honoured since #63; a consumer older than that fetches a `browser` command over HTTP and stores the empty shell, which is why co-core's MUST waited on -Replicator's announcement. Replicator requires **co-core ≥ 0.8.0** to decode a command at all. +Replicator's announcement. **v0.51.1** added `credential_headers` (cannobserv#577), resolved since +#216; a consumer older than that decodes the field and ignores it, sending the fetch without the +credential. Replicator requires **co-core ≥ 0.8.0** to decode a command at all. Founding rationale: [`docs/plans/2026-06-25-replicator-mvp-design.md`](../plans/2026-06-25-replicator-mvp-design.md). diff --git a/docs/contracts/content-fetch-outcome-reference.md b/docs/contracts/content-fetch-outcome-reference.md index e89a00a7..995b0080 100644 --- a/docs/contracts/content-fetch-outcome-reference.md +++ b/docs/contracts/content-fetch-outcome-reference.md @@ -135,7 +135,8 @@ are the whole value of the six: | `detail` | `str \| None` | Free text for the journal. **Never branch on it**, and never show it to an end user — on `handler_error` it is an unanticipated exception's text, so unbounded | The tokens emitted today are `http_status`, `not_modified`, `not_fetchable`, `too_large`, -`destination_refused`, `unsupported_schema_version`, `invalid_request_options` and `handler_error` — +`destination_refused`, `credential_unknown`, `credential_refused` (both #216), +`unsupported_schema_version`, `invalid_request_options` and `handler_error` — one per row of the [failure taxonomy](#failure-taxonomy-what-happens-and-what-the-issuer-sees) below, which states each one's condition. Why the list is additive, why `wrong_payload_type` never appears and why every one is `terminal=True`: [Reading the failure fact](#reading-the-failure-fact). @@ -155,7 +156,9 @@ appears and why every one is `terminal=True`: [Reading the failure fact](#readin | HTTP 304 Not Modified — a conditional GET that **succeeded** (#17) | fact, ack, and **no DLQ entry**; the dedupe key is written | `fetch_failed` · `not_modified` (+ `status_code=304`) | | URL not fetchable (bad scheme / invalid URL; under `browser`, a download or non-HTML document) | fact, then `content.fetch.dlq` | `fetch_failed` · `not_fetchable` | | Body over `REPLICATOR_MAX_BLOB_BYTES` (default 64 MiB) | fact, then `content.fetch.dlq` — since #104 **Replicator stops reading at the ceiling**, or before any byte when `Content-Length` declares more | `fetch_failed` · `too_large` | -| Unsendable `headers` / `timeout_seconds` / `render` | fact, then `content.fetch.dlq`, **before the fetch** | `fetch_failed` · `invalid_request_options` | +| Unsendable `headers` / `timeout_seconds` / `render` / `credential_headers` names, or both header maps over the count or byte bound | fact, then `content.fetch.dlq`, **before the fetch** | `fetch_failed` · `invalid_request_options` | +| A `credential_headers` reference this host has no usable binding for — never provisioned, dropped at boot, or off `fetch-` (#216) | fact, then `content.fetch.dlq`, **before the fetch** | `fetch_failed` · `credential_unknown` | +| A credential used outside its binding: another header, or a URL or **redirect hop** not `https`, not on port 443, or not one of every binding's hosts (#216) | fact, then `content.fetch.dlq`, **before the request or the hop goes out**; never sent without the credential instead | `fetch_failed` · `credential_refused` | | Destination in a range this host will not fetch from — loopback, RFC 1918, link-local, ULA, the tailnet's CGNAT `100.64.0.0/10` (#95), an IANA special-purpose range (#161), or an IPv6 address embedding one (#156) | fact, then `content.fetch.dlq`, **before the request goes out**, and on **each redirect hop** | `fetch_failed` · `destination_refused` | | HTTP 5xx / 408 / 429, a network error, or a fetch still running at `REPLICATOR_MAX_FETCH_SECONDS` (default 120 s, #104) | retry indefinitely, default ~60 s cadence | delayed fact, or **nothing while it retries** | | Blob tree over `REPLICATOR_BLOB_MAX_TOTAL_BYTES` | parked in the PEL until a sweep frees space | delayed fact, or **nothing while it waits** | diff --git a/scripts/seed_fetch.py b/scripts/seed_fetch.py index f8886e3f..8f24b943 100644 --- a/scripts/seed_fetch.py +++ b/scripts/seed_fetch.py @@ -123,6 +123,7 @@ def build_command( timeout_seconds: float | None = None, info_source_id: str = SEED_INFO_SOURCE_ID, render: str | None = None, + credential_headers: dict[str, str] | None = None, ) -> ContentFetchCommand: """Mint a command for one URL. @@ -147,6 +148,10 @@ def build_command( ``render`` (#63) is ``None`` by default, today's HTTP fetch. It is passed through unchecked, so a scratch run can seed the refusal of an unknown mode too. + + ``credential_headers`` (#216) maps a header name to a ``fetch-`` + **reference**, never a value: the worker resolves it from its host's table. Also + unchecked, so a scratch run can seed ``credential_unknown`` and its siblings. """ return ContentFetchCommand( occurred_at=datetime.now(UTC), @@ -156,6 +161,7 @@ def build_command( timeout_seconds=timeout_seconds, info_source_id=info_source_id, render=render, + credential_headers=credential_headers, ) @@ -297,6 +303,7 @@ async def publish( timeout_seconds: float | None = None, info_source_id: str = SEED_INFO_SOURCE_ID, render: str | None = None, + credential_headers: dict[str, str] | None = None, ) -> list[SeedResult]: """XADD one command per URL, in the order given. @@ -312,7 +319,9 @@ async def publish( publisher = AsyncBusPublisher(client) results = [] for url in urls: - command = build_command(url, headers, timeout_seconds, info_source_id, render) + command = build_command( + url, headers, timeout_seconds, info_source_id, render, credential_headers + ) result = await publisher.execute(BusPublish(topic, to_wire(command))) published = SeedResult(command.command_id, url, result.bus_message_id) results.append(published) @@ -469,6 +478,17 @@ def build_parser() -> argparse.ArgumentParser: metavar="'Name: value'", help="request header to attach to every command; repeatable (#11)", ) + parser.add_argument( + "--credential-header", + action=HeaderAction, + dest="credential_headers", + default=None, + metavar="'Name: fetch-'", + help=( + "credential reference to attach to every command; repeatable (#216). " + "A fetch- name the worker resolves from its host's table, never a value" + ), + ) parser.add_argument( "--info-source-id", default=SEED_INFO_SOURCE_ID, @@ -514,6 +534,7 @@ def _print_dry_run( timeout_seconds: float | None = None, info_source_id: str = SEED_INFO_SOURCE_ID, render: str | None = None, + credential_headers: dict[str, str] | None = None, ) -> None: """Show the wire frames without publishing them. @@ -523,7 +544,9 @@ def _print_dry_run( travel, after this script's own stripping. """ for url in urls: - command = build_command(url, headers, timeout_seconds, info_source_id, render) + command = build_command( + url, headers, timeout_seconds, info_source_id, render, credential_headers + ) print(f"would publish to {topic}: {to_wire(command)}") @@ -608,6 +631,7 @@ def report(result: SeedResult) -> None: timeout_seconds=args.timeout_seconds, info_source_id=args.info_source_id, render=args.render, + credential_headers=args.credential_headers, ) except (RedisError, OSError) as exc: print( @@ -692,6 +716,7 @@ def main(argv: list[str] | None = None) -> int: args.timeout_seconds, args.info_source_id, args.render, + args.credential_headers, ) return 0 return asyncio.run(run(args)) diff --git a/tests/test_seed_fetch.py b/tests/test_seed_fetch.py index 39286854..e8b4a62d 100644 --- a/tests/test_seed_fetch.py +++ b/tests/test_seed_fetch.py @@ -844,3 +844,50 @@ def test_a_dry_run_shows_the_options_that_would_travel(capsys): assert "watcher/0.1.0" in printed assert "5.0" in printed assert '"render":"browser"' in printed + + +async def test_published_commands_carry_credential_references(fake_redis, owned_client): + """#216: end to end through argparse. A reference, never a value, rides the frame.""" + argv = ("--topic", TOPIC, "--credential-header", "X-Api-Key: fetch-wa-leg-api", URL) + assert await run(seed_args(*argv)) == 0 + + (command,) = await decoded_commands(fake_redis) + assert command.credential_headers == {"X-Api-Key": "fetch-wa-leg-api"} + assert command.headers is None + + +def test_repeated_credential_header_flags_collect_into_one_mapping(): + args = seed_args( + "--topic", + TOPIC, + "--credential-header", + "X-Api-Key: fetch-a", + "--credential-header", + "Cookie: fetch-b", + URL, + ) + + assert args.credential_headers == {"X-Api-Key": "fetch-a", "Cookie": "fetch-b"} + assert args.headers is None + + +def test_no_credential_header_flag_means_none(): + assert seed_args("--topic", TOPIC, URL).credential_headers is None + + +def test_a_dry_run_shows_the_credential_reference(capsys): + code = main( + [ + "--redis-url", + "redis://localhost:1/0", + "--topic", + TOPIC, + "--dry-run", + "--credential-header", + "X-Api-Key: fetch-wa-leg-api", + URL, + ] + ) + + assert code == 0 + assert "fetch-wa-leg-api" in capsys.readouterr().out From 6a053eef8dafdfc64baf1791a712a509d3614204 Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 17:26:57 +0000 Subject: [PATCH 09/23] #216 test: a credentialed frame per hop against a live broker Two seeded commands through the real driver and the scope transport: one redirected within the binding's host stores a blob with the credential on both hops; one redirected off it closes credential_refused, the off-scope host never contacted. No scratch stream, the DLQ included, carries the value. Co-Authored-By: Claude Opus 5.5 --- tests/worker/test_loop_integration.py | 107 ++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) diff --git a/tests/worker/test_loop_integration.py b/tests/worker/test_loop_integration.py index d12cb28f..742473f8 100644 --- a/tests/worker/test_loop_integration.py +++ b/tests/worker/test_loop_integration.py @@ -46,17 +46,23 @@ import time import uuid from collections.abc import AsyncGenerator +from types import MappingProxyType +import httpx import pytest from co_core.pure.adapters.bus.exceptions import BusMessageAnomaly from co_core.pure.adapters.bus.streams import dlq_name from co_core.pure.models.changes import FetchFailedEvent from co_core.pure.util.hashing import sha256 +from co_core_aio.fetch import AsyncFetchDriver from co_core_sync.drivers.blobstore import LocalBlobStore +from pydantic import SecretStr from scripts.seed_fetch import last_id, publish, resolve_blobs_topic, watch_for_facts from src.core.config import get_settings from src.core.errors import TransientError +from src.worker.credentials import FetchCredential, FetchCredentialTable +from src.worker.egress import CommandScopeTransport, never_storing_cookies from src.worker.handler import build_handler from src.worker.loop import ( DEDUPE_KEY_PREFIX, @@ -665,3 +671,104 @@ async def test_an_end_to_end_run_only_creates_predictable_keys( for key in created if not (key.startswith("replicator.itest.") or key.startswith(DEDUPE_KEY_PREFIX)) ] + + +async def test_a_credentialed_frame_is_scoped_per_hop_against_a_live_broker( + real_redis, scratch_topic, scratch_blobs_topic, dedupe_keys, itest_settings, tmp_path +): + """#216 end to end: a seeded reference, resolved on the host, sent in scope only. + + The real driver and the worker's scope transport over a mock origin, so the hops + are observable. Two commands: one redirected within the binding's host, which + stores a blob with the credential on both hops; one redirected off it, which + closes ``credential_refused`` with the off-scope host never contacted. Then every + scratch stream is searched for the value. + """ + value = "planted-itest-value-5be0" # never a real credential; a tripwire + seen: list[httpx.Request] = [] + + def origin(request: httpx.Request) -> httpx.Response: + seen.append(request) + if request.url.path == "/in": + return httpx.Response(302, headers={"location": "/landed"}) + if request.url.path == "/out": + return httpx.Response(302, headers={"location": "https://elsewhere.example/"}) + return httpx.Response(200, content=BODY, headers={"content-type": "text/html"}) + + table = FetchCredentialTable( + MappingProxyType( + { + "fetch-itest": FetchCredential( + header="x-api-key", + hosts=frozenset({"api.example"}), + value=SecretStr(value), + value_file="/scratch", + ) + } + ) + ) + settings = itest_settings.model_copy( + update={"blob_dir": tmp_path, "dedupe_ttl_seconds": DEDUPE_TTL_SECONDS} + ) + consumer = build_consumer(real_redis, settings, topic=scratch_topic) + await consumer.ensure_group(start_id="0") + client = httpx.AsyncClient( + transport=CommandScopeTransport(httpx.MockTransport(origin)), + cookies=never_storing_cookies(), + follow_redirects=True, + ) + handler = build_handler( + fetcher=AsyncFetchDriver(client), + store=LocalBlobStore(tmp_path, touch_on_rereference=True), + client=real_redis, + settings=settings, + blobs_topic=scratch_blobs_topic, + credentials=table, + ) + stop = asyncio.Event() + loop = asyncio.create_task( + run_loop( + client=real_redis, + consumer=consumer, + group=GROUP, + settings=settings, + handler=handler, + reporter=build_failure_reporter(client=real_redis, blobs_topic=scratch_blobs_topic), + spec=FETCH_SPEC, + stop=stop, + ) + ) + start_id = await last_id(real_redis, scratch_blobs_topic) + seeded = await publish( + real_redis, + scratch_topic, + ["https://api.example/in", "https://api.example/out"], + credential_headers={"X-Api-Key": "fetch-itest"}, + ) + dedupe_keys.extend(FETCH_SPEC.dedupe_key(s.command_id) for s in seeded) + try: + facts = await watch_for_facts( + real_redis, + scratch_blobs_topic, + start_id, + {s.command_id for s in seeded}, + timeout_seconds=FACT_TIMEOUT_SECONDS, + ) + finally: + stop.set() + await asyncio.wait_for(loop, timeout=5) + await client.aclose() + + by_command = {fact.command_id: fact for fact in facts} + stored, refused = (by_command[s.command_id] for s in seeded) + assert stored.content_fingerprint == sha256(BODY) + assert isinstance(refused, FetchFailedEvent) + assert refused.reason == "credential_refused" + assert refused.terminal is True + assert [(r.url.host, r.url.path, r.headers.get("x-api-key")) for r in seen] == [ + ("api.example", "/in", value), + ("api.example", "/landed", value), + ("api.example", "/out", value), + ] + for topic in (scratch_topic, scratch_blobs_topic, dlq_name(scratch_topic)): + assert value not in str(await real_redis.xrange(topic)), topic From d88913509301c7356250cea23dbca46472eefd16 Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 17:30:13 +0000 Subject: [PATCH 10/23] #216 refactor: annotate command_scope as a Generator ty flags Iterator on a @contextmanager as deprecated. Co-Authored-By: Claude Opus 5.5 --- src/worker/egress.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/worker/egress.py b/src/worker/egress.py index 73bb1874..f3d7635e 100644 --- a/src/worker/egress.py +++ b/src/worker/egress.py @@ -64,7 +64,7 @@ import http.cookiejar import ipaddress import socket -from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Iterator, Sequence +from collections.abc import AsyncIterator, Awaitable, Callable, Generator, Iterable, Sequence from contextlib import contextmanager from contextvars import ContextVar from dataclasses import dataclass, field @@ -317,7 +317,7 @@ class CommandScope: @contextmanager -def command_scope(credentials: tuple[Resolved, ...] = ()) -> Iterator[CommandScope]: +def command_scope(credentials: tuple[Resolved, ...] = ()) -> Generator[CommandScope]: """Enter a fresh scope for one command's fetch, and leave it even when the fetch raises.""" scope = CommandScope(credentials=credentials) token = _COMMAND_SCOPE.set(scope) From 9ffb4cf434a7a920dcb365132fc7d29dd09dc2bc Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 17:30:32 +0000 Subject: [PATCH 11/23] #216 docs: name reflection as the limit a binding can't close Co-Authored-By: Claude Opus 5.5 --- docs/contracts/content-fetch-issuer-reference.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/contracts/content-fetch-issuer-reference.md b/docs/contracts/content-fetch-issuer-reference.md index 3f6131d0..b740f8a7 100644 --- a/docs/contracts/content-fetch-issuer-reference.md +++ b/docs/contracts/content-fetch-issuer-reference.md @@ -175,6 +175,11 @@ re-issuing the same command is refused identically until one of them changes: fi the operator to provision the binding. An origin's 401 or 403 when a credential **was** sent stays `http_status`. +**What a binding cannot prevent: reflection.** An in-scope origin that echoes the request header into +its response body puts the value in the stored blob, which `blob_available` announces cluster-wide. +The header pin narrows that to the header the operator meant; beyond it, bind only hosts trusted to +keep the credential. + **Cookies live for one command since #216.** A `Set-Cookie` on one hop is sent on the later hops of the same redirect chain, as before, and on nothing after it: one command's session no longer rides another command to the same host. That applies to every command, credentialed or not. From b6a433c2c35899cae9469319c11996b0074ef21e Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 18:26:42 +0000 Subject: [PATCH 12/23] =?UTF-8?q?#216=20fix:=20CR=201=20=E2=80=94=20never?= =?UTF-8?q?=20quote=20a=20pasted=20value=20from=20value=5Ffile=20or=20host?= =?UTF-8?q?s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A dropped binding logged its value_file whenever it was a string, and an invalid host was quoted twice (the detail and PolicyHost's message). A value pasted into either field reached the journal. value_file is logged only when it is an absolute path; a bad host is named by position. Co-Authored-By: Claude Opus 5.5 --- src/worker/credentials.py | 31 ++++++++++++++++++++++--------- tests/worker/test_credentials.py | 22 ++++++++++++++++++++++ 2 files changed, 44 insertions(+), 9 deletions(-) diff --git a/src/worker/credentials.py b/src/worker/credentials.py index 0c23d4d7..de6dbbee 100644 --- a/src/worker/credentials.py +++ b/src/worker/credentials.py @@ -208,7 +208,9 @@ def _credential_or_none(reference: str, entry: Any, position: int) -> FetchCrede why, credential = _why_unusable(entry) if why is not None: extra: dict[str, Any] = {"reference": reference, "detail": why} - if isinstance(entry, dict) and isinstance(entry.get("value_file"), str): + # The path only when it is one (CR 1): a value_file that isn't an absolute + # path is likeliest the value itself, pasted, and is never quoted. + if isinstance(entry, dict) and _is_host_path(entry.get("value_file")): extra["value_file"] = entry["value_file"] logger.warning(_DROPPED, extra=extra) return None @@ -227,8 +229,8 @@ def _why_unusable(entry: Any) -> tuple[str | None, FetchCredential | None]: if why is not None: return why, None value_file = entry.get("value_file") - if not isinstance(value_file, str) or not value_file.startswith("/"): - return "value_file must be an absolute host path to the value", None + if not _is_host_path(value_file): + return "value_file must be an absolute host path to the value (not quoted)", None value, why = _read_value(value_file, header.lower()) if why is not None: return why, None @@ -251,20 +253,31 @@ def _why_unusable_header(header: Any) -> str | None: return None +def _is_host_path(value: Any) -> bool: + return isinstance(value, str) and value.startswith("/") + + def _canonical_hosts(hosts: Any) -> tuple[frozenset[str], str | None]: - """Each host in ``PolicyHost``'s form; a binding matches hosts exactly.""" + """Each host in ``PolicyHost``'s form; a binding matches hosts exactly. + + A bad host is named by its position, never its text (CR 1): ``PolicyHost``'s own + message quotes the host back, and a value pasted into ``hosts`` would ride it. + """ if not isinstance(hosts, list) or not hosts: return frozenset(), "hosts must be a non-empty list of hostnames" canonical: set[str] = set() - for host in hosts: + for position, host in enumerate(hosts): if not isinstance(host, str): - return frozenset(), "every entry in hosts must be a hostname" + return frozenset(), f"hosts[{position}] is not a hostname" if "*" in host: - return frozenset(), f"host {host!r} is a wildcard; a binding matches hosts exactly" + return frozenset(), f"hosts[{position}] is a wildcard; a binding matches hosts exactly" try: canonical.add(_POLICY_HOST.validate_python(host)) - except ValidationError as exc: - return frozenset(), f"host {host!r} is not a bare hostname: {exc.errors()[0]['msg']}" + except ValidationError: + return frozenset(), ( + f"hosts[{position}] is not a bare hostname: lower-case punycode, " + "no scheme, port or path (not quoted)" + ) return frozenset(canonical), None diff --git a/tests/worker/test_credentials.py b/tests/worker/test_credentials.py index df6ee5a2..88afa706 100644 --- a/tests/worker/test_credentials.py +++ b/tests/worker/test_credentials.py @@ -345,3 +345,25 @@ def test_a_credential_is_constructed_only_with_a_secret(): FetchCredential( header="x-api-key", hosts=frozenset({"a.example"}), value=VALUE, value_file="/v" ) + + +@pytest.mark.parametrize( + "overrides", + [ + pytest.param({"value_file": VALUE}, id="value-pasted-as-value_file"), + pytest.param({"hosts": [VALUE + ":x"]}, id="value-pasted-as-a-host"), + pytest.param({"hosts": ["api.leg.wa.gov", f"https://{VALUE}"]}, id="value-in-a-host-url"), + ], +) +def test_a_value_pasted_into_another_field_is_never_quoted(tmp_path, caplog, overrides): + """CR 1: a value pasted where a path or host belongs is dropped, not logged. + + The alias table refuses to quote a non-path ``credentials_file`` for this reason; + the same holds for ``value_file`` and for ``hosts``, whose validator's own message + would quote the host back. + """ + entry = binding(write_value(tmp_path), **overrides) + + warning = _dropped(tmp_path, caplog, "fetch-wa-leg-api", entry, "") + + assert warning.reference == "fetch-wa-leg-api" From 5d5a9e63a4d02ea66f91f034811bd2659c13ce34 Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 18:27:20 +0000 Subject: [PATCH 13/23] =?UTF-8?q?#216=20fix:=20CR=202=20=E2=80=94=20bound?= =?UTF-8?q?=20the=20value-file=20read?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Path.read_bytes() had no bound, so a value_file at /dev/zero (or a huge file) held the boot forever — a loader that promises to fail closed never returned. It now reads the header bound plus two bytes, and the length check runs before the charset so a truncated read is named for its length. Co-Authored-By: Claude Opus 5.5 --- src/worker/credentials.py | 14 ++++++++++---- tests/worker/test_credentials.py | 9 +++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/worker/credentials.py b/src/worker/credentials.py index de6dbbee..a465c3e0 100644 --- a/src/worker/credentials.py +++ b/src/worker/credentials.py @@ -283,8 +283,13 @@ def _canonical_hosts(hosts: Any) -> tuple[frozenset[str], str | None]: def _read_value(value_file: str, header: str) -> tuple[str, str | None]: """The value, minus one trailing ``\\n``, or why it can't be sent verbatim. Never quoted.""" + # Bounded (CR 2): a path at /dev/zero, or a file far over the bound, must drop + # the binding rather than hold the boot. The bound, a newline, and one byte more + # to tell "at the bound" from "over it". + limit = MAX_REQUEST_HEADER_BYTES - len(header) - 4 try: - content = Path(value_file).read_bytes() + with open(value_file, "rb") as handle: + content = handle.read(limit + 2) except OSError as exc: return "", f"value_file is unreadable ({type(exc).__name__})" try: @@ -294,13 +299,14 @@ def _read_value(value_file: str, header: str) -> tuple[str, str | None]: value = value.removesuffix("\n") if not value: return "", "the value is empty" + # First, so a truncated read is always named for its length. The handler's + # measure: name, ": ", value, CRLF (``headers.py``). + if len(value) > limit: + return "", f"the value exceeds the {MAX_REQUEST_HEADER_BYTES}-byte header bound" if not HEADER_VALUE.match(value): return "", "the value is not printable US-ASCII on one line" if value != value.strip(): # The handler strips an issuer's value; a credential's is refused instead, # because a stripped secret is a different secret. return "", "the value has leading or trailing whitespace" - # The handler's measure: name, ": ", value, CRLF (``headers.py``). - if len(header) + len(value) + 4 > MAX_REQUEST_HEADER_BYTES: - return "", f"the value exceeds the {MAX_REQUEST_HEADER_BYTES}-byte header bound" return value, None diff --git a/tests/worker/test_credentials.py b/tests/worker/test_credentials.py index 88afa706..6eb021dc 100644 --- a/tests/worker/test_credentials.py +++ b/tests/worker/test_credentials.py @@ -367,3 +367,12 @@ def test_a_value_pasted_into_another_field_is_never_quoted(tmp_path, caplog, ove warning = _dropped(tmp_path, caplog, "fetch-wa-leg-api", entry, "") assert warning.reference == "fetch-wa-leg-api" + + +def test_a_value_file_that_never_ends_drops_the_binding_at_once(tmp_path, caplog): + """CR 2: the read is bounded, so ``/dev/zero`` can't hold the boot forever.""" + warning = _dropped( + tmp_path, caplog, "fetch-wa-leg-api", binding("/dev/zero"), "byte header bound" + ) + + assert warning.value_file == "/dev/zero" From 6e16921247cb403c8cb4cc3cb51ea44da8a1f2ff Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 18:27:30 +0000 Subject: [PATCH 14/23] =?UTF-8?q?#216=20refactor:=20CR=203=20=E2=80=94=20l?= =?UTF-8?q?oad=20the=20credential=20table=20above=20the=20alias=20block?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It had split the alias table's comment from the call it describes. Co-Authored-By: Claude Opus 5.5 --- src/worker/main.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/worker/main.py b/src/worker/main.py index d1675a48..b5b18466 100644 --- a/src/worker/main.py +++ b/src/worker/main.py @@ -965,15 +965,15 @@ async def run( else None ) capture_consumer_name = consumer_name_for(settings, settings.capture_consumer_group) + # The fetch credential table, the same kind of host state (#216): read once, + # values included, so a bad value file drops its binding here and not at the + # first credentialed fetch. Never raises; unset provisions nothing. + fetch_credentials = load_fetch_credentials(settings.fetch_credentials_file) # Host state, read once at boot: which destinations an operator # provisioned here. Unset means nothing is provisioned and every # replicate command is refused — the safe default (contract T5), and # every host's state until an operator writes the table (this VM's # until #86 provisioned `primary`). - # The fetch credential table, the same kind of host state (#216): read once, - # values included, so a bad value file drops its binding here and not at the - # first credentialed fetch. Never raises; unset provisions nothing. - fetch_credentials = load_fetch_credentials(settings.fetch_credentials_file) aliases = load_alias_table( settings.replication_aliases_file, # No alias may bind a bucket this host keeps blobs in (#114). From cca1dc38909605c8ec0ec3e3e2816b4bc78ac5ef Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 18:28:23 +0000 Subject: [PATCH 15/23] =?UTF-8?q?#216=20docs:=20CR=204=20=E2=80=94=20tight?= =?UTF-8?q?en=20the=20credential=20additions=20to=20each=20doc's=20budget?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ENVIRONMENT, STREAMS, the issuer contract and the charter are back under 10,000 tokens; each now states what it owns and links the issuer reference for the rules. The outcome reference stays 75 over: it had 15 tokens of headroom before #216, and its two tokens' one row can't fit. Co-Authored-By: Claude Opus 5.5 --- docs/ENVIRONMENT.md | 4 ++-- docs/STREAMS.md | 2 +- docs/contracts/content-fetch-issuer-contract.md | 7 ++----- docs/contracts/content-fetch-outcome-reference.md | 8 +++----- docs/contracts/replicator-boundaries.md | 13 ++++--------- 5 files changed, 12 insertions(+), 22 deletions(-) diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md index 52c2dfd6..75746917 100644 --- a/docs/ENVIRONMENT.md +++ b/docs/ENVIRONMENT.md @@ -84,14 +84,14 @@ In `/etc/replicator/.env` (read by the service): A binding names **where**, and at most *which key file* — the credential itself is resolved locally, from ADC or that file. A `credentials_file` that is not an absolute path drops the binding without quoting the value; a key that will not load withholds the writer and never falls back to ADC. `alias table loaded` lists `credentials_files`, alias to path. Fields the binding does not declare are dropped at load, so a key pasted in here never reaches the worker's memory. An unreadable file provisions nothing (logged ERROR); one unusable entry drops only itself (logged WARNING). **Unset, and a path with no file behind it, both log `no alias table on this host — replication is not provisioned` at INFO** — `detail` names the variable in the first case, `path` names the file it looked for in the second — and a loaded table logs `alias table loaded` with its `provisioned` list, so one grep of a boot answers whether this host is provisioned. Until #86 the unset case returned silently, and the only evidence was `replication_aliases` on the `worker ready` line, which still carries it. **Each alias gets its own writer, so two aliases may safely name two buckets.** The worker builds one `AsyncGcsDriver` per binding at startup and keys them by alias — a driver *is* a bucket, and keying them by provider once let a command land in a bucket its binding never named (CR #26). A binding whose driver cannot be built — ADC resolves inside that constructor, so an expired key file or a revoked SA raises there — is **skipped and logged at ERROR**, never fatal: commands naming it are refused `provider_disabled`, and the fetch path keeps running. Grep the journal for `could not build a provider writer` after any credential change. -- `REPLICATOR_FETCH_CREDENTIALS_FILE` — path to the JSON fetch credential table (#216); **unset by default, and that is the safe posture**: every `content.fetch` command carrying `credential_headers` is refused `credential_unknown`, never fetched without its credential. The alias table's shape and reasoning: env carries the path, the table carries the bindings, and each **value** sits in a file of its own. Format: +- `REPLICATOR_FETCH_CREDENTIALS_FILE` — path to the JSON fetch credential table (#216); **unset is the safe posture**: a command carrying `credential_headers` closes `credential_unknown`, never fetched bare. The alias table's shape, plus one file per **value**: ```json { "fetch-wa-leg-api": { "header": "X-Api-Key", "hosts": ["api.leg.wa.gov"], "value_file": "/etc/replicator/fetch-credentials/fetch-wa-leg-api" } } ``` - The key is a `fetch-` reference (co-core's `validate_fetch_credential`). `header` is the one header the value may ride (operator call 3): a token `headers` would send, and not `user-agent`, `if-none-match` or `if-modified-since`. `hosts` is a non-empty list of exact hostnames in `content.fetch-policy`'s form (lower case, punycode, no trailing dot, no port, no wildcard); a hop is sent the value only over `https`, on port 443, to a host in **every** binding the command names. `value_file` is an absolute path; its content, less one trailing newline, must be non-empty printable US-ASCII without surrounding whitespace, and fit the 8192-byte header bound. **Values are read at boot** (operator call 2), so rotating one is `sudo systemctl restart replicator`. Posture: the directory `root:replicator 0750`, each value file and the table `root:replicator 0640`, as the writers' keys are. An unusable binding drops itself (WARNING) with the rule it broke; neither a value nor an off-rule reference is ever logged. **Unset, and a path with no file behind it, both log `no fetch credential table on this host — fetch credentials are not provisioned` at INFO**; a loaded table logs `fetch credentials loaded` with each reference's header, hosts and value-file **path**. + `header` is the one header the value may ride; `hosts` are exact, in `content.fetch-policy`'s form; `value_file` is an absolute path whose content (less one trailing newline) is printable ASCII within the header bound. **Values are read at boot**: rotation is `sudo systemctl restart replicator`. Posture: the directory `root:replicator 0750`, the table and each value `0640`. A bad binding drops itself (WARNING, never quoting a value); boot logs `fetch credentials loaded` (references, headers, hosts, paths) or `no fetch credential table on this host — …` at INFO. Rules and refusals: [the issuer reference](contracts/content-fetch-issuer-reference.md#credential_headers-fetch-credential-references-216). - `REPLICATOR_LOG_LEVEL` — default `INFO`. Governs the **root** logger only, which is the whole tree for the worker. Under the dev server's `--log-config`, uvicorn's own `uvicorn` / `uvicorn.access` / `uvicorn.error` loggers are pinned `INFO` by `src/core/log_config.json` and do not follow it (nor did they under uvicorn's built-in config), so setting `WARNING` will not silence access lines; root itself is `INFO` from boot until the lifespan's `configure_logging()` applies this value - `BUILD_ID` — git SHA stamped by the systemd unit's `ExecStartPre`; defaults to `"dev"` outside systemd diff --git a/docs/STREAMS.md b/docs/STREAMS.md index 74e24666..99f6aa2d 100644 --- a/docs/STREAMS.md +++ b/docs/STREAMS.md @@ -11,7 +11,7 @@ what each stream carries is here: - **`blob_available` carries the fetch, not just the bytes.** Seven optional fields beyond the blob itself: six describing the *fetch* (#10, cannobserv#271 + #279 — v0.7.5) — `final_url`, `status_code`, `fetched_at`, `content_type_raw`, `etag`, `last_modified` — and `blob_expires_at`, which describes the *store* (cannobserv#301, populated by #28: `stored_at + REPLICATOR_BLOB_TTL_SECONDS`, read before the store so the announced horizon can only fall earlier than the real reap; see [STORAGE.md](STORAGE.md)). Each is what Replicator holds at publish time and a broadcast consumer cannot recover now that fetching lives here rather than in Watcher. **`None` means nobody said it** — never a stand-in: `final_url` is never backfilled from `command.url` (an issuer could no longer tell "landed where I asked" from "nobody knows"), and `content_type_raw` is never backfilled with `DEFAULT_MEDIA_TYPE` (which is the value a consumer reads as "unknown, guess from the URL"). `media_type` keeps its normalized semantics beside the raw channel; the two are not interchangeable. `fetched_at` is stamped where the fetch *returns*, not at publish — `occurred_at` under a reclaim is minutes late. `status_code` is always 2xx on this fact, so it distinguishes 200 from 203/206 and is not a success branch. The passthroughs are **dropped, never repaired**, on two conditions: over `MAX_HEADER_VALUE_LENGTH`, because a truncated ETag replayed in an `If-None-Match` is a validator that can never match; and — `etag` and `last_modified` only, in `_replayable` — outside the printable US-ASCII the request guard accepts, because one Replicator would refuse to send wedges the issuer that stores it (#60). `content_type_raw` takes only the first — never replayed. `src/worker/handler.py::_passthrough`. - **One loop, N command streams (#29).** Everything in `loop.py` is the same decision for every command stream — read `count=1`, refuse a foreign payload, branch on `schema_version` before destructuring, dedupe on `command_id`, ack after the handler, retry the transient and dead-letter the deterministic, fact before ack. What differs is injected as a `CommandSpec`: the payload type its `isinstance` gate accepts, the segment its dedupe keys are namespaced under, the label its journal lines carry, the builder that turns a command plus a cause into *that stream's* failure report, and `describe`, which names a frame in the journal when the correlator cannot (a blank `command_id` is the one dead-letter with nothing to correlate on, so the stream's own identifier — fetch's URL, replicate's destination — is load-bearing there). **A builder that raises degrades to no-fact rather than propagating**: it is called from inside the delivery-ceiling path, so an unguarded raise would escape before anything dead-letters, strand the entry in the PEL, and jam the stream permanently with the ceiling unable to fire — the frame still dead-letters and MUST-6's reaper is the backstop for the missing fact. So `content.replicate` is another `run_loop` with another spec, not a second copy of the module with four differences edited in and nine invariants free to drift. **Dedupe keys are namespaced per stream** (`replicator:cmd::`) — issuer-assigned ids make a cross-stream collision unlikely rather than impossible, and its shape is the worst available: the second command acks having done nothing. **The report is per stream and deliberately not a shared superset** — `ReplicationFailedEvent` models no `status_code` and `FetchFailedEvent` has no `info_item_rep_spec_id`, so one dataclass with everything optional would put fields on the wire path that one of its two producers can never fill. `tests/worker/test_loop_spec.py` drives the loop over a real `ContentReplicateCommand` against a second spec, because a generic seam with one instantiation is untested generality. -- **A fetch is bounded by where it may point, not only by who may issue it (#89, #95).** `content.fetch` is unauthenticated and its bytes are announced on `content.blobs`, so an unbounded destination made the capability *read whatever this node reaches and republish it cluster-wide*; loopback here includes an agent UI answering 200 unauthenticated. `src/worker/egress.py` refuses loopback, RFC 1918, link-local, ULA, multicast/reserved, IANA special-purpose ranges (#161) and the tailnet's CGNAT `100.64.0.0/10`, against **every** address the host resolves to, and any IPv4 address one embeds (NAT64, 6to4, #156) (one public answer beside a loopback one is the cheap half of rebinding). **It is an `httpx` transport, not a check on `command.url`**: redirects are followed by default and the transport runs once per hop, so the obvious pre-flight implementation passes every unit test while a 302 walks around it. A `render="browser"` fetch (#63) goes through capture's per-connection SOCKS guard instead, and since that proxy never sees `file:`, the URL is checked as `http(s)` with a host before the launch (CR 1). Composed in at `build_fetch_client` over an injected client, so `run()` closes it and env proxies no longer apply (CR 1, CR 4). **Since #216 a command scope sits outside it**: the handler sets the command's scope around the fetch, and each hop refuses without one, carries that command's cookies alone (the client's jar never stores, so one command's `Set-Cookie` never rides another's request), and carries a resolved `credential_headers` binding only when the hop is `https`, port 443 and a host in every binding — else `credential_refused`, before DNS, never sent without it. Each hop goes out on a copy of the request, because httpx builds the next hop from the one it handed in. Resolving here owns its failure vocabulary: an unresolvable name is **transient**, an unencodable one terminal, because the loop classifies by exception type (CR 2). An answer the check cannot run on — empty in any shape, not an address, or none within `RESOLVE_TIMEOUT_SECONDS` — is transient too, **never a pass** (#100). The table is env, unset meaning the deny set and no value spelling "off". Left open: rebinding's TOCTOU window. #89 declined a URL allowlist (a second copy of Watcher's `Domain` table) and message signing (CannObserv/broker#14 narrows the too-wide grant). Trust posture and residual: [the request reference](contracts/content-fetch-issuer-reference.md); refusal row: [the outcome reference](contracts/content-fetch-outcome-reference.md). +- **A fetch is bounded by where it may point, not only by who may issue it (#89, #95).** `content.fetch` is unauthenticated and its bytes are announced on `content.blobs`, so an unbounded destination made the capability *read whatever this node reaches and republish it cluster-wide*; loopback here includes an agent UI answering 200 unauthenticated. `src/worker/egress.py` refuses loopback, RFC 1918, link-local, ULA, multicast/reserved, IANA special-purpose ranges (#161) and the tailnet's CGNAT `100.64.0.0/10`, against **every** address the host resolves to, and any IPv4 address one embeds (NAT64, 6to4, #156) (one public answer beside a loopback one is the cheap half of rebinding). **It is an `httpx` transport, not a check on `command.url`**: redirects are followed by default and the transport runs once per hop, so the obvious pre-flight implementation passes every unit test while a 302 walks around it. A `render="browser"` fetch (#63) goes through capture's per-connection SOCKS guard instead, and since that proxy never sees `file:`, the URL is checked as `http(s)` with a host before the launch (CR 1). Composed in at `build_fetch_client` over an injected client, so `run()` closes it and env proxies no longer apply (CR 1, CR 4). **Outside it since #216, the command scope**: per hop, that command's cookies only, and a credential only in its binding's scope, else `credential_refused` before DNS. Resolving here owns its failure vocabulary: an unresolvable name is **transient**, an unencodable one terminal, because the loop classifies by exception type (CR 2). An answer the check cannot run on — empty in any shape, not an address, or none within `RESOLVE_TIMEOUT_SECONDS` — is transient too, **never a pass** (#100). The table is env, unset meaning the deny set and no value spelling "off". Left open: rebinding's TOCTOU window. #89 declined a URL allowlist (a second copy of Watcher's `Domain` table) and message signing (CannObserv/broker#14 narrows the too-wide grant). Trust posture and residual: [the request reference](contracts/content-fetch-issuer-reference.md); refusal row: [the outcome reference](contracts/content-fetch-outcome-reference.md). - **`content.replicate` is the second command loop, and it writes for `gcs` (#29).** Same `run_loop`, `REPLICATE_SPEC` instead of `FETCH_SPEC`, its own consumer group (`replicator.replicate`), its own PEL, its own dedupe namespace. Both outcomes go to **`content.artifacts`**, not `content.blobs` — a fact on the wrong stream reaches a consumer group that will never match it. The write goes through `AsyncGcsDriver.create_if_absent` (co-core-aio's `[gcs]` extra), which is T4's primitive: `ifGenerationMatch=0`, then an md5 comparison on the 412. **A blob already in a bucket is copied server-side instead** (#114 item 5): `copy_if_absent`, a `rewrite` under the same precondition, with the two objects' reported md5s compared on the 412 — the bytes never transit this host, and the journal's `method` says `copy` or `upload`. **`REPLICATOR_REPLICATE_WRITE_TIMEOUT_SECONDS` bounds each rewrite call, not the copy**: co-core loops on the rewrite token, and a rewrite that changes location or storage class may need several calls, each with the full timeout, while the handler holds the group. The three buckets are all `US-WEST1` ([INFRASTRUCTURE.md](INFRASTRUCTURE.md)), so location does not trigger it here — but an issuer's `object_options.storage_class` can. It runs as the alias's writer, which therefore reads the source buckets ([INFRASTRUCTURE.md](INFRASTRUCTURE.md)). Both carry the `co-content-sha256` stamp (#114 item 4). **Four outcomes, three facts** — `WROTE` and `ALREADY_IDENTICAL` both emit `replication_complete` with the same `public_url` (a redelivery onto matching bytes is a no-op that still tells the issuer), `CONFLICT` is a terminal `destination_conflict`, and **`INDETERMINATE` does not close the command** — a 412 whose confirming read found *no object* is a race, not a conflict, and closing it terminally would tell an issuer no artifact is coming about a destination that would accept the next attempt. **Not closing it publishes nothing**: `TransientReplicateError` is exempt from the delivery ceiling, so the entry simply stays pending and `build_replicate_reporter` still stamps `terminal=True` on every fact it does emit — the absence of a fact is what "still trying" looks like on this wire, and MUST-6's reaper bounds it. Emitting a `terminal=false` fact instead would be a contract change, not an implementation detail. **Provider failures are classified by HTTP status, not caught as a class** (CR #27): 5xx, 408, 429 and anything with no status stay open, because T4 makes the retry safe; every other 4xx *closes* — a 400 is the issuer's rendered key or `object_options` (`invalid_destination`), the rest are the host's missing bucket or permission (`provider_disabled`). Classifying them all as transient meant a 403 retried forever and published no fact at all, and `object_options` being an opaque dict made that reachable from the wire. `gdrive` and `ia` have no conditional create yet and take the `provider_disabled` path, the same one a host with no binding takes. diff --git a/docs/contracts/content-fetch-issuer-contract.md b/docs/contracts/content-fetch-issuer-contract.md index 56e3ca3e..ff4ae694 100644 --- a/docs/contracts/content-fetch-issuer-contract.md +++ b/docs/contracts/content-fetch-issuer-contract.md @@ -107,11 +107,8 @@ The refusal list itself — hop-by-hop and derived headers, the rules on names a ceilings, the timeout bounds, the header-name folding rule, and the reasoning behind each — is in [the reference](content-fetch-issuer-reference.md#request-options-what-replicator-will-send-and-what-it-refuses-11). -`credential_headers` (#216) carries **references, never values**: a header name to a -`fetch-` binding the Replicator operator provisioned. A reference resolves only where it was -provisioned, the binding pins its header, hosts and `https`:443, and every redirect hop is held to -it. Its refusals (`invalid_request_options`, `credential_unknown`, `credential_refused`) are in -[the reference](content-fetch-issuer-reference.md#credential_headers-fetch-credential-references-216). +`credential_headers` (#216) carries **references, never values**, resolved only where the operator +provisioned them: [the reference](content-fetch-issuer-reference.md#credential_headers-fetch-credential-references-216). ### The facts diff --git a/docs/contracts/content-fetch-outcome-reference.md b/docs/contracts/content-fetch-outcome-reference.md index 995b0080..33962fd5 100644 --- a/docs/contracts/content-fetch-outcome-reference.md +++ b/docs/contracts/content-fetch-outcome-reference.md @@ -135,8 +135,7 @@ are the whole value of the six: | `detail` | `str \| None` | Free text for the journal. **Never branch on it**, and never show it to an end user — on `handler_error` it is an unanticipated exception's text, so unbounded | The tokens emitted today are `http_status`, `not_modified`, `not_fetchable`, `too_large`, -`destination_refused`, `credential_unknown`, `credential_refused` (both #216), -`unsupported_schema_version`, `invalid_request_options` and `handler_error` — +`destination_refused`, `credential_unknown`, `credential_refused`, `unsupported_schema_version`, `invalid_request_options` and `handler_error` — one per row of the [failure taxonomy](#failure-taxonomy-what-happens-and-what-the-issuer-sees) below, which states each one's condition. Why the list is additive, why `wrong_payload_type` never appears and why every one is `terminal=True`: [Reading the failure fact](#reading-the-failure-fact). @@ -156,9 +155,8 @@ appears and why every one is `terminal=True`: [Reading the failure fact](#readin | HTTP 304 Not Modified — a conditional GET that **succeeded** (#17) | fact, ack, and **no DLQ entry**; the dedupe key is written | `fetch_failed` · `not_modified` (+ `status_code=304`) | | URL not fetchable (bad scheme / invalid URL; under `browser`, a download or non-HTML document) | fact, then `content.fetch.dlq` | `fetch_failed` · `not_fetchable` | | Body over `REPLICATOR_MAX_BLOB_BYTES` (default 64 MiB) | fact, then `content.fetch.dlq` — since #104 **Replicator stops reading at the ceiling**, or before any byte when `Content-Length` declares more | `fetch_failed` · `too_large` | -| Unsendable `headers` / `timeout_seconds` / `render` / `credential_headers` names, or both header maps over the count or byte bound | fact, then `content.fetch.dlq`, **before the fetch** | `fetch_failed` · `invalid_request_options` | -| A `credential_headers` reference this host has no usable binding for — never provisioned, dropped at boot, or off `fetch-` (#216) | fact, then `content.fetch.dlq`, **before the fetch** | `fetch_failed` · `credential_unknown` | -| A credential used outside its binding: another header, or a URL or **redirect hop** not `https`, not on port 443, or not one of every binding's hosts (#216) | fact, then `content.fetch.dlq`, **before the request or the hop goes out**; never sent without the credential instead | `fetch_failed` · `credential_refused` | +| Unsendable `headers` / `timeout_seconds` / `render` | fact, then `content.fetch.dlq`, **before the fetch** | `fetch_failed` · `invalid_request_options` | +| A credential reference unbound here, or used off its binding, **redirect hops** included (#216) | fact, then `content.fetch.dlq`, before the hop | `credential_unknown` / `credential_refused` | | Destination in a range this host will not fetch from — loopback, RFC 1918, link-local, ULA, the tailnet's CGNAT `100.64.0.0/10` (#95), an IANA special-purpose range (#161), or an IPv6 address embedding one (#156) | fact, then `content.fetch.dlq`, **before the request goes out**, and on **each redirect hop** | `fetch_failed` · `destination_refused` | | HTTP 5xx / 408 / 429, a network error, or a fetch still running at `REPLICATOR_MAX_FETCH_SECONDS` (default 120 s, #104) | retry indefinitely, default ~60 s cadence | delayed fact, or **nothing while it retries** | | Blob tree over `REPLICATOR_BLOB_MAX_TOTAL_BYTES` | parked in the PEL until a sweep frees space | delayed fact, or **nothing while it waits** | diff --git a/docs/contracts/replicator-boundaries.md b/docs/contracts/replicator-boundaries.md index 42eee350..009ba5e4 100644 --- a/docs/contracts/replicator-boundaries.md +++ b/docs/contracts/replicator-boundaries.md @@ -112,13 +112,8 @@ cohort convention, kept from when four services shared one VM (#88). **`BUILD_ID mean a per-service variable name for one git SHA. It is exempted by name in the test, not waved through — an exemption list that grows is this convention ending quietly. -**A credential reference is a key, and the value never travels (#216, cannobserv#577).** -`credential_headers` maps a header name to a `fetch-` reference; the binding it names, and -the secret, are host state read at boot, as the alias table is. So env carries the table's path, -the command carries this occasion's reference, and the value rides neither. It passes the three -tests: no per-resource history (cookies now live *shorter*, one command), coordination over a -resource only the fetcher can see (the secret, and the redirect hops only the transport sees), and -no domain vocabulary (a header name, a reference, hostnames). Its scan is §2c of the tests. +**A credential reference is a key; the value never travels (#216)**: the secret is host state, read +at boot, as the alias table is. **The fourth channel is rejected by name: an inbound admin HTTP API.** It is the easy path for every future config need and it ends the property that makes this service testable and @@ -359,8 +354,8 @@ is failing a PR, not documenting an intention. | No domain vocabulary | AST scan of `src/`: `info_source`, `info_item`, `watched_item`, `tenant`, `aspect` appear in no identifier and no string literal — exact `info_source_id` and `info_item_rep_spec_id` exempted in the emit-path modules only, per token | | The echoed keys are never interpreted | AST scan of `src/`: every occurrence of either echoed field is a field declaration, a parameter, the keyword named for **itself**, or that keyword's value; all else fails | | Ingress is read-only | recursive route walk: every path in the allowlist, every method in `{GET, HEAD}` | -| The credential reference is a key; the value is the transport's | AST scan of `src/`: `credential_headers` is read in `handler.py` alone; a reference bound by its `.items()` loop is only a lookup, validator or `Resolved` argument, or a placeholder in a `PermanentFetchError` message — never compared, stored or made a path; the map's values are reached no other way; `get_secret_value()` has one call site, `CommandScopeTransport.handle_async_request` (#216) | -| The deployed process has no ingress | `src/worker/` imports no server framework — `http.server` by name, so `http.cookiejar` (the fetch client's never-storing jar, #216) stays legal; the unit runs `src.worker.main` with no `uvicorn` and no `--port` | +| The credential reference is a key | AST scan: a reference is only looked up, validated or named in a refusal; one `get_secret_value()` call (#216) | +| The deployed process has no ingress | `src/worker/` imports no server framework (`http.server`, not `http.cookiejar`); the unit runs `src.worker.main` with no `uvicorn` and no `--port` | | No locally-defined wire models | no class in `src/` declares an `event_type` field — every wire payload comes from co-core | | No issuer SDK | no dependency on a sibling repo's client in the lock | | Config surface | every `Settings` field is `REPLICATOR_*`-prefixed except `build_id`, exempted by name; no `env_file`; no configuration or network call at import time | From 8a32f35e100c0cd5aa69a83e83673c2ff9aa6992 Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 18:28:36 +0000 Subject: [PATCH 16/23] =?UTF-8?q?#216=20test:=20CR=205=20=E2=80=94=20the?= =?UTF-8?q?=20trailing-newline=20test=20asserts=20the=20off-rule=20branch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Either branch closed it credential_unknown, so it didn't prove the reference is checked whole. Co-Authored-By: Claude Opus 5.5 --- tests/worker/test_handler_credentials.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/worker/test_handler_credentials.py b/tests/worker/test_handler_credentials.py index daf9f0c7..599649bc 100644 --- a/tests/worker/test_handler_credentials.py +++ b/tests/worker/test_handler_credentials.py @@ -402,12 +402,15 @@ async def test_a_refusal_closes_with_a_terminal_fact_that_names_no_value( async def test_a_reference_with_a_trailing_newline_is_off_the_rule(handler): """co-core's pattern ends in ``$``; the rule is checked whole, so ``\\n`` can't ride it.""" - await refused( + error = await refused( handler, command(url=URL, credential_headers={"X-Api-Key": "fetch-wa-leg-api\n"}), FailureReason.CREDENTIAL_UNKNOWN, ) + # The off-rule branch, not the unprovisioned one: the whole string was checked. + assert "not a fetch- reference" in str(error) + async def test_an_unparseable_url_with_credentials_is_not_fetchable(handler): """The scope check parses the URL first; one httpx can't parse closes as ``_fetch`` would.""" From 812d0e592a9939687fc1fc80e43f64a6ff5cd55d Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 18:28:40 +0000 Subject: [PATCH 17/23] =?UTF-8?q?#216=20test:=20CR=206=20=E2=80=94=20pass?= =?UTF-8?q?=20the=20root=20to=20=5Fsecret=5Freads,=20not=20a=20swapped=20g?= =?UTF-8?q?lobal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- tests/test_boundaries.py | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/tests/test_boundaries.py b/tests/test_boundaries.py index 9b8d0155..2d099a82 100644 --- a/tests/test_boundaries.py +++ b/tests/test_boundaries.py @@ -1029,11 +1029,11 @@ def visit(node: ast.AST, prefix: str) -> None: return owner -def _secret_reads(path: Path) -> list[tuple[str, str]]: +def _secret_reads(path: Path, root: Path = REPO) -> list[tuple[str, str]]: tree = _parse(path) owner = _qualified_functions(tree) return [ - (path.relative_to(REPO).as_posix(), owner.get(id(node), "")) + (path.relative_to(root).as_posix(), owner.get(id(node), "")) for node in ast.walk(tree) if isinstance(node, ast.Call) and _call_name(node) == "get_secret_value" ] @@ -1134,12 +1134,7 @@ def test_the_secret_read_detector_sees_a_second_reader(tmp_path): "class T:\n def f(self, c):\n return c.value.get_secret_value()\n" "def leak(c):\n print(c.value.get_secret_value())\n" ) - original = REPO - try: - globals()["REPO"] = tmp_path - reads = _secret_reads(planted) - finally: - globals()["REPO"] = original + reads = _secret_reads(planted, root=tmp_path) assert reads == [("planted.py", "T.f"), ("planted.py", "leak")] From 803f11e8f326e2ccb52bc7a2548f6f7ce7288304 Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 19:00:09 +0000 Subject: [PATCH 18/23] #216 docs: curate the four docs over the 10,000-token budget MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Exact counts (count_tokens), before -> after: docs/DEPLOYMENT.md 10222 -> 9116 docs/contracts/content-fetch-outcome-reference.md 10072 -> 9935 docs/TESTING.md 10025 -> 9984 docs/INFRASTRUCTURE.md 10011 -> 9981 docs/DEPENDENCIES.md (destination) 4097 -> 5193 Relocated (class B, moved verbatim): - DEPLOYMENT.md "### Dependabot proposes the action and Python bumps (#76, #169)" -> DEPENDENCIES.md "## Dependabot proposes the action and Python bumps": the heading lost its provenance per the #162 seams note (both issues stay in the body); its two links re-aimed (DEPLOYMENT.md#main-takes-pull-requests-208, and #the-build-backends-bound-and-cis-uv same-doc). Pointers repointed: .github/dependabot.yml (2), tests/ci/test_dependabot.py, .skills/doc-sections, .skills/doc-sensitive-paths; DEPENDENCIES.md's scope line names the section. Tightened (class C, every atom kept, claims_dropped 0): - outcome reference, "How the blob TTL clock runs": the window's history ("used to be" a host setting) and the operator-side pairing detail INFRASTRUCTURE.md's lifecycle table carries; - TESTING.md: "Both divergences were found by running against the real server", and "The grant's full shape is broker#2's to state" (broker#2 stays on the line); - INFRASTRUCTURE.md: "It reached 97% on 2026-10-22", "not as a courtesy", and the grants subsection's narrative lead-in. Deleted: nothing. No FALSE facts; links, anchors, orphans, unindexed all empty. Seams: 0 after judging 8 — the #216 heading `credential_headers ... (#216)` renamed (its two anchors updated), six standing provenance headings and one legitimate AGENTS.md back-reference acknowledged in .skills/context-seams-ok. Warrants: .skills/context-loss-ok (3 + 11 + 2 + 4), .skills/context-claims-ok (2). Co-Authored-By: Claude Opus 5.5 --- .github/dependabot.yml | 4 +- .skills/context-claims-ok | 8 ++++ .skills/context-loss-ok | 39 +++++++++++++++++++ .skills/context-seams-ok | 16 +++++++- .skills/doc-sections | 2 +- .skills/doc-sensitive-paths | 4 +- docs/DEPENDENCIES.md | 33 +++++++++++++++- docs/DEPLOYMENT.md | 29 -------------- docs/ENVIRONMENT.md | 2 +- docs/INFRASTRUCTURE.md | 8 ++-- docs/TESTING.md | 4 +- .../content-fetch-issuer-contract.md | 2 +- .../content-fetch-issuer-reference.md | 4 +- .../content-fetch-outcome-reference.md | 18 ++++----- tests/ci/test_dependabot.py | 2 +- 15 files changed, 115 insertions(+), 60 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 7a998d7d..7a10dd82 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -4,7 +4,7 @@ # `uv lock` (#169). Each PR is gated by ci.yml; a Dependabot-triggered run is # treated like a fork's, so on a red one read the WIF auth step first (the # verdict table on #76). How one lands, and when a `uv` PR owes a deploy: -# docs/DEPLOYMENT.md -> "Dependabot". +# docs/DEPENDENCIES.md -> "Dependabot". # # The `uv` updater resolves co-core from the co-pypi index (#183) over OIDC: # the org registry admits this repository, and pyproject.toml's index URL @@ -43,7 +43,7 @@ updates: open-pull-requests-limit: 10 groups: # Dev tooling is one PR. Not a no-deploy marker: anyio, httpx and pyyaml - # are runtime transitives too (docs/DEPLOYMENT.md -> "Dependabot"). + # are runtime transitives too (docs/DEPENDENCIES.md -> "Dependabot"). dev-tools: dependency-type: "development" # Dependabot gives a requirement with extras no previous version, and diff --git a/.skills/context-claims-ok b/.skills/context-claims-ok index 5dacdad9..08a2e266 100644 --- a/.skills/context-claims-ok +++ b/.skills/context-claims-ok @@ -46,3 +46,11 @@ docs/SKILLS.md :: retarget :: SOCRATICODE.md docs/SOCRATICODE.md :: disproven :: systemd-run --user --scope -p MemoryHigh=1200M -p MemoryMax=1536M -p CPUQuota=100% -- npm install --prefix ~/.socraticode/pin socraticode@ docs/SOCRATICODE.md :: disproven :: systemd-run --user --scope -p MemoryHigh=1200M -p MemoryMax=1536M -p CPUQuota=100% -- npx -y -p socraticode@ -- node -e 0 docs/CONVENTIONS.md :: disproven :: (+xdel ~content.fetch.dlq ~content.replicate.dlq) + +# ---- #216 curation ---- +# @run base=812d0e592a99 file=docs/DEPLOYMENT.md +# The moved Dependabot section's two links, re-aimed from docs/DEPENDENCIES.md: +# the same-doc anchor now names DEPLOYMENT.md, the DEPENDENCIES.md one is same-doc. +retarget :: #main-takes-pull-requests-208 +retarget :: DEPENDENCIES.md#the-build-backends-bound-and-cis-uv +# @run end diff --git a/.skills/context-loss-ok b/.skills/context-loss-ok index 1725ccb5..1d62b1d5 100644 --- a/.skills/context-loss-ok +++ b/.skills/context-loss-ok @@ -828,3 +828,42 @@ docs/SOCRATICODE.md :: disproven :: `systemd-run --user --scope -p MemoryHigh=12 # #162 CR 1: CONVENTIONS.md quoted a two-queue XDEL selector; broker's deploy/redis-acl.conf # names four (persist and capture joined). It now links the selector's shape instead. docs/CONVENTIONS.md :: disproven :: - **DLQ is a shipped seam, not a TODO:** `dead_letter(message_id, fields, reason=…)` copies the frame to `.dlq` with co-core's `dlq.*` provenance beside it, and acks the original. Deterministic failure ⇒ DLQ; transient failure ⇒ retry. **Draining it is this service's job, and both halves are granted** — `XADD .dlq` parks a frame and, since 2026-09-11, an ACL selector `(+xdel ~content.fetch.dlq ~content.replicate.dlq)` removes one once it is triaged (#86, broker#12). `XDEL` is refused on every other stream and nothing here issues `XTRIM` (#106 — the broker had granted it on both fact streams and both queues, and broker#41 withdraws it), so disposal is one entry at a time by id and a drain can never become a wipe. Resting state for both queues is 0: `docs/COMMANDS.md`. + +# ---- #216 curation: the four docs over the 10,000-token budget ---- +# Each line below was read against its replacement before being warranted. +# @run base=812d0e592a99 file=docs/DEPLOYMENT.md +# The Dependabot section moved verbatim to docs/DEPENDENCIES.md as a `##`; its +# provenance heading lost `(#76, #169)` per the seams-ack note (#162), both issues +# still cited in its body, and its two links were re-aimed from the new home. +rename :: ### Dependabot proposes the action and Python bumps (#76, #169) +retarget :: It proposes one PR per runtime package and one `dev-tools` group PR. +retarget :: Merge a bot PR [like any PR](#main-takes-pull-requests-208) +# @run end +# @run base=812d0e592a99 file=docs/contracts/content-fetch-outcome-reference.md +# The TTL section's history (the window "used to be" a host setting) and the +# operator-side pairing detail, which INFRASTRUCTURE.md's lifecycle table carries; +# every atom kept (claims_dropped 0). +tighten :: **Why the seven-day window is a commitment rather than a number to ask about.** It used to be +tighten :: `REPLICATOR_BLOB_TTL_SECONDS` on Replicator's host — a setting, visible to nobody else, changeable +tighten :: by an operator with no consumer the wiser. Under the object-store backend the reap is a **bucket +tighten :: lifecycle rule**, which is a stated, auditable window rather than an mtime clock that moves for +tighten :: reasons no consumer can see. The rule is `daysSinceCustomTime: 8` against a published 7-day +tighten :: horizon — the extra day for the reason the table below gives. +tighten :: **Nothing keeps the two halves in step automatically under `gcs`.** The published horizon comes from +tighten :: `REPLICATOR_BLOB_TTL_SECONDS` and the reap comes from a lifecycle rule configured in Google Cloud; +tighten :: a rule shorter than the setting would announce a window the bucket will not honour, which is the one +tighten :: way this value can be wrong in the unsafe direction. The worker logs the horizon at boot beside the +tighten :: bucket so the pairing is checkable, and `docs/INFRASTRUCTURE.md` records the provisioned rule. +# @run end +# @run base=812d0e592a99 file=docs/TESTING.md +# Two sentences of how-it-was-found narrative; every atom kept. +tighten :: **Where fakeredis diverges.** It is sound for consumer-group *mechanics* +tighten :: **The shared broker is not a `real_redis` target, three times over.** +# @run end +# @run base=812d0e592a99 file=docs/INFRASTRUCTURE.md +# A dated disk reading, a filler clause and a narrative lead-in; every atom kept. +tighten :: It reached 97% on 2026-10-22. Disk hygiene here is Provisioner' +tighten :: [COMMANDS.md](COMMANDS.md#inspecting-the-consume-path), beside the commands. Some of +tighten :: those rows arrived after broker#2's ACL cutover, and this is how: +tighten :: **`XPENDING` moved columns on 2026-09-22 (broker#39, #103, #107)**, not as a courtesy: the +# @run end diff --git a/.skills/context-seams-ok b/.skills/context-seams-ok index b7709e9b..93174fd1 100644 --- a/.skills/context-seams-ok +++ b/.skills/context-seams-ok @@ -531,7 +531,19 @@ tests/test_socraticode_pin.py :: worker runs beside every session (docs/COMMANDS # # #162: three standing provenance headings, added after #146's sweep by #76, #148 # and #138. Renaming one moves its anchor, which this curation has no reason to -# do. Rename each with its doc's next substantive edit. -docs/DEPLOYMENT.md :: Dependabot proposes the action bumps (#76) +# do. Rename each with its doc's next substantive edit. (#76's went with #216's +# move of the Dependabot section into docs/DEPENDENCIES.md.) docs/INFRASTRUCTURE.md :: The host's disk GC is the cohort's (#148) docs/TESTING.md :: Testing the browser (#138) +# +# #216 curation: provenance headings the interval sweep reached because their docs +# were edited. Each anchor is linked from elsewhere (the moved Dependabot section +# links #main-takes-pull-requests-208 itself), so renaming is its own change. +docs/DEPLOYMENT.md :: Releases (#151) +docs/DEPLOYMENT.md :: `main` takes pull requests (#208) +docs/DEPLOYMENT.md :: The service user (#202) +docs/DEPLOYMENT.md :: The release check — only a release builds a writer (#52, #151) +docs/INFRASTRUCTURE.md :: The captures bucket (#189) +docs/contracts/content-fetch-issuer-reference.md :: `render`: the browser mode (#63) +# DEPENDENCIES.md's scope line names AGENTS.md for the co-core rule, which stays there. +docs/DEPENDENCIES.md :: `AGENTS.md` keeps the co-core rule diff --git a/.skills/doc-sections b/.skills/doc-sections index fb0cdd4d..66db3bda 100644 --- a/.skills/doc-sections +++ b/.skills/doc-sections @@ -22,7 +22,7 @@ docs/ARCHITECTURE.md: Project Layout, one line per module (src/, scripts/) docs/ENVIRONMENT.md: every REPLICATOR_* variable, its default and the reasoning behind it (src/core/config.py) docs/COMMANDS.md: every script with its flags (scripts/) — README.md's Setup, Seeding a fetch and Deploy blocks repeat some of them docs/TESTING.md: what the test and gcs jobs run and why; a checkout change also reaches docs/SKILLS.md's Submodules in CI (.github/workflows/) -docs/DEPLOYMENT.md: the Dependabot section — which ecosystems it proposes, what it excludes, how a bot PR lands (.github/dependabot.yml) +docs/DEPENDENCIES.md: the Dependabot section — which ecosystems it proposes, what it excludes, how a bot PR lands (.github/dependabot.yml) docs/contracts/: normative and linked from sibling repos, so drift here is cross-repo — change a charter and tests/test_boundaries.py together, file a changed issuer obligation in each issuer's repo, and check README.md's two Issuing paragraphs, which summarize the obligations docs/SKILLS.md: the skill and vendor inventory, hook registration and suspension, and The doc-check lists section (skills/, .claude/, .gitmodules, doc-sensitive-paths, doc-sections) AGENTS.md: Code Exploration Notes — run codebase_update in the same change as a manifest description edit; NOT codebase_context_index, which re-embeds every artifact (.socraticodecontextartifacts.json) diff --git a/.skills/doc-sensitive-paths b/.skills/doc-sensitive-paths index b99de78e..62a8cfef 100644 --- a/.skills/doc-sensitive-paths +++ b/.skills/doc-sensitive-paths @@ -35,8 +35,8 @@ deploy/ # CI gates, including the charter enforcement in tests/test_boundaries.py. .github/workflows/ -# Which ecosystems Dependabot proposes, and what it excludes (docs/DEPLOYMENT.md, -# "Dependabot proposes the action bumps"). Enabling uv edits only this file (#76). +# Which ecosystems Dependabot proposes, and what it excludes (docs/DEPENDENCIES.md, +# "Dependabot proposes the action and Python bumps"; moved from DEPLOYMENT.md, #216). .github/dependabot.yml # Normative contracts — linked from sibling repos, so drift here is cross-repo. diff --git a/docs/DEPENDENCIES.md b/docs/DEPENDENCIES.md index a528e6be..6ef9e004 100644 --- a/docs/DEPENDENCIES.md +++ b/docs/DEPENDENCIES.md @@ -1,7 +1,7 @@ # Dependencies -Where co-core comes from, how to reach it, and its pin; then the `uv_build` bound and -CI's uv. `AGENTS.md` keeps the co-core rule and `[build-system]`'s comment keeps the +Where co-core comes from, how to reach it, and its pin; then the `uv_build` bound, +CI's uv, and what Dependabot proposes. `AGENTS.md` keeps the co-core rule and `[build-system]`'s comment keeps the bound's; the reasoning is here. The unit and the deploy recipe are in [DEPLOYMENT.md](DEPLOYMENT.md); every variable is in [ENVIRONMENT.md](ENVIRONMENT.md). @@ -135,3 +135,32 @@ reads to see which packages moved. reads `pyproject.toml` and `uv.lock`, not `ci.yml`. - **Unpinned.** CI took each new minor the day it shipped, which is how the warning got into CI logs. + +## Dependabot proposes the action and Python bumps + +`.github/dependabot.yml` has two blocks, both weekly: + +- **`github-actions`** (#76). Every `uses:` in `ci.yml` pins a commit SHA with a `# vX.Y.Z` comment, and Dependabot moves both. `context-cadence.yml` is excluded, because the installer re-renders it (gregoryfoster/skills#373). +- **`uv`** (#169). It proposes one PR per runtime package and one `dev-tools` group PR. `google-auth[requests]` gets its own PR, because an extras requirement inside a group drops the whole group without an error (#169). Under `increase-if-necessary` each PR raises the requirement's floor in `pyproject.toml` along with the lock. It resolves co-core from the co-pypi index over OIDC, through the org registry that admits this repository. It ignores `co-core*`, which moves by epic #154's pin-move children; `playwright`, whose bump is the viewport-capture runbook's install on every host; and `uv-build`, which moves with the host's uv ([above](#the-build-backends-bound-and-cis-uv)). **Majors arrive as PRs.** To keep a cap, close the PR with `@dependabot ignore this major version`. + +Guarded by `tests/ci/`. Merge a bot PR [like any PR](DEPLOYMENT.md#main-takes-pull-requests-208), then `git pull --ff-only` before the next local commit. If a bot PR is red at the WIF auth step, suspect the Dependabot run's OIDC token before the bump (the verdict table on #76). Read the release notes, not the diff: setup-uv v9 flipped `prune-cache` silently. A bump that changes behaviour takes fix commits pushed onto its branch. + +**Whether a bot PR owes a deploy:** + +- **An action PR** touches only `.github/`, so it needs no deploy and no restart. +- **A `uv` PR owes one only if it changes what a release installs.** `deploy.sh` builds with `uv sync --locked --no-dev`. Some dev packages are also runtime transitives: `anyio`, `httpx` and `pyyaml` from `dev`, and `google-auth` from `co-pypi`. So the group a PR comes from can't tell you, and neither can whether a `[project].dependencies` line moved. A lock-only security PR can move a runtime transitive too. + +Diff the two install sets. It needs no index token and no checkout of the PR: + +```bash +release_set() { # what a release of installs + local d; d=$(mktemp -d) + git show "$1:pyproject.toml" >"$d/pyproject.toml" && git show "$1:uv.lock" >"$d/uv.lock" && + (cd "$d" && uv export --frozen --no-dev --no-emit-project --no-hashes --no-header -q) + rm -rf "$d" +} +git fetch -q origin pull//head +diff <(release_set origin/main) <(release_set FETCH_HEAD) && echo "no deploy owed" +``` + +If any line differs, merge the PR, then deploy the merge commit with `scripts/deploy.sh`, which restarts the worker. diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index e0bdc3c2..6bad24bb 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -289,35 +289,6 @@ losing any `replicator:cmd:*` key costs a re-fetch rather than correctness, including an empty namespace after a flush: [CONVENTIONS.md](CONVENTIONS.md#the-replicatorcmd-keys). -### Dependabot proposes the action and Python bumps (#76, #169) - -`.github/dependabot.yml` has two blocks, both weekly: - -- **`github-actions`** (#76). Every `uses:` in `ci.yml` pins a commit SHA with a `# vX.Y.Z` comment, and Dependabot moves both. `context-cadence.yml` is excluded, because the installer re-renders it (gregoryfoster/skills#373). -- **`uv`** (#169). It proposes one PR per runtime package and one `dev-tools` group PR. `google-auth[requests]` gets its own PR, because an extras requirement inside a group drops the whole group without an error (#169). Under `increase-if-necessary` each PR raises the requirement's floor in `pyproject.toml` along with the lock. It resolves co-core from the co-pypi index over OIDC, through the org registry that admits this repository. It ignores `co-core*`, which moves by epic #154's pin-move children; `playwright`, whose bump is the viewport-capture runbook's install on every host; and `uv-build`, which moves with the host's uv ([DEPENDENCIES.md](DEPENDENCIES.md#the-build-backends-bound-and-cis-uv)). **Majors arrive as PRs.** To keep a cap, close the PR with `@dependabot ignore this major version`. - -Guarded by `tests/ci/`. Merge a bot PR [like any PR](#main-takes-pull-requests-208), then `git pull --ff-only` before the next local commit. If a bot PR is red at the WIF auth step, suspect the Dependabot run's OIDC token before the bump (the verdict table on #76). Read the release notes, not the diff: setup-uv v9 flipped `prune-cache` silently. A bump that changes behaviour takes fix commits pushed onto its branch. - -**Whether a bot PR owes a deploy:** - -- **An action PR** touches only `.github/`, so it needs no deploy and no restart. -- **A `uv` PR owes one only if it changes what a release installs.** `deploy.sh` builds with `uv sync --locked --no-dev`. Some dev packages are also runtime transitives: `anyio`, `httpx` and `pyyaml` from `dev`, and `google-auth` from `co-pypi`. So the group a PR comes from can't tell you, and neither can whether a `[project].dependencies` line moved. A lock-only security PR can move a runtime transitive too. - -Diff the two install sets. It needs no index token and no checkout of the PR: - -```bash -release_set() { # what a release of installs - local d; d=$(mktemp -d) - git show "$1:pyproject.toml" >"$d/pyproject.toml" && git show "$1:uv.lock" >"$d/uv.lock" && - (cd "$d" && uv export --frozen --no-dev --no-emit-project --no-hashes --no-header -q) - rm -rf "$d" -} -git fetch -q origin pull//head -diff <(release_set origin/main) <(release_set FETCH_HEAD) && echo "no deploy owed" -``` - -If any line differs, merge the PR, then deploy the merge commit with `scripts/deploy.sh`, which restarts the worker. - ## Environment Variables Every variable either env file carries, with the reasoning behind each default, diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md index 75746917..ee45d878 100644 --- a/docs/ENVIRONMENT.md +++ b/docs/ENVIRONMENT.md @@ -91,7 +91,7 @@ In `/etc/replicator/.env` (read by the service): "value_file": "/etc/replicator/fetch-credentials/fetch-wa-leg-api" } } ``` - `header` is the one header the value may ride; `hosts` are exact, in `content.fetch-policy`'s form; `value_file` is an absolute path whose content (less one trailing newline) is printable ASCII within the header bound. **Values are read at boot**: rotation is `sudo systemctl restart replicator`. Posture: the directory `root:replicator 0750`, the table and each value `0640`. A bad binding drops itself (WARNING, never quoting a value); boot logs `fetch credentials loaded` (references, headers, hosts, paths) or `no fetch credential table on this host — …` at INFO. Rules and refusals: [the issuer reference](contracts/content-fetch-issuer-reference.md#credential_headers-fetch-credential-references-216). + `header` is the one header the value may ride; `hosts` are exact, in `content.fetch-policy`'s form; `value_file` is an absolute path whose content (less one trailing newline) is printable ASCII within the header bound. **Values are read at boot**: rotation is `sudo systemctl restart replicator`. Posture: the directory `root:replicator 0750`, the table and each value `0640`. A bad binding drops itself (WARNING, never quoting a value); boot logs `fetch credentials loaded` (references, headers, hosts, paths) or `no fetch credential table on this host — …` at INFO. Rules and refusals: [the issuer reference](contracts/content-fetch-issuer-reference.md#credential_headers-fetch-credential-references). - `REPLICATOR_LOG_LEVEL` — default `INFO`. Governs the **root** logger only, which is the whole tree for the worker. Under the dev server's `--log-config`, uvicorn's own `uvicorn` / `uvicorn.access` / `uvicorn.error` loggers are pinned `INFO` by `src/core/log_config.json` and do not follow it (nor did they under uvicorn's built-in config), so setting `WARNING` will not silence access lines; root itself is `INFO` from boot until the lifespan's `configure_logging()` applies this value - `BUILD_ID` — git SHA stamped by the systemd unit's `ExecStartPre`; defaults to `"dev"` outside systemd diff --git a/docs/INFRASTRUCTURE.md b/docs/INFRASTRUCTURE.md index e7f52340..04d53f42 100644 --- a/docs/INFRASTRUCTURE.md +++ b/docs/INFRASTRUCTURE.md @@ -19,7 +19,7 @@ The worker binds no port; 8000 is reserved for the API, 8001 is dev. No tailnet ## The host's disk GC is the cohort's (#148) -The root is shared by the worker's temp blobs, the journal, and the dev sessions' tooling trees. It reached 97% on 2026-10-22. Disk hygiene here is Provisioner's canonical GC and headroom sensor (`cannobserv-disk-gc.timer`, `cannobserv-disk-headroom.timer`), adopted through the [`maintaining-host-disk`](../skills/maintaining-host-disk/) skill and never built here. It's a host install, not a `deploy/` copy: the config and key live in `/etc/cannobserv/disk-gc/`, outside the repo. The installed `VERSION`, the lines and tiers, and each timer's state are recorded on #148. +The root is shared by the worker's temp blobs, the journal, and the dev sessions' tooling trees. Disk hygiene here is Provisioner's canonical GC and headroom sensor (`cannobserv-disk-gc.timer`, `cannobserv-disk-headroom.timer`), adopted through the [`maintaining-host-disk`](../skills/maintaining-host-disk/) skill and never built here. It's a host install, not a `deploy/` copy: the config and key live in `/etc/cannobserv/disk-gc/`, outside the repo. The installed `VERSION`, the lines and tiers, and each timer's state are recorded on #148. ## The broker is `co-broker` — Replicator connects, it does not run one @@ -32,10 +32,10 @@ The **redis-py client** resolves `>=5,<8` transitively via `co-core-aio[bus]`. D ### Grants the `replicator` user gained later What this credential may run, and what to ask the broker operator for, is tabulated in -[COMMANDS.md](COMMANDS.md#inspecting-the-consume-path), beside the commands. Some of -those rows arrived after broker#2's ACL cutover, and this is how: +[COMMANDS.md](COMMANDS.md#inspecting-the-consume-path), beside the commands. Rows that +arrived after broker#2's ACL cutover: -**`XPENDING` moved columns on 2026-09-22 (broker#39, #103, #107)**, not as a courtesy: the +**`XPENDING` moved columns on 2026-09-22 (broker#39, #103, #107)**: the delivery ceiling reads it, so before the grant `REPLICATOR_MAX_DELIVERY_ATTEMPTS` could never fire. Probed afterwards, like every row: both groups answered 0 pending, where 12:55Z had returned `NOPERM`. diff --git a/docs/TESTING.md b/docs/TESTING.md index a7cbf940..8af06864 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -29,11 +29,11 @@ test-only variables, defined in `tests/conftest.py`. **Testing the bus.** `tests/conftest.py` ships a `fake_redis` fixture (fakeredis, Streams-capable) — consumer-group behaviour is testable without a broker, and assertions should read the broker's own view (`xinfo_groups` / `xinfo_consumers`) rather than co-core's private attributes, which are not a stable contract. Anything that genuinely needs a live Redis goes behind `@pytest.mark.integration` and is excluded by default. -**Where fakeredis diverges.** It is sound for consumer-group *mechanics* — what state a command leaves behind — but diverges on *lifecycle* and *blocking* semantics: it registers a consumer on an empty `XREADGROUP` (real Redis waits for a delivery, GH #3) and it ignores `block` (worked around by `IDLE_SLEEP_SECONDS` in `src/worker/loop.py`). Its `XAUTOCLAIM` is wrong outright (fakeredis 2.37.0): the cursor is the highest *claimed* id rather than the next to scan, never `0-0`, with no `count * 10` attempt budget — so a cursor-following walk on it re-claims the entry it just claimed and never ends. `fake_redis` replaces the command with one rebuilt from `XPENDING` + `XCLAIM`, which the fake does get right, and `tests/worker/test_fake_xautoclaim_integration.py` holds the rebuild to a real server scenario by scenario (#109). A test that patches `fake_redis.xpending_range` to simulate a refusal still refuses only the worker's own call: the rebuild binds its primitives at fixture creation. Rule of thumb: an assertion about **what state results** is safe against the fake; an assertion about **when Redis does something** needs a live broker. Both divergences were found by running against the real server, not by the suite. +**Where fakeredis diverges.** It is sound for consumer-group *mechanics* — what state a command leaves behind — but diverges on *lifecycle* and *blocking* semantics: it registers a consumer on an empty `XREADGROUP` (real Redis waits for a delivery, GH #3) and it ignores `block` (worked around by `IDLE_SLEEP_SECONDS` in `src/worker/loop.py`). Its `XAUTOCLAIM` is wrong outright (fakeredis 2.37.0): the cursor is the highest *claimed* id rather than the next to scan, never `0-0`, with no `count * 10` attempt budget — so a cursor-following walk on it re-claims the entry it just claimed and never ends. `fake_redis` replaces the command with one rebuilt from `XPENDING` + `XCLAIM`, which the fake does get right, and `tests/worker/test_fake_xautoclaim_integration.py` holds the rebuild to a real server scenario by scenario (#109). A test that patches `fake_redis.xpending_range` to simulate a refusal still refuses only the worker's own call: the rebuild binds its primitives at fixture creation. Rule of thumb: an assertion about **what state results** is safe against the fake; an assertion about **when Redis does something** needs a live broker. Live-broker tests use the `real_redis` fixture (`tests/conftest.py`), which connects to `REPLICATOR_TEST_REDIS_URL` (default `redis://localhost:6379/15` — a scratch server on this host, never the broker), skips when nothing answers (an *auth* failure re-raises — a misconfigured broker must not pass as a skip), expires stray `replicator.itest.*` keys from crashed runs once per session, and refuses two targets outright, from the URL and before dialling (`redis_target_refusal`): any host that is not loopback (#132), and db 0 — db 0 carries the live `content.fetch` stream that the running `replicator.service` consumes, so a test frame written there would be fetched for real. A unix socket counts as this host. Confine such tests to scratch stream keys via the `scratch_topic` fixture (`tests/worker/conftest.py`), whose teardown also removes `.dlq`; the guards are the backstop, not the plan. -**The shared broker is not a `real_redis` target, three times over.** First, the fixture never dials it: `broker` is not loopback, so `REPLICATOR_TEST_REDIS_URL=redis://broker:6379/15` fails every live-broker test before a connection exists (#132). Before that guard the URL connected and authenticated and only `SELECT 15` failed — late enough to leave a client in co-broker's `CLIENT LIST` and, for `replicator`, a `NOPERM` entry in the `ACL LOG` its operator reads as evidence (CannObserv/broker#48). A non-loopback scratch server, if one is ever wanted, is a separate opt-in under its own name that cannot be co-broker, not a widening of this one. Second, broker#2's ACL cutover: `select` is not among the `replicator` user's granted commands, so past the guard every live-broker test would fail with `NoPermissionError: this user has no permissions to run the 'select' command`, on connect and before any test body runs. (`scan`, `xinfo|groups`, `xinfo|consumers`, `client|list` and `acl|log` are denied too, and `xpending` was until broker#39 granted it for the delivery ceiling (#103). The operator half of that split is tabulated in [COMMANDS.md](COMMANDS.md#inspecting-the-consume-path). It is why a connection-shape question like #85's has to be answered from the broker side rather than from here. The grant's full shape is broker#2's to state, not this file's.) That is the grant working: db 15 on a broker whose db 0 carries the live `content.fetch` stream is one typo away from the stream `replicator.service` is consuming. +**The shared broker is not a `real_redis` target, three times over.** First, the fixture never dials it: `broker` is not loopback, so `REPLICATOR_TEST_REDIS_URL=redis://broker:6379/15` fails every live-broker test before a connection exists (#132). Before that guard the URL connected and authenticated and only `SELECT 15` failed — late enough to leave a client in co-broker's `CLIENT LIST` and, for `replicator`, a `NOPERM` entry in the `ACL LOG` its operator reads as evidence (CannObserv/broker#48). A non-loopback scratch server, if one is ever wanted, is a separate opt-in under its own name that cannot be co-broker, not a widening of this one. Second, broker#2's ACL cutover: `select` is not among the `replicator` user's granted commands, so past the guard every live-broker test would fail with `NoPermissionError: this user has no permissions to run the 'select' command`, on connect and before any test body runs. (`scan`, `xinfo|groups`, `xinfo|consumers`, `client|list` and `acl|log` are denied too, and `xpending` was until broker#39 granted it for the delivery ceiling (#103). The operator half of that split is tabulated in [COMMANDS.md](COMMANDS.md#inspecting-the-consume-path). It is why a connection-shape question like #85's has to be answered from the broker side rather than from here.) That is the grant working: db 15 on a broker whose db 0 carries the live `content.fetch` stream is one typo away from the stream `replicator.service` is consuming. Third, and for any credential: **the broker has one database** since 2026-09-10 (`databases 1`, broker#5). `SELECT 15` fails outright there, and db 0 — the only one — is the database this fixture refuses, so a repointed URL has nowhere to land (#90). That is deliberate on the broker's side, the database-index half of its R4 guard — the topic-name half is closed by co-broker declaring no test credential at all (CannObserv/broker#53, which deleted broker#2's `citest` on 2026-10-06), and neither substitutes for the other, since Redis ACLs cannot partition by database index — and the db-0 refusal here stays: on a one-database broker it is what keeps a test run off the database the live stream is on. Nor does the default point at the broker: `localhost` on `co-replicator` is not `co-broker` (#88). Run a scratch server on the default's port — `redis-server --bind 127.0.0.1 --save '' --appendonly no`, which the default finds with no variable set, since nothing else here listens on 6379 and the packaged service is masked. `test_oom_integration.py` spawns its own and needs neither. diff --git a/docs/contracts/content-fetch-issuer-contract.md b/docs/contracts/content-fetch-issuer-contract.md index ff4ae694..81c4b8f8 100644 --- a/docs/contracts/content-fetch-issuer-contract.md +++ b/docs/contracts/content-fetch-issuer-contract.md @@ -108,7 +108,7 @@ ceilings, the timeout bounds, the header-name folding rule, and the reasoning be [the reference](content-fetch-issuer-reference.md#request-options-what-replicator-will-send-and-what-it-refuses-11). `credential_headers` (#216) carries **references, never values**, resolved only where the operator -provisioned them: [the reference](content-fetch-issuer-reference.md#credential_headers-fetch-credential-references-216). +provisioned them: [the reference](content-fetch-issuer-reference.md#credential_headers-fetch-credential-references). ### The facts diff --git a/docs/contracts/content-fetch-issuer-reference.md b/docs/contracts/content-fetch-issuer-reference.md index b740f8a7..54946f7f 100644 --- a/docs/contracts/content-fetch-issuer-reference.md +++ b/docs/contracts/content-fetch-issuer-reference.md @@ -131,9 +131,9 @@ checks on **every connection the page opens**, not only on the URL and its redir same URL, so the first fetch after a flip reads as a content change. Whether to re-baseline is the issuer's call (archiver#379). -### `credential_headers`: fetch credential references (#216) +### `credential_headers`: fetch credential references -**What it is.** `credential_headers` (co-core **0.51.1**, cannobserv#577) maps a header name to a +**What it is.** `credential_headers` (co-core **0.51.1**, cannobserv#577; #216) maps a header name to a `fetch-` **reference**, e.g. `{"X-Api-Key": "fetch-wa-leg-api"}`. The reference names a binding an operator provisioned on Replicator's host; the binding holds the value. **The value never travels on the bus**, and Replicator never echoes it: not on a fact, not in `detail`, not in the diff --git a/docs/contracts/content-fetch-outcome-reference.md b/docs/contracts/content-fetch-outcome-reference.md index 33962fd5..2d9b3947 100644 --- a/docs/contracts/content-fetch-outcome-reference.md +++ b/docs/contracts/content-fetch-outcome-reference.md @@ -307,12 +307,10 @@ have and must not grow. Expands [MUST-7](content-fetch-issuer-contract.md#7-copy-the-bytes-before-the-blob-expires). -**Why the seven-day window is a commitment rather than a number to ask about.** It used to be -`REPLICATOR_BLOB_TTL_SECONDS` on Replicator's host — a setting, visible to nobody else, changeable -by an operator with no consumer the wiser. Under the object-store backend the reap is a **bucket -lifecycle rule**, which is a stated, auditable window rather than an mtime clock that moves for -reasons no consumer can see. The rule is `daysSinceCustomTime: 8` against a published 7-day -horizon — the extra day for the reason the table below gives. +**The seven-day window is a commitment, not a number to ask about.** Under the object-store backend +the reap is a **bucket lifecycle rule** on `REPLICATOR_BLOB_TTL_SECONDS`'s horizon: +`daysSinceCustomTime: 8` against a published 7 days, the extra day for the reason the table below +gives. The clock runs from **last reference by a fetch**, not last read by a consumer, and **both backends implement that same rule by different means**. A consumer reading the blob extends nothing, on @@ -335,11 +333,9 @@ moment the reap measures against — and every mechanism after it pushes the rea The error is one-way: acting on the horizon is early, never too late. A later fetch pushes the expiry out and emits a fresh fact carrying the new value. -**Nothing keeps the two halves in step automatically under `gcs`.** The published horizon comes from -`REPLICATOR_BLOB_TTL_SECONDS` and the reap comes from a lifecycle rule configured in Google Cloud; -a rule shorter than the setting would announce a window the bucket will not honour, which is the one -way this value can be wrong in the unsafe direction. The worker logs the horizon at boot beside the -bucket so the pairing is checkable, and `docs/INFRASTRUCTURE.md` records the provisioned rule. +**Nothing keeps the two halves in step under `gcs`**: the horizon is `REPLICATOR_BLOB_TTL_SECONDS`, +the reap a lifecycle rule in Google Cloud. A rule shorter than the setting is the one way this value +can be wrong in the unsafe direction; the boot log and `docs/INFRASTRUCTURE.md` are the check. Also, on the reaper [MUST-6](content-fetch-issuer-contract.md#6-handle-fetch_failed-and-keep-a-reaper-anyway) keeps: diff --git a/tests/ci/test_dependabot.py b/tests/ci/test_dependabot.py index 95485552..27725c25 100644 --- a/tests/ci/test_dependabot.py +++ b/tests/ci/test_dependabot.py @@ -220,7 +220,7 @@ def test_uv_strategy_is_not_the_unsupported_widen(uv_block): def test_uv_dev_tools_are_one_grouped_pr(uv_block): """One group, for development dependencies only. Not a no-deploy marker: - some dev packages are runtime transitives too (docs/DEPLOYMENT.md).""" + some dev packages are runtime transitives too (docs/DEPENDENCIES.md).""" groups = uv_block.get("groups", {}) assert list(groups) == ["dev-tools"] assert groups["dev-tools"].get("dependency-type") == "development" From f49fa80cab7e77f7cfb4cf8b446194292ea76dff Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 19:01:11 +0000 Subject: [PATCH 19/23] #216 chore: curation telemetry for the four over-budget docs A baseline row per doc at 812d0e5 and a curation row per doc at 803f11e. Co-Authored-By: Claude Opus 5.5 --- .skills/context-metrics.jsonl | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.skills/context-metrics.jsonl b/.skills/context-metrics.jsonl index dbe883ca..7fece113 100644 --- a/.skills/context-metrics.jsonl +++ b/.skills/context-metrics.jsonl @@ -81,3 +81,11 @@ {"actions": ["baseline:scheduled"], "budget": 6000, "bytes": 14077, "claims_dropped": null, "claims_warranted": null, "counts": null, "counts_acked": null, "delta_days": 7, "delta_tokens": -18, "docs_orphaned": 0, "docs_total": 24, "docs_unindexed": 0, "file": "AGENTS.md", "lines": 249, "links_dead": 0, "links_dead_anchors": 0, "no_loss": null, "no_loss_warrants": null, "note": null, "over_budget": false, "repo": "replicator", "repo_commit": "93fb513", "seams": 0, "seams_acked": 42, "skill_commit": "de245880", "skill_version": "1.31", "tokens": 5960, "tokens_exact": true, "tokens_live": 181136, "top_section": "Bus Conventions", "top_section_share": 24, "ts": "2026-11-03"} {"actions": ["baseline:scheduled"], "budget": 6000, "bytes": 13938, "claims_dropped": null, "claims_warranted": null, "counts": null, "counts_acked": null, "delta_days": 7, "delta_tokens": -63, "docs_orphaned": 0, "docs_total": 25, "docs_unindexed": 0, "file": "AGENTS.md", "lines": 244, "links_dead": 0, "links_dead_anchors": 0, "no_loss": null, "no_loss_warrants": null, "note": null, "over_budget": false, "repo": "replicator", "repo_commit": "294e489", "seams": 2, "seams_acked": 42, "skill_commit": "1803026d", "skill_version": "1.31", "tokens": 5897, "tokens_exact": true, "tokens_live": 184932, "top_section": "Bus Conventions", "top_section_share": 24, "ts": "2026-11-10"} {"actions": ["baseline:scheduled"], "budget": 6000, "bytes": 14042, "claims_dropped": null, "claims_warranted": null, "counts": 1, "counts_acked": 4, "delta_days": 7, "delta_tokens": 55, "docs_orphaned": 0, "docs_total": 25, "docs_unindexed": 0, "file": "AGENTS.md", "lines": 245, "links_dead": 0, "links_dead_anchors": 0, "no_loss": null, "no_loss_warrants": null, "note": null, "over_budget": false, "repo": "replicator", "repo_commit": "a072ba5", "seams": 7, "seams_acked": 40, "skill_commit": "063ba5db", "skill_version": "1.31", "tokens": 5952, "tokens_exact": true, "tokens_live": 191097, "top_section": "Bus Conventions", "top_section_share": 24, "ts": "2026-11-17"} +{"actions": ["baseline:pre-curation"], "budget": 10000, "bytes": 25844, "claims_dropped": null, "claims_warranted": null, "counts": null, "counts_acked": null, "delta_days": 37, "delta_tokens": 2652, "docs_orphaned": 2, "docs_total": 24, "docs_unindexed": 13, "file": "docs/DEPLOYMENT.md", "lines": 333, "links_dead": 0, "links_dead_anchors": 0, "no_loss": null, "no_loss_warrants": null, "note": null, "over_budget": true, "repo": "replicator", "repo_commit": "812d0e5", "seams": null, "seams_acked": null, "skill_commit": "817963f6", "skill_version": "1.31", "tokens": 10222, "tokens_exact": true, "tokens_live": 184262, "top_section": "Server Lifecycle", "top_section_share": 52, "ts": "2026-11-23"} +{"actions": ["baseline:pre-curation"], "budget": 10000, "bytes": 26714, "claims_dropped": null, "claims_warranted": null, "counts": null, "counts_acked": null, "delta_days": 60, "delta_tokens": 551, "docs_orphaned": 2, "docs_total": 24, "docs_unindexed": 19, "file": "docs/contracts/content-fetch-outcome-reference.md", "lines": 370, "links_dead": 0, "links_dead_anchors": 0, "no_loss": null, "no_loss_warrants": null, "note": null, "over_budget": true, "repo": "replicator", "repo_commit": "812d0e5", "seams": null, "seams_acked": null, "skill_commit": "817963f6", "skill_version": "1.31", "tokens": 10072, "tokens_exact": true, "tokens_live": 184262, "top_section": "The enriched `blob_available` fields", "top_section_share": 19, "ts": "2026-11-23"} +{"actions": ["baseline:pre-curation"], "budget": 10000, "bytes": 26546, "claims_dropped": null, "claims_warranted": null, "counts": null, "counts_acked": null, "delta_days": null, "delta_tokens": null, "docs_orphaned": 2, "docs_total": 24, "docs_unindexed": 17, "file": "docs/TESTING.md", "lines": 293, "links_dead": 0, "links_dead_anchors": 0, "no_loss": null, "no_loss_warrants": null, "note": null, "over_budget": true, "repo": "replicator", "repo_commit": "812d0e5", "seams": null, "seams_acked": null, "skill_commit": "817963f6", "skill_version": "1.31", "tokens": 10025, "tokens_exact": true, "tokens_live": 184262, "top_section": "Testing the write path", "top_section_share": 38, "ts": "2026-11-23"} +{"actions": ["baseline:pre-curation"], "budget": 10000, "bytes": 25254, "claims_dropped": null, "claims_warranted": null, "counts": null, "counts_acked": null, "delta_days": null, "delta_tokens": null, "docs_orphaned": 2, "docs_total": 24, "docs_unindexed": 14, "file": "docs/INFRASTRUCTURE.md", "lines": 298, "links_dead": 0, "links_dead_anchors": 0, "no_loss": null, "no_loss_warrants": null, "note": null, "over_budget": true, "repo": "replicator", "repo_commit": "812d0e5", "seams": null, "seams_acked": null, "skill_commit": "817963f6", "skill_version": "1.31", "tokens": 10011, "tokens_exact": true, "tokens_live": 184262, "top_section": "The temp-blob buckets — live since 2026-08-20 (#7)", "top_section_share": 24, "ts": "2026-11-23"} +{"actions": ["demote:Dependabot proposes the action and Python bumps", "rename:provenance-heading"], "budget": 10000, "bytes": 23126, "claims_dropped": 0, "claims_warranted": 2, "counts": 16, "counts_acked": 0, "delta_days": 0, "delta_tokens": -1106, "docs_orphaned": 2, "docs_total": 24, "docs_unindexed": 13, "file": "docs/DEPLOYMENT.md", "lines": 304, "links_dead": 0, "links_dead_anchors": 0, "no_loss": "ok", "no_loss_warrants": 3, "note": null, "over_budget": false, "repo": "replicator", "repo_commit": "803f11e", "seams": 0, "seams_acked": 46, "skill_commit": "817963f6", "skill_version": "1.31", "tokens": 9116, "tokens_exact": true, "tokens_live": 184043, "top_section": "Server Lifecycle", "top_section_share": 46, "ts": "2026-11-23"} +{"actions": ["tighten:How the blob TTL clock runs"], "budget": 10000, "bytes": 26259, "claims_dropped": 0, "claims_warranted": 0, "counts": 19, "counts_acked": 0, "delta_days": 0, "delta_tokens": -137, "docs_orphaned": 2, "docs_total": 24, "docs_unindexed": 19, "file": "docs/contracts/content-fetch-outcome-reference.md", "lines": 366, "links_dead": 0, "links_dead_anchors": 0, "no_loss": "ok", "no_loss_warrants": 11, "note": null, "over_budget": false, "repo": "replicator", "repo_commit": "803f11e", "seams": 0, "seams_acked": 46, "skill_commit": "817963f6", "skill_version": "1.31", "tokens": 9935, "tokens_exact": true, "tokens_live": 184043, "top_section": "The enriched `blob_available` fields", "top_section_share": 20, "ts": "2026-11-23"} +{"actions": ["tighten:Testing the bus"], "budget": 10000, "bytes": 26400, "claims_dropped": 0, "claims_warranted": 0, "counts": 20, "counts_acked": 0, "delta_days": 0, "delta_tokens": -41, "docs_orphaned": 2, "docs_total": 24, "docs_unindexed": 17, "file": "docs/TESTING.md", "lines": 293, "links_dead": 0, "links_dead_anchors": 0, "no_loss": "ok", "no_loss_warrants": 2, "note": null, "over_budget": false, "repo": "replicator", "repo_commit": "803f11e", "seams": 0, "seams_acked": 46, "skill_commit": "817963f6", "skill_version": "1.31", "tokens": 9984, "tokens_exact": true, "tokens_live": 184043, "top_section": "Testing the write path", "top_section_share": 38, "ts": "2026-11-23"} +{"actions": ["tighten:The host's disk GC is the cohort's", "tighten:Grants the replicator user gained later"], "budget": 10000, "bytes": 25179, "claims_dropped": 0, "claims_warranted": 0, "counts": 8, "counts_acked": 0, "delta_days": 0, "delta_tokens": -30, "docs_orphaned": 2, "docs_total": 24, "docs_unindexed": 14, "file": "docs/INFRASTRUCTURE.md", "lines": 298, "links_dead": 0, "links_dead_anchors": 0, "no_loss": "ok", "no_loss_warrants": 4, "note": null, "over_budget": false, "repo": "replicator", "repo_commit": "803f11e", "seams": 0, "seams_acked": 46, "skill_commit": "817963f6", "skill_version": "1.31", "tokens": 9981, "tokens_exact": true, "tokens_live": 184043, "top_section": "The temp-blob buckets — live since 2026-08-20 (#7)", "top_section_share": 24, "ts": "2026-11-23"} From e875da9343230c145d8e3071349f42e14bd68246 Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 19:02:26 +0000 Subject: [PATCH 20/23] =?UTF-8?q?#216=20docs:=20CR=207=20=E2=80=94=20the?= =?UTF-8?q?=20lifecycle=20rule=20isn't=20on=20the=20TTL=20setting?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The tightening said the reap rule was 'on REPLICATOR_BLOB_TTL_SECONDS's horizon', contradicting the next paragraph (nothing keeps the two in step). The rule is daysSinceCustomTime: 8 against the horizon published from the setting. Restores what the boot line shows. Co-Authored-By: Claude Opus 5.5 --- docs/contracts/content-fetch-outcome-reference.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/contracts/content-fetch-outcome-reference.md b/docs/contracts/content-fetch-outcome-reference.md index 2d9b3947..15733b6a 100644 --- a/docs/contracts/content-fetch-outcome-reference.md +++ b/docs/contracts/content-fetch-outcome-reference.md @@ -308,9 +308,8 @@ have and must not grow. Expands [MUST-7](content-fetch-issuer-contract.md#7-copy-the-bytes-before-the-blob-expires). **The seven-day window is a commitment, not a number to ask about.** Under the object-store backend -the reap is a **bucket lifecycle rule** on `REPLICATOR_BLOB_TTL_SECONDS`'s horizon: -`daysSinceCustomTime: 8` against a published 7 days, the extra day for the reason the table below -gives. +the reap is a **bucket lifecycle rule**, `daysSinceCustomTime: 8`, against the 7-day horizon published +from `REPLICATOR_BLOB_TTL_SECONDS`; the extra day is for the reason the table below gives. The clock runs from **last reference by a fetch**, not last read by a consumer, and **both backends implement that same rule by different means**. A consumer reading the blob extends nothing, on @@ -335,7 +334,8 @@ expiry out and emits a fresh fact carrying the new value. **Nothing keeps the two halves in step under `gcs`**: the horizon is `REPLICATOR_BLOB_TTL_SECONDS`, the reap a lifecycle rule in Google Cloud. A rule shorter than the setting is the one way this value -can be wrong in the unsafe direction; the boot log and `docs/INFRASTRUCTURE.md` are the check. +can be wrong in the unsafe direction. The worker logs the horizon at boot beside the bucket, and +`docs/INFRASTRUCTURE.md` records the rule. Also, on the reaper [MUST-6](content-fetch-issuer-contract.md#6-handle-fetch_failed-and-keep-a-reaper-anyway) keeps: From 6c4f8482a28991ad9e81b47f03780eaaa4e45b8a Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 19:02:31 +0000 Subject: [PATCH 21/23] =?UTF-8?q?#216=20docs:=20CR=208=20=E2=80=94=20DEPLO?= =?UTF-8?q?YMENT=20points=20at=20whether=20a=20bot=20PR=20owes=20a=20deplo?= =?UTF-8?q?y?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Dependabot move left the deploy question without a pointer from the doc an operator reads for it; a row in its when-to-do-what table. Co-Authored-By: Claude Opus 5.5 --- docs/DEPLOYMENT.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 6bad24bb..0ffa7334 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -195,6 +195,7 @@ world-readable, so `-m browser` still runs as `exedev`. | After editing `deploy/needrestart.conf.d/replicator.conf` | `sudo install -D -m 644 deploy/needrestart.conf.d/replicator.conf /etc/needrestart/conf.d/replicator.conf` — **no reload**, apt's hook reads it at the next dpkg run; `sudo needrestart -m u -r l -b` printing `Disabling Ubuntu mode` proves it loads. Without it a security apply restarts the worker mid-apply, outside any window (#122) | | Reading what the failure handler reported | `journalctl -t replicator-failure` — **not** `journalctl -u`; why, in [FAILURE-NOTIFICATION.md](FAILURE-NOTIFICATION.md) | | After a co-core pin move | the procedure in [DEPENDENCIES.md](DEPENDENCIES.md#moving-the-pin), then deploy | +| After merging a Dependabot PR | an action PR owes none; a `uv` PR owes one when what a release installs changed — [the check](DEPENDENCIES.md#dependabot-proposes-the-action-and-python-bumps) | | `Start request repeated too quickly` | `sudo systemctl reset-failed replicator && sudo systemctl start replicator` — the rate limit, not a broken build | **A start syncs nothing.** `ExecStart` runs the release's own `.venv`, built at deploy From da647eae4397816d6e9200eff75a6702345f978f Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 19:02:31 +0000 Subject: [PATCH 22/23] =?UTF-8?q?#216=20docs:=20CR=209=20=E2=80=94=20rewra?= =?UTF-8?q?p=20DEPENDENCIES.md's=20scope=20paragraph?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- docs/DEPENDENCIES.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/DEPENDENCIES.md b/docs/DEPENDENCIES.md index 6ef9e004..f95c857d 100644 --- a/docs/DEPENDENCIES.md +++ b/docs/DEPENDENCIES.md @@ -1,9 +1,10 @@ # Dependencies Where co-core comes from, how to reach it, and its pin; then the `uv_build` bound, -CI's uv, and what Dependabot proposes. `AGENTS.md` keeps the co-core rule and `[build-system]`'s comment keeps the -bound's; the reasoning is here. The unit and the deploy recipe are in -[DEPLOYMENT.md](DEPLOYMENT.md); every variable is in [ENVIRONMENT.md](ENVIRONMENT.md). +CI's uv, and what Dependabot proposes. `AGENTS.md` keeps the co-core rule and +`[build-system]`'s comment keeps the bound's; the reasoning is here. The unit and the +deploy recipe are in [DEPLOYMENT.md](DEPLOYMENT.md); every variable is in +[ENVIRONMENT.md](ENVIRONMENT.md). ## The co-pypi index From a70c7ade434337e11f634306d220915b28e27422 Mon Sep 17 00:00:00 2001 From: gregoryfoster Date: Mon, 23 Nov 2026 19:03:04 +0000 Subject: [PATCH 23/23] #216 chore: amend the curation rows for CR 7 and CR 8's late fixes Co-Authored-By: Claude Opus 5.5 --- .skills/context-metrics.jsonl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.skills/context-metrics.jsonl b/.skills/context-metrics.jsonl index 7fece113..cc4f875d 100644 --- a/.skills/context-metrics.jsonl +++ b/.skills/context-metrics.jsonl @@ -85,7 +85,7 @@ {"actions": ["baseline:pre-curation"], "budget": 10000, "bytes": 26714, "claims_dropped": null, "claims_warranted": null, "counts": null, "counts_acked": null, "delta_days": 60, "delta_tokens": 551, "docs_orphaned": 2, "docs_total": 24, "docs_unindexed": 19, "file": "docs/contracts/content-fetch-outcome-reference.md", "lines": 370, "links_dead": 0, "links_dead_anchors": 0, "no_loss": null, "no_loss_warrants": null, "note": null, "over_budget": true, "repo": "replicator", "repo_commit": "812d0e5", "seams": null, "seams_acked": null, "skill_commit": "817963f6", "skill_version": "1.31", "tokens": 10072, "tokens_exact": true, "tokens_live": 184262, "top_section": "The enriched `blob_available` fields", "top_section_share": 19, "ts": "2026-11-23"} {"actions": ["baseline:pre-curation"], "budget": 10000, "bytes": 26546, "claims_dropped": null, "claims_warranted": null, "counts": null, "counts_acked": null, "delta_days": null, "delta_tokens": null, "docs_orphaned": 2, "docs_total": 24, "docs_unindexed": 17, "file": "docs/TESTING.md", "lines": 293, "links_dead": 0, "links_dead_anchors": 0, "no_loss": null, "no_loss_warrants": null, "note": null, "over_budget": true, "repo": "replicator", "repo_commit": "812d0e5", "seams": null, "seams_acked": null, "skill_commit": "817963f6", "skill_version": "1.31", "tokens": 10025, "tokens_exact": true, "tokens_live": 184262, "top_section": "Testing the write path", "top_section_share": 38, "ts": "2026-11-23"} {"actions": ["baseline:pre-curation"], "budget": 10000, "bytes": 25254, "claims_dropped": null, "claims_warranted": null, "counts": null, "counts_acked": null, "delta_days": null, "delta_tokens": null, "docs_orphaned": 2, "docs_total": 24, "docs_unindexed": 14, "file": "docs/INFRASTRUCTURE.md", "lines": 298, "links_dead": 0, "links_dead_anchors": 0, "no_loss": null, "no_loss_warrants": null, "note": null, "over_budget": true, "repo": "replicator", "repo_commit": "812d0e5", "seams": null, "seams_acked": null, "skill_commit": "817963f6", "skill_version": "1.31", "tokens": 10011, "tokens_exact": true, "tokens_live": 184262, "top_section": "The temp-blob buckets — live since 2026-08-20 (#7)", "top_section_share": 24, "ts": "2026-11-23"} -{"actions": ["demote:Dependabot proposes the action and Python bumps", "rename:provenance-heading"], "budget": 10000, "bytes": 23126, "claims_dropped": 0, "claims_warranted": 2, "counts": 16, "counts_acked": 0, "delta_days": 0, "delta_tokens": -1106, "docs_orphaned": 2, "docs_total": 24, "docs_unindexed": 13, "file": "docs/DEPLOYMENT.md", "lines": 304, "links_dead": 0, "links_dead_anchors": 0, "no_loss": "ok", "no_loss_warrants": 3, "note": null, "over_budget": false, "repo": "replicator", "repo_commit": "803f11e", "seams": 0, "seams_acked": 46, "skill_commit": "817963f6", "skill_version": "1.31", "tokens": 9116, "tokens_exact": true, "tokens_live": 184043, "top_section": "Server Lifecycle", "top_section_share": 46, "ts": "2026-11-23"} -{"actions": ["tighten:How the blob TTL clock runs"], "budget": 10000, "bytes": 26259, "claims_dropped": 0, "claims_warranted": 0, "counts": 19, "counts_acked": 0, "delta_days": 0, "delta_tokens": -137, "docs_orphaned": 2, "docs_total": 24, "docs_unindexed": 19, "file": "docs/contracts/content-fetch-outcome-reference.md", "lines": 366, "links_dead": 0, "links_dead_anchors": 0, "no_loss": "ok", "no_loss_warrants": 11, "note": null, "over_budget": false, "repo": "replicator", "repo_commit": "803f11e", "seams": 0, "seams_acked": 46, "skill_commit": "817963f6", "skill_version": "1.31", "tokens": 9935, "tokens_exact": true, "tokens_live": 184043, "top_section": "The enriched `blob_available` fields", "top_section_share": 20, "ts": "2026-11-23"} {"actions": ["tighten:Testing the bus"], "budget": 10000, "bytes": 26400, "claims_dropped": 0, "claims_warranted": 0, "counts": 20, "counts_acked": 0, "delta_days": 0, "delta_tokens": -41, "docs_orphaned": 2, "docs_total": 24, "docs_unindexed": 17, "file": "docs/TESTING.md", "lines": 293, "links_dead": 0, "links_dead_anchors": 0, "no_loss": "ok", "no_loss_warrants": 2, "note": null, "over_budget": false, "repo": "replicator", "repo_commit": "803f11e", "seams": 0, "seams_acked": 46, "skill_commit": "817963f6", "skill_version": "1.31", "tokens": 9984, "tokens_exact": true, "tokens_live": 184043, "top_section": "Testing the write path", "top_section_share": 38, "ts": "2026-11-23"} {"actions": ["tighten:The host's disk GC is the cohort's", "tighten:Grants the replicator user gained later"], "budget": 10000, "bytes": 25179, "claims_dropped": 0, "claims_warranted": 0, "counts": 8, "counts_acked": 0, "delta_days": 0, "delta_tokens": -30, "docs_orphaned": 2, "docs_total": 24, "docs_unindexed": 14, "file": "docs/INFRASTRUCTURE.md", "lines": 298, "links_dead": 0, "links_dead_anchors": 0, "no_loss": "ok", "no_loss_warrants": 4, "note": null, "over_budget": false, "repo": "replicator", "repo_commit": "803f11e", "seams": 0, "seams_acked": 46, "skill_commit": "817963f6", "skill_version": "1.31", "tokens": 9981, "tokens_exact": true, "tokens_live": 184043, "top_section": "The temp-blob buckets — live since 2026-08-20 (#7)", "top_section_share": 24, "ts": "2026-11-23"} +{"actions": ["tighten:How the blob TTL clock runs"], "budget": 10000, "bytes": 26309, "claims_dropped": 0, "claims_warranted": 0, "counts": 19, "counts_acked": 0, "delta_days": 0, "delta_tokens": -121, "docs_orphaned": 2, "docs_total": 24, "docs_unindexed": 19, "file": "docs/contracts/content-fetch-outcome-reference.md", "lines": 366, "links_dead": 0, "links_dead_anchors": 0, "no_loss": "ok", "no_loss_warrants": 11, "note": null, "over_budget": false, "repo": "replicator", "repo_commit": "da647ea", "seams": 0, "seams_acked": 46, "skill_commit": "817963f6", "skill_version": "1.31", "tokens": 9951, "tokens_exact": true, "tokens_live": 184139, "top_section": "The enriched `blob_available` fields", "top_section_share": 20, "ts": "2026-11-23"} +{"actions": ["demote:Dependabot proposes the action and Python bumps", "rename:provenance-heading"], "budget": 10000, "bytes": 23323, "claims_dropped": 0, "claims_warranted": 2, "counts": 16, "counts_acked": 0, "delta_days": 0, "delta_tokens": -1027, "docs_orphaned": 2, "docs_total": 24, "docs_unindexed": 13, "file": "docs/DEPLOYMENT.md", "lines": 305, "links_dead": 0, "links_dead_anchors": 0, "no_loss": "ok", "no_loss_warrants": 3, "note": null, "over_budget": false, "repo": "replicator", "repo_commit": "da647ea", "seams": 0, "seams_acked": 46, "skill_commit": "817963f6", "skill_version": "1.31", "tokens": 9195, "tokens_exact": true, "tokens_live": 184139, "top_section": "Server Lifecycle", "top_section_share": 46, "ts": "2026-11-23"}