From 07c8a815f72f60eab55657506a1f55f75db44791 Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Tue, 16 Jun 2026 10:39:15 +0200 Subject: [PATCH 1/8] feat(greffer): remote-update opt-in flag advertised in register payload (self-update v2) --- app/settings.py | 9 +++++++++ app/workers/register.py | 5 +++++ tests/test_workers_register.py | 15 +++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/app/settings.py b/app/settings.py index e2b2b466..16eab418 100644 --- a/app/settings.py +++ b/app/settings.py @@ -139,6 +139,15 @@ def _heartbeat_interval_in_range(cls, v): # bug Codex caught before merge (greffon/greffer#17 review). greffer_workers_enabled: bool = False + # Remote update opt-in (greffer self-update v2). Default OFF: a + # manager-triggered remote update is root-equivalent on the operator's host, + # so the authoritative switch is greffer-side and operator-sovereign. The + # value is advertised in the register payload so the manager knows whether to + # offer the button; the controller update route (a later v2 increment) is a + # clear no-op unless this is true. Carries the ``greffer_`` prefix to bind + # GREFFER_REMOTE_UPDATE_ENABLED (the prefix pitfall noted above). + greffer_remote_update_enabled: bool = False + # Self-health watchdog (greffer-observability epic, Feature #3). The # watchdog evaluates /readyz's FATAL conditions and, when one is sustained # past the grace window, exits the uvicorn process so ``restart: diff --git a/app/workers/register.py b/app/workers/register.py index acad0044..a42a95a3 100644 --- a/app/workers/register.py +++ b/app/workers/register.py @@ -318,6 +318,11 @@ def _post_register(settings: Settings, address: str, token: str) -> None: # without this field leaves Greffer.version null -> treated as below any # floor (fail-safe deny). "version": settings.greffer_version, + # Remote-update opt-in (greffer self-update v2), operator-sovereign and + # default off. Advertised every (re-)register so the manager knows + # whether to offer the remote "Update" button; the manager mirrors it + # for UI only and is never the authority. + "remote_update_enabled": settings.greffer_remote_update_enabled, } # Include greffer_mode in the register payload only when the operator # has set it explicitly. The manager's register endpoint accepts an diff --git a/tests/test_workers_register.py b/tests/test_workers_register.py index 6541788c..b3b0d003 100644 --- a/tests/test_workers_register.py +++ b/tests/test_workers_register.py @@ -49,6 +49,9 @@ def test_post_register_passes_correct_payload(settings: Settings) -> None: # version is always sent so the manager can stamp Greffer.version and # enforce the per-greffon min_greffer_version compatibility gate. assert kwargs["json"]["version"] == settings.greffer_version + # remote-update opt-in is advertised every register (default off) so the + # manager knows whether to offer the v2 remote "Update" button. + assert kwargs["json"]["remote_update_enabled"] is False assert kwargs["verify"] == settings.greffer_ssl_verify # mode is omitted when settings.greffer_mode is unset — preserves the # pre-tunnel-feature behaviour for proxy greffers (manager treats a @@ -56,6 +59,18 @@ def test_post_register_passes_correct_payload(settings: Settings) -> None: assert "mode" not in kwargs["json"] +def test_post_register_advertises_remote_update_opt_in(settings: Settings) -> None: + """The operator-sovereign GREFFER_REMOTE_UPDATE_ENABLED flag is advertised in + the register payload (default off) so the manager can mirror it for the UI; + when the operator enables it, the True value flows into the payload.""" + settings.greffer_remote_update_enabled = True # type: ignore[misc] + with patch("app.workers.register.requests") as mock_requests: + mock_requests.post.return_value.status_code = 200 + _post_register(settings, "10.0.0.1", "tok") + kwargs = mock_requests.post.call_args.kwargs + assert kwargs["json"]["remote_update_enabled"] is True + + def test_post_register_version_defaults_to_app_version(settings: Settings) -> None: """With GREFFER_VERSION unset, the register payload carries the worker's own ``app.__version__`` — the single source the manager stamps onto From b5784c898517ecb1d7fe79b2e544759d8e40f411 Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Tue, 16 Jun 2026 11:03:46 +0200 Subject: [PATCH 2/8] feat(greffer): v2 updater verification primitives (cosign provenance + anti-replay floor) --- cli/greffer_cli/updater/__init__.py | 13 ++ cli/greffer_cli/updater/floor.py | 140 +++++++++++++++++ cli/greffer_cli/updater/provenance.py | 74 +++++++++ cli/tests/test_updater_provenance_floor.py | 175 +++++++++++++++++++++ 4 files changed, 402 insertions(+) create mode 100644 cli/greffer_cli/updater/__init__.py create mode 100644 cli/greffer_cli/updater/floor.py create mode 100644 cli/greffer_cli/updater/provenance.py create mode 100644 cli/tests/test_updater_provenance_floor.py diff --git a/cli/greffer_cli/updater/__init__.py b/cli/greffer_cli/updater/__init__.py new file mode 100644 index 00000000..57665637 --- /dev/null +++ b/cli/greffer_cli/updater/__init__.py @@ -0,0 +1,13 @@ +"""Greffer self-update v2: the detached updater engine. + +This package is the verification + recreate logic that the signed +``greffon/greffer-updater`` image runs when the manager triggers a remote +update. It enforces the trust model in +``docs/features/greffer-self-update/v2-image-provenance-and-trust-model.md`` +(cosign verify + repo-binding + digest pin + the anti-replay ``min_supported`` +floor) and then reuses the v1 ``greffer_cli`` compose engine to recreate the +node, health-gate on ``/readyz``, and roll back on failure. + +Every check fails closed: any verification or floor failure aborts BEFORE the +node is recreated, leaving it on its current, already-trusted image. +""" diff --git a/cli/greffer_cli/updater/floor.py b/cli/greffer_cli/updater/floor.py new file mode 100644 index 00000000..18fb524e --- /dev/null +++ b/cli/greffer_cli/updater/floor.py @@ -0,0 +1,140 @@ +"""The v2 ``min_supported`` downgrade floor, with anti-replay. + +A cosign-signed manifest proves authenticity, not freshness: a replayed older +manifest (or a stale-floored canary channel) could otherwise lower the floor +and re-admit a known-vulnerable but authentically-signed release. The EFFECTIVE +floor is ``max(baked build-time baseline, signed manifest min_supported, +persisted /data high-water ratchet)`` and only ever ratchets up. See the +trust-model doc, resolution (d) "Freshness". + +Fail-closed: an unreachable / unverifiable / malformed manifest raises +``FloorError`` and the update aborts; the floor is never silently lowered. +""" + +from __future__ import annotations + +import json +import tempfile +import urllib.error +from pathlib import Path + +from .. import compose, update + + +class FloorError(Exception): + """The floor could not be established. Fail-closed: abort the update.""" + + +def parse_version(v: object) -> tuple[int, ...] | None: + """'0.3.5' -> (0, 3, 5); None if not clean dotted-numeric.""" + if not isinstance(v, str): + return None + try: + return tuple(int(p) for p in v.split(".")) + except (ValueError, AttributeError): + return None + + +def version_ge(a: object, b: object) -> bool: + """a >= b, zero-padded. False if either is unparseable (fail-closed).""" + pa, pb = parse_version(a), parse_version(b) + if pa is None or pb is None: + return False + n = max(len(pa), len(pb)) + return pa + (0,) * (n - len(pa)) >= pb + (0,) * (n - len(pb)) + + +def higher(a: str | None, b: str | None) -> str | None: + """The greater of two version strings; ignores an unparseable side.""" + if parse_version(a) is None: + return b + if parse_version(b) is None: + return a + return a if version_ge(a, b) else b + + +def _fetch_bytes(url: str, *, timeout: float = 10.0) -> bytes: + """Bounded HTTPS-only fetch via the v1 hardened opener (refuses an + https->http redirect downgrade). Raises FloorError fail-closed on failure.""" + if not url.startswith("https://"): + raise FloorError(f"refusing non-https fetch: {url}") + try: + with update._MANIFEST_OPENER.open(url, timeout=timeout) as r: + raw = r.read(update._MAX_MANIFEST_BYTES + 1) + except (urllib.error.URLError, OSError, ValueError) as exc: + raise FloorError(f"fetch failed ({url}): {exc}") from exc + if len(raw) > update._MAX_MANIFEST_BYTES: + raise FloorError(f"manifest oversized ({url})") + return raw + + +def verify_blob(manifest_bytes: bytes, sig_bytes: bytes, *, cosign_pub: str) -> bool: + """cosign verify-blob the manifest against its detached signature.""" + with tempfile.TemporaryDirectory() as d: + mpath = Path(d) / "manifest.json" + spath = Path(d) / "manifest.sig" + mpath.write_bytes(manifest_bytes) + spath.write_bytes(sig_bytes) + res = compose._run( + ["cosign", "verify-blob", "--key", cosign_pub, + "--signature", str(spath), str(mpath)], + timeout=120, + ) + return res.ok + + +def signed_min_supported(manifest_url: str, *, cosign_pub: str) -> str | None: + """Fetch the manifest + its ``.sig``, verify the signature, and return + ``min_supported`` (None if the manifest carries none). Raises FloorError + fail-closed on any fetch / signature / parse failure.""" + manifest_bytes = _fetch_bytes(manifest_url) + sig_bytes = _fetch_bytes(manifest_url + ".sig") + if not verify_blob(manifest_bytes, sig_bytes, cosign_pub=cosign_pub): + raise FloorError("manifest signature did not verify") + try: + data = json.loads(manifest_bytes.decode("utf-8")) + except (ValueError, UnicodeDecodeError) as exc: + raise FloorError(f"manifest is not valid JSON: {exc}") from exc + if not isinstance(data, dict): + raise FloorError("manifest is not a JSON object") + ms = data.get("min_supported") + return ms if isinstance(ms, str) else None + + +def read_ratchet(path: Path) -> str | None: + """The persisted high-water floor on /data, or None if absent/garbage.""" + try: + v = path.read_text(encoding="utf-8").strip() + except OSError: + return None + return v if parse_version(v) is not None else None + + +def write_ratchet(path: Path, version: str) -> None: + """Persist the high-water floor (best-effort; a failed write still leaves + the in-process floor enforced for this run).""" + if parse_version(version) is None: + return + try: + path.write_text(version + "\n", encoding="utf-8") + except OSError: + pass + + +def effective_floor(manifest_url: str, *, baked_baseline: str | None, + ratchet_path: Path, cosign_pub: str) -> str: + """Compute and persist the effective floor = + ``max(baked_baseline, signed manifest min_supported, persisted ratchet)``. + + Raises FloorError fail-closed if the signed manifest can't be established or + no usable floor exists. Ratchets the high-water mark up, never down.""" + manifest_floor = signed_min_supported(manifest_url, cosign_pub=cosign_pub) + prior = read_ratchet(ratchet_path) + floor: str | None = None + for candidate in (baked_baseline, manifest_floor, prior): + floor = higher(floor, candidate) + if floor is None or parse_version(floor) is None: + raise FloorError( + "no usable floor (no baked baseline, manifest min_supported, or ratchet)") + write_ratchet(ratchet_path, floor) + return floor diff --git a/cli/greffer_cli/updater/provenance.py b/cli/greffer_cli/updater/provenance.py new file mode 100644 index 00000000..db57500f --- /dev/null +++ b/cli/greffer_cli/updater/provenance.py @@ -0,0 +1,74 @@ +"""Image-provenance verification (cosign) for the v2 updater. + +Before recreate, every ``greffon/*`` image is proven genuine: resolved to a +digest, cosign-verified against the baked public key AND bound to its expected +repo, then pinned by that digest. Acting on the digest (not the mutable tag) +closes the tag-moved TOCTOU; the repo binding closes the same-key cross-image +substitution (key-only cosign proves a Greffon key signed *some* digest, not +which repo). Fail-closed: any error returns None / False. + +cosign and docker are invoked via ``greffer_cli.compose._run`` so tests can +monkeypatch the subprocess layer without a real registry. +""" + +from __future__ import annotations + +from .. import compose + +# Baked into the greffer-updater image at build time (the publish CI commits +# cosign.pub into the image); the updater holds what it needs to verify offline. +DEFAULT_COSIGN_PUB = "/etc/greffer/cosign.pub" + +# The OCI label the publish CI stamps with each image's build version, so the +# floor check reads the actual version from the verified image, not the tag. +VERSION_LABEL = "org.opencontainers.image.version" + + +def resolve_digest(ref: str) -> str | None: + """Resolve ``greffon/:`` to its content digest (``sha256:<64hex>``), + or None. Uses ``docker buildx imagetools inspect`` so it needs no pull.""" + res = compose._run( + ["docker", "buildx", "imagetools", "inspect", ref, + "--format", "{{.Manifest.Digest}}"], + timeout=60, + ) + if not res.ok: + return None + digest = res.stdout.strip() + if not digest.startswith("sha256:"): + return None + hexpart = digest[len("sha256:"):] + return digest if len(hexpart) == 64 and all( + c in "0123456789abcdef" for c in hexpart + ) else None + + +def cosign_verify(repo: str, digest: str, *, pubkey: str = DEFAULT_COSIGN_PUB) -> bool: + """True iff ``greffon/@`` carries a valid Greffon signature + **bound to that repo**. The ``repo`` annotation (set by the publish CI) is + required so a signature lifted from another Greffon image (an old below-floor + nginx, or the updater) cannot pass in this slot. Fail-closed on any error.""" + ref = f"{repo}@{digest}" + res = compose._run( + ["cosign", "verify", "--key", pubkey, + "--annotation", f"repo={repo}", ref], + timeout=120, + ) + return res.ok + + +def image_version(ref_or_digest: str, *, label: str = VERSION_LABEL) -> str | None: + """Read the build version from a (verified, locally-present) image's OCI + ``org.opencontainers.image.version`` label via ``docker inspect``; None if + absent. Read from the image, never the tag string, so a non-semver tag + (``latest``) cannot spoof the version the floor compares.""" + res = compose._run( + ["docker", "inspect", "--format", + f'{{{{ index .Config.Labels "{label}" }}}}', ref_or_digest], + timeout=30, + ) + if not res.ok: + return None + value = res.stdout.strip() + # docker prints "" for an absent label. + return value if value and value != "" else None diff --git a/cli/tests/test_updater_provenance_floor.py b/cli/tests/test_updater_provenance_floor.py new file mode 100644 index 00000000..5e4865e3 --- /dev/null +++ b/cli/tests/test_updater_provenance_floor.py @@ -0,0 +1,175 @@ +"""Tests for the v2 updater verification primitives (provenance + floor). + +The cosign/docker subprocess layer (``compose._run``) and the hardened manifest +HTTP opener are monkeypatched, so no real registry, cosign binary, or network. +""" + +from __future__ import annotations + +import json + +import pytest + +from greffer_cli import compose, update +from greffer_cli.updater import floor, provenance + + +def _ok(out: str = "") -> compose.CommandResult: + return compose.CommandResult(0, out, "") + + +def _fail() -> compose.CommandResult: + return compose.CommandResult(1, "", "boom") + + +# --- provenance: digest resolution ----------------------------------- + +def test_resolve_digest_ok(monkeypatch): + monkeypatch.setattr(compose, "_run", lambda a, **k: _ok("sha256:" + "a" * 64 + "\n")) + assert provenance.resolve_digest("greffon/greffer:0.3.5") == "sha256:" + "a" * 64 + + +def test_resolve_digest_rejects_malformed(monkeypatch): + for bad in ("", "sha256:zz", "deadbeef", "sha256:" + "a" * 63, "sha256:" + "g" * 64): + monkeypatch.setattr(compose, "_run", lambda a, _b=bad, **k: _ok(_b)) + assert provenance.resolve_digest("greffon/greffer:0.3.5") is None + monkeypatch.setattr(compose, "_run", lambda a, **k: _fail()) + assert provenance.resolve_digest("greffon/greffer:0.3.5") is None + + +# --- provenance: cosign verify + repo binding ------------------------ + +def test_cosign_verify_binds_repo_annotation(monkeypatch): + seen = {} + monkeypatch.setattr(compose, "_run", lambda a, **k: (seen.update(args=a), _ok())[1]) + digest = "sha256:" + "b" * 64 + assert provenance.cosign_verify("greffon/greffer-nginx", digest, pubkey="/k") is True + a = seen["args"] + assert a[:2] == ["cosign", "verify"] + assert a[a.index("--key") + 1] == "/k" + # the repo binding is what stops a same-key cross-image signature swap + assert a[a.index("--annotation") + 1] == "repo=greffon/greffer-nginx" + assert a[-1] == f"greffon/greffer-nginx@{digest}" + + +def test_cosign_verify_fail_closed(monkeypatch): + monkeypatch.setattr(compose, "_run", lambda a, **k: _fail()) + assert provenance.cosign_verify("greffon/greffer", "sha256:" + "c" * 64) is False + + +# --- provenance: version label --------------------------------------- + +def test_image_version_reads_label(monkeypatch): + monkeypatch.setattr(compose, "_run", lambda a, **k: _ok("0.3.5\n")) + assert provenance.image_version("greffon/greffer@sha256:x") == "0.3.5" + + +def test_image_version_absent_or_error(monkeypatch): + monkeypatch.setattr(compose, "_run", lambda a, **k: _ok("\n")) + assert provenance.image_version("x") is None + monkeypatch.setattr(compose, "_run", lambda a, **k: _ok(" \n")) + assert provenance.image_version("x") is None + monkeypatch.setattr(compose, "_run", lambda a, **k: _fail()) + assert provenance.image_version("x") is None + + +# --- floor: semver ---------------------------------------------------- + +def test_parse_and_compare(): + assert floor.parse_version("0.3.5") == (0, 3, 5) + assert floor.parse_version("latest") is None + assert floor.version_ge("0.3.5", "0.3.4") is True + assert floor.version_ge("0.3", "0.3.0") is True # zero-pad + assert floor.version_ge("0.3.4", "0.3.5") is False + assert floor.version_ge("latest", "0.3.0") is False # unparseable -> fail-closed + assert floor.higher("0.3.4", "0.3.9") == "0.3.9" + assert floor.higher(None, "0.3.1") == "0.3.1" + assert floor.higher("0.3.1", None) == "0.3.1" + + +# --- floor: signed manifest fetch + verify --------------------------- + +class _Resp: + def __init__(self, body: bytes) -> None: + self._b = body + + def read(self, n: int = -1) -> bytes: + return self._b if n < 0 else self._b[:n] + + def __enter__(self) -> "_Resp": + return self + + def __exit__(self, *a: object) -> bool: + return False + + +def _patch_opener(monkeypatch, bodies: dict) -> None: + def opn(url, timeout=None): + return _Resp(bodies[".sig" if url.endswith(".sig") else ""]) + monkeypatch.setattr(update._MANIFEST_OPENER, "open", opn) + + +def test_signed_min_supported_happy(monkeypatch): + manifest = json.dumps({"latest": "0.3.5", "min_supported": "0.3.0"}).encode() + _patch_opener(monkeypatch, {"": manifest, ".sig": b"SIG"}) + monkeypatch.setattr(compose, "_run", lambda a, **k: _ok()) # cosign verify-blob ok + assert floor.signed_min_supported("https://x/m.json", cosign_pub="/k") == "0.3.0" + + +def test_signed_min_supported_sig_fail_closed(monkeypatch): + _patch_opener(monkeypatch, {"": b"{}", ".sig": b"SIG"}) + monkeypatch.setattr(compose, "_run", lambda a, **k: _fail()) # cosign rejects + with pytest.raises(floor.FloorError): + floor.signed_min_supported("https://x/m.json", cosign_pub="/k") + + +def test_signed_min_supported_refuses_non_https(): + with pytest.raises(floor.FloorError): + floor.signed_min_supported("http://x/m.json", cosign_pub="/k") + + +def test_signed_min_supported_none_when_absent(monkeypatch): + _patch_opener(monkeypatch, {"": json.dumps({"latest": "0.3.5"}).encode(), ".sig": b"S"}) + monkeypatch.setattr(compose, "_run", lambda a, **k: _ok()) + assert floor.signed_min_supported("https://x/m.json", cosign_pub="/k") is None + + +# --- floor: ratchet + effective_floor -------------------------------- + +def test_ratchet_roundtrip(tmp_path): + p = tmp_path / "floor" + assert floor.read_ratchet(p) is None + floor.write_ratchet(p, "0.3.0") + assert floor.read_ratchet(p) == "0.3.0" + floor.write_ratchet(p, "garbage") # non-version write ignored + assert floor.read_ratchet(p) == "0.3.0" + + +def test_effective_floor_takes_max_and_ratchets(monkeypatch, tmp_path): + _patch_opener(monkeypatch, {"": json.dumps({"min_supported": "0.3.0"}).encode(), ".sig": b"S"}) + monkeypatch.setattr(compose, "_run", lambda a, **k: _ok()) + p = tmp_path / "floor" + p.write_text("0.3.5\n") # ratchet already higher than the manifest + f = floor.effective_floor("https://x/m.json", baked_baseline="0.2.0", + ratchet_path=p, cosign_pub="/k") + assert f == "0.3.5" # max(0.2.0, 0.3.0, 0.3.5) + assert floor.read_ratchet(p) == "0.3.5" # ratchet held + + +def test_effective_floor_replayed_manifest_cannot_lower(monkeypatch, tmp_path): + # a replayed OLD manifest (min_supported 0.3.0) cannot drop a node whose + # baked baseline already saw 0.3.5 (the anti-replay guarantee) + _patch_opener(monkeypatch, {"": json.dumps({"min_supported": "0.3.0"}).encode(), ".sig": b"S"}) + monkeypatch.setattr(compose, "_run", lambda a, **k: _ok()) + p = tmp_path / "floor" + f = floor.effective_floor("https://x/m.json", baked_baseline="0.3.5", + ratchet_path=p, cosign_pub="/k") + assert f == "0.3.5" + + +def test_effective_floor_fail_closed_on_bad_manifest(monkeypatch, tmp_path): + _patch_opener(monkeypatch, {"": b"x", ".sig": b"S"}) + monkeypatch.setattr(compose, "_run", lambda a, **k: _fail()) # signature fails + with pytest.raises(floor.FloorError): + floor.effective_floor("https://x/m.json", baked_baseline="0.3.0", + ratchet_path=tmp_path / "f", cosign_pub="/k") From 6ebebf4e3050fc1564f640eb4a8053cb41eb268f Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Tue, 16 Jun 2026 11:07:07 +0200 Subject: [PATCH 3/8] feat(greffer): v2 updater orchestration (verify -> pin digests -> recreate -> rollback) --- cli/greffer_cli/updater/engine.py | 136 +++++++++++++++++++++++++++++ cli/tests/test_updater_engine.py | 139 ++++++++++++++++++++++++++++++ 2 files changed, 275 insertions(+) create mode 100644 cli/greffer_cli/updater/engine.py create mode 100644 cli/tests/test_updater_engine.py diff --git a/cli/greffer_cli/updater/engine.py b/cli/greffer_cli/updater/engine.py new file mode 100644 index 00000000..a62225d3 --- /dev/null +++ b/cli/greffer_cli/updater/engine.py @@ -0,0 +1,136 @@ +"""The v2 updater orchestration: verify -> pin -> recreate. + +Runs inside the signed ``greffon/greffer-updater`` container against the host's +``/work/docker-compose.yml``. Adds the trust-model verification (effective +``min_supported`` floor + per-image cosign verify / repo-binding / digest-pin / +version cohesion) BEFORE any recreate, then reuses the v1 ``greffer_cli`` engine +for recreate -> ``/readyz`` health-gate -> rollback. Fail-closed at every step: +any verification or floor failure aborts before the node is recreated. + +Concurrency: the caller (the updater entrypoint) holds the +``/data/.greffer-update.lock`` across this call so the recreated controller and a +host ``greffer update`` are mutually exclusive (HLD "Concurrency"). The lock is +out of this module's scope so the verify/recreate logic stays unit-testable. +""" + +from __future__ import annotations + +import logging +import time +from pathlib import Path +from typing import Callable + +from .. import compose, update +from . import floor, provenance + +logger = logging.getLogger("greffer-updater") + +# Exit codes mirror the v1 engine so a wrapper reads them the same way. +EXIT_OK = update.EXIT_OK +EXIT_FAILED_ROLLED_BACK = update.EXIT_FAILED_ROLLED_BACK +EXIT_FAILED_ROLLBACK_FAILED = update.EXIT_FAILED_ROLLBACK_FAILED +EXIT_REFUSED = update.EXIT_PREFLIGHT_REFUSED + + +class VerifyError(Exception): + """A provenance check failed. Fail-closed: refuse before recreate.""" + + +def _compose_repos(compose_file: Path) -> dict[str, str]: + """The ``greffon/*`` repos in the rendered compose mapped to their current + full refs (for rollback). Derived from the file so it tracks whatever the + template renders (the set-closure invariant).""" + text = compose_file.read_text(encoding="utf-8") + _, refs = compose._rewrite_image_lines(text, lambda repo, old: None) + return refs + + +def verify_and_pin( + compose_file: Path, *, target_tag: str, manifest_url: str, + cosign_pub: str, baked_baseline: str | None, ratchet_path: Path, +) -> dict[str, str]: + """Run the full trust model and return the verified ``repo -> repo@digest`` + refs to pin. Raises ``VerifyError`` / ``floor.FloorError`` fail-closed on any + failure, leaving the compose file untouched (no recreate).""" + if not compose.is_valid_image_tag(target_tag): + raise VerifyError(f"invalid target tag: {target_tag!r}") + + # Effective floor first (max of baked baseline, signed manifest, ratchet); + # FloorError aborts before any image work. + floor_v = floor.effective_floor( + manifest_url, baked_baseline=baked_baseline, + ratchet_path=ratchet_path, cosign_pub=cosign_pub, + ) + + repos = _compose_repos(compose_file) + if not repos: + raise VerifyError("no greffon/* images in the compose file") + + verified: dict[str, str] = {} + versions: set[str] = set() + for repo in repos: + ref = f"{repo}:{target_tag}" + digest = provenance.resolve_digest(ref) + if not digest: + raise VerifyError(f"cannot resolve digest for {ref}") + if not provenance.cosign_verify(repo, digest, pubkey=cosign_pub): + raise VerifyError(f"signature/repo-binding failed for {repo}@{digest}") + by_digest = f"{repo}@{digest}" + # Pull by the verified digest so the OCI version label is locally + # readable; pulling bytes is safe, recreating them is what the floor gates. + if not compose._run(["docker", "pull", by_digest], timeout=600).ok: + raise VerifyError(f"pull failed for {by_digest}") + version = provenance.image_version(by_digest) + if not floor.version_ge(version, floor_v): + raise VerifyError( + f"{repo} version {version!r} is below the floor {floor_v}") + versions.add(version) # type: ignore[arg-type] + verified[repo] = by_digest + + # Cohesion: every image must be the SAME version, so a moved tag can't pair + # an at-floor greffer with a below-floor, network-exposed nginx. + if len(versions) != 1: + raise VerifyError(f"version cohesion failed across images: {sorted(versions)}") + return verified + + +def run_remote_update( + compose_file: Path, *, target_tag: str, manifest_url: str, + cosign_pub: str, baked_baseline: str | None, ratchet_path: Path, + greffer_id: str | None, mode: str, timeout: float = 600.0, + sleep: Callable[[float], None] = time.sleep, +) -> int: + """Verify provenance + floor, pin the verified digests, recreate, + health-gate on ``/readyz``, and roll back on failure. Returns an ``EXIT_*`` + code. Nothing is recreated unless verification fully passes.""" + old_refs = _compose_repos(compose_file) + try: + verified = verify_and_pin( + compose_file, target_tag=target_tag, manifest_url=manifest_url, + cosign_pub=cosign_pub, baked_baseline=baked_baseline, + ratchet_path=ratchet_path, + ) + except (VerifyError, floor.FloorError) as exc: + logger.error("remote update refused, no recreate: %s", exc) + return EXIT_REFUSED + + profile = update.profile_for_mode(mode) + services = update.active_services(mode) + compose.set_image_refs(compose_file, verified) # pin the verified digests + up = compose.compose_up(compose_file, profile=profile) + if not up.ok: + return update._rollback( + compose_file, profile=profile, services=services, + old_refs=old_refs, greffer_id=greffer_id, timeout=timeout, sleep=sleep) + + outcome = update.health_gate( + compose_file, greffer_id=greffer_id, target=target_tag, + services=services, profile=profile, timeout=timeout, sleep=sleep) + if outcome == update.GATE_READY: + logger.info("remote update applied: %s", target_tag) + return EXIT_OK + + logger.error("health gate failed (%s), rolling back", outcome) + return update._rollback( + compose_file, profile=profile, services=services, + old_refs=old_refs, greffer_id=greffer_id, timeout=timeout, sleep=sleep) diff --git a/cli/tests/test_updater_engine.py b/cli/tests/test_updater_engine.py new file mode 100644 index 00000000..25fe1bae --- /dev/null +++ b/cli/tests/test_updater_engine.py @@ -0,0 +1,139 @@ +"""Tests for the v2 updater orchestration (engine.run_remote_update). + +The verification primitives (provenance/floor) and the compose/recreate layer +are monkeypatched, so no real cosign, docker, or network. Focus: the fail-closed +refusal paths (nothing recreated) and the verify -> pin -> recreate -> rollback +flow. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from greffer_cli import compose, update +from greffer_cli.updater import engine, floor, provenance + +_COMPOSE = """\ +services: + greffer: + image: greffon/greffer:0.3.5 + nginx: + image: greffon/greffer-nginx:0.3.5 + tunnel-sidecar: + image: greffon/tunnel-sidecar:0.3.5 +""" + +_ALL_OK = { + "greffon/greffer": "0.3.5", + "greffon/greffer-nginx": "0.3.5", + "greffon/tunnel-sidecar": "0.3.5", +} + + +def _ok(out: str = "") -> compose.CommandResult: + return compose.CommandResult(0, out, "") + + +@pytest.fixture +def cf(tmp_path: Path) -> Path: + p = tmp_path / "docker-compose.yml" + p.write_text(_COMPOSE, encoding="utf-8") + return p + + +def _patch_verify(monkeypatch, *, floor_v="0.3.0", versions=None, + digest_ok=True, cosign_ok=True, pull_ok=True): + versions = versions or _ALL_OK + monkeypatch.setattr(floor, "effective_floor", lambda *a, **k: floor_v) + monkeypatch.setattr(provenance, "resolve_digest", + lambda ref: ("sha256:" + "a" * 64) if digest_ok else None) + monkeypatch.setattr(provenance, "cosign_verify", lambda repo, d, **k: cosign_ok) + monkeypatch.setattr(provenance, "image_version", + lambda by_digest, **k: versions[by_digest.split("@")[0]]) + monkeypatch.setattr(compose, "_run", + lambda a, **k: _ok() if pull_ok else compose.CommandResult(1, "", "")) + + +def _run(cf, monkeypatch, **kw): + return engine.run_remote_update( + cf, target_tag="0.3.6", manifest_url="https://x/m.json", + cosign_pub="/k", baked_baseline="0.3.0", ratchet_path=Path("/tmp/r"), + greffer_id="g1", mode="tunnel", sleep=lambda _s: None, **kw) + + +# --- verify_and_pin ------------------------------------------------- + +def test_verify_and_pin_happy(cf, monkeypatch): + _patch_verify(monkeypatch) + verified = engine.verify_and_pin( + cf, target_tag="0.3.6", manifest_url="https://x/m.json", + cosign_pub="/k", baked_baseline="0.3.0", ratchet_path=Path("/tmp/r")) + assert set(verified) == set(_ALL_OK) + for repo, ref in verified.items(): + assert ref == f"{repo}@sha256:{'a' * 64}" + + +def test_verify_invalid_tag(cf, monkeypatch): + _patch_verify(monkeypatch) + with pytest.raises(engine.VerifyError): + engine.verify_and_pin( + cf, target_tag="bad:tag", manifest_url="https://x/m.json", + cosign_pub="/k", baked_baseline="0.3.0", ratchet_path=Path("/tmp/r")) + + +# --- run_remote_update refusal paths (no recreate) ------------------ + +def test_floor_error_refuses_without_recreate(cf, monkeypatch): + _patch_verify(monkeypatch) + monkeypatch.setattr(floor, "effective_floor", + lambda *a, **k: (_ for _ in ()).throw(floor.FloorError("unreachable"))) + pinned = {"called": False} + monkeypatch.setattr(compose, "set_image_refs", + lambda *a, **k: pinned.__setitem__("called", True)) + assert _run(cf, monkeypatch) == engine.EXIT_REFUSED + assert pinned["called"] is False # nothing recreated + + +def test_cosign_failure_refuses(cf, monkeypatch): + _patch_verify(monkeypatch, cosign_ok=False) + monkeypatch.setattr(compose, "set_image_refs", lambda *a, **k: pytest.fail("recreated")) + assert _run(cf, monkeypatch) == engine.EXIT_REFUSED + + +def test_below_floor_refuses(cf, monkeypatch): + bad = dict(_ALL_OK, **{"greffon/greffer-nginx": "0.2.9"}) # nginx below floor + _patch_verify(monkeypatch, versions=bad) + monkeypatch.setattr(compose, "set_image_refs", lambda *a, **k: pytest.fail("recreated")) + assert _run(cf, monkeypatch) == engine.EXIT_REFUSED + + +def test_cohesion_mismatch_refuses(cf, monkeypatch): + mixed = dict(_ALL_OK, **{"greffon/greffer-nginx": "0.3.4"}) # different version + _patch_verify(monkeypatch, versions=mixed) + monkeypatch.setattr(compose, "set_image_refs", lambda *a, **k: pytest.fail("recreated")) + assert _run(cf, monkeypatch) == engine.EXIT_REFUSED + + +# --- run_remote_update recreate + rollback -------------------------- + +def test_happy_pins_digests_and_recreates(cf, monkeypatch): + _patch_verify(monkeypatch) + seen = {} + monkeypatch.setattr(compose, "set_image_refs", lambda f, refs: seen.update(refs=refs)) + monkeypatch.setattr(compose, "compose_up", lambda f, **k: _ok()) + monkeypatch.setattr(update, "health_gate", lambda *a, **k: update.GATE_READY) + assert _run(cf, monkeypatch) == engine.EXIT_OK + # the compose was pinned to the verified digests, not the tag + assert all(v == f"{r}@sha256:{'a' * 64}" for r, v in seen["refs"].items()) + assert set(seen["refs"]) == set(_ALL_OK) + + +def test_gate_failure_rolls_back(cf, monkeypatch): + _patch_verify(monkeypatch) + monkeypatch.setattr(compose, "set_image_refs", lambda f, refs: None) + monkeypatch.setattr(compose, "compose_up", lambda f, **k: _ok()) + monkeypatch.setattr(update, "health_gate", lambda *a, **k: update.GATE_FATAL) + monkeypatch.setattr(update, "_rollback", lambda *a, **k: update.EXIT_FAILED_ROLLED_BACK) + assert _run(cf, monkeypatch) == engine.EXIT_FAILED_ROLLED_BACK From c582c1b2bff940f49f5c3cfdb4f8683772336d61 Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Tue, 16 Jun 2026 11:12:29 +0200 Subject: [PATCH 4/8] feat(greffer-cli): updater container entrypoint (v2 remote update) python -m greffer_cli.updater reads the rest of its config from the env the greffer sets, takes the /data update lock (mutually exclusive with a host 'greffer update'), runs the verify -> pin -> recreate engine, and exits with its code. main() injects run/lock for tests; missing env, bad args, or a held lock all refuse fail-closed. Co-Authored-By: Claude Opus 4.8 --- cli/greffer_cli/updater/__main__.py | 111 +++++++++++++++++++++++++++ cli/tests/test_updater_main.py | 113 ++++++++++++++++++++++++++++ 2 files changed, 224 insertions(+) create mode 100644 cli/greffer_cli/updater/__main__.py create mode 100644 cli/tests/test_updater_main.py diff --git a/cli/greffer_cli/updater/__main__.py b/cli/greffer_cli/updater/__main__.py new file mode 100644 index 00000000..d3f1b8f6 --- /dev/null +++ b/cli/greffer_cli/updater/__main__.py @@ -0,0 +1,111 @@ +"""Entrypoint for the signed ``greffon/greffer-updater`` image. + +``python -m greffer_cli.updater `` (the rest of the config comes +from the environment the greffer sets when it spawns the updater). It takes the +``/data`` update lock so a remote update and a host ``greffer update`` are +mutually exclusive (HLD "Concurrency"), runs the v2 verify -> pin -> recreate +engine, and exits with its code. The lock lives on the ``/data`` volume because +that is the only filesystem the updater and the recreated greffer share. +""" + +from __future__ import annotations + +import os +import sys +from pathlib import Path + +from . import engine + +# Paths inside the updater container: the greffer mounts the host config dir at +# /work, the greffer's /data volume at /data, and bakes cosign.pub + the +# min_supported baseline into /etc/greffer at build time. +DEFAULT_COMPOSE = Path("/work/docker-compose.yml") +DEFAULT_RATCHET = Path("/data/.greffer-update-floor") +DEFAULT_LOCK = Path("/data/.greffer-update.lock") +DEFAULT_COSIGN_PUB = "/etc/greffer/cosign.pub" +DEFAULT_BASELINE_FILE = Path("/etc/greffer/min_supported_baseline") + +# Sentinel: no fcntl (non-POSIX); proceed without a host lock. +_NO_LOCK = object() + + +def _baked_baseline(env: dict) -> str | None: + """The build-time min_supported baseline, from an env override or the file + baked into the image. None if neither is present (the floor then rests on + the signed manifest + ratchet).""" + v = env.get("GREFFER_MIN_SUPPORTED_BASELINE") + if v and v.strip(): + return v.strip() + try: + return DEFAULT_BASELINE_FILE.read_text(encoding="utf-8").strip() or None + except OSError: + return None + + +def _config_from_env(target_tag: str, env: dict) -> dict: + return { + "compose_file": Path(env.get("GREFFER_UPDATER_COMPOSE", str(DEFAULT_COMPOSE))), + "target_tag": target_tag, + "manifest_url": env["GREFFER_VERSION_MANIFEST_URL"], + "cosign_pub": env.get("GREFFER_COSIGN_PUB", DEFAULT_COSIGN_PUB), + "baked_baseline": _baked_baseline(env), + "ratchet_path": Path(env.get("GREFFER_UPDATER_RATCHET", str(DEFAULT_RATCHET))), + "greffer_id": env.get("GREFFER_ID"), + "mode": env.get("GREFFER_MODE") or "proxy", + "timeout": float(env.get("GREFFER_UPDATER_TIMEOUT", "600")), + } + + +def acquire_lock(lock_path: Path = DEFAULT_LOCK): + """Exclusive flock on the /data update lock. Returns a handle to release, or + None if another actor already holds it (the caller refuses), or the + ``_NO_LOCK`` sentinel on a platform without fcntl.""" + try: + import fcntl + except ImportError: + return _NO_LOCK + fh = open(lock_path, "w", encoding="utf-8") + try: + fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + fh.close() + return None + return fh + + +def release_lock(handle) -> None: + if handle is None or handle is _NO_LOCK: + return + try: + handle.close() # closing the fd releases the flock + except OSError: + pass + + +def main(argv=None, *, env=None, run=engine.run_remote_update, + lock_acquire=acquire_lock, lock_release=release_lock) -> int: + """Resolve config, take the /data lock, run the engine. ``run`` / + ``lock_acquire`` are injectable for tests.""" + argv = sys.argv[1:] if argv is None else argv + env = os.environ if env is None else env + if len(argv) != 1 or not argv[0]: + print("usage: python -m greffer_cli.updater ", file=sys.stderr) + return engine.EXIT_REFUSED + try: + cfg = _config_from_env(argv[0], env) + except KeyError as exc: + print(f"missing required updater env: {exc}", file=sys.stderr) + return engine.EXIT_REFUSED + + handle = lock_acquire() + if handle is None: + print("another update is in progress (/data lock held)", file=sys.stderr) + return engine.EXIT_REFUSED + try: + return run(**cfg) + finally: + lock_release(handle) + + +if __name__ == "__main__": # pragma: no cover + raise SystemExit(main()) diff --git a/cli/tests/test_updater_main.py b/cli/tests/test_updater_main.py new file mode 100644 index 00000000..ef9447bc --- /dev/null +++ b/cli/tests/test_updater_main.py @@ -0,0 +1,113 @@ +"""Tests for the updater container entrypoint (greffer_cli.updater.__main__). + +The engine and the /data lock are injected, so no real docker, cosign, or +fcntl. Focus: env -> config mapping, the usage/missing-env/lock-held refusal +paths, and that the lock is always released (try/finally). +""" + +from __future__ import annotations + +from pathlib import Path + +from greffer_cli.updater import __main__ as entry +from greffer_cli.updater import engine + +_ENV = { + "GREFFER_VERSION_MANIFEST_URL": "https://x/m.json", + "GREFFER_ID": "g1", + "GREFFER_MODE": "tunnel", +} + + +def test_config_from_env_maps_fields(): + cfg = entry._config_from_env("0.3.6", dict(_ENV)) + assert cfg["target_tag"] == "0.3.6" + assert cfg["manifest_url"] == "https://x/m.json" + assert cfg["greffer_id"] == "g1" + assert cfg["mode"] == "tunnel" + assert cfg["compose_file"] == entry.DEFAULT_COMPOSE + assert cfg["ratchet_path"] == entry.DEFAULT_RATCHET + assert cfg["cosign_pub"] == entry.DEFAULT_COSIGN_PUB + assert cfg["timeout"] == 600.0 + + +def test_config_defaults_mode_proxy_when_blank(): + env = dict(_ENV) + env["GREFFER_MODE"] = "" + assert entry._config_from_env("0.3.6", env)["mode"] == "proxy" + + +def test_baked_baseline_env_overrides_file(): + env = {"GREFFER_MIN_SUPPORTED_BASELINE": " 0.3.2 "} + assert entry._baked_baseline(env) == "0.3.2" + + +def test_baked_baseline_none_when_absent(monkeypatch): + # No env override and the baked file is absent -> None. + monkeypatch.setattr(entry, "DEFAULT_BASELINE_FILE", Path("/nonexistent/baseline")) + assert entry._baked_baseline({}) is None + + +def test_main_happy_runs_engine_and_releases_lock(): + calls = {} + handle = object() + + def fake_run(**cfg): + calls["cfg"] = cfg + return engine.EXIT_OK + + released = [] + rc = entry.main( + ["0.3.6"], env=dict(_ENV), run=fake_run, + lock_acquire=lambda: handle, lock_release=released.append, + ) + assert rc == engine.EXIT_OK + assert calls["cfg"]["target_tag"] == "0.3.6" + assert released == [handle] # lock released in finally + + +def test_main_usage_error_refuses(): + rc = entry.main([], env=dict(_ENV), run=lambda **k: pytest_fail()) + assert rc == engine.EXIT_REFUSED + + +def test_main_empty_tag_refuses(): + rc = entry.main([""], env=dict(_ENV), run=lambda **k: pytest_fail()) + assert rc == engine.EXIT_REFUSED + + +def test_main_missing_env_refuses_before_lock(): + locked = {"acquired": False} + rc = entry.main( + ["0.3.6"], env={}, run=lambda **k: pytest_fail(), + lock_acquire=lambda: locked.__setitem__("acquired", True), + ) + assert rc == engine.EXIT_REFUSED + assert locked["acquired"] is False # never reached the lock + + +def test_main_lock_held_refuses_without_running(): + rc = entry.main( + ["0.3.6"], env=dict(_ENV), run=lambda **k: pytest_fail(), + lock_acquire=lambda: None, # another actor holds it + ) + assert rc == engine.EXIT_REFUSED + + +def test_main_releases_lock_even_when_engine_raises(): + released = [] + handle = object() + + def boom(**cfg): + raise RuntimeError("engine blew up") + + try: + entry.main(["0.3.6"], env=dict(_ENV), run=boom, + lock_acquire=lambda: handle, lock_release=released.append) + except RuntimeError: + pass + assert released == [handle] # released despite the exception + + +def pytest_fail(): + raise AssertionError("run should not have been called") From 8caa947377665a38e419b801482fe6369648ed5f Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Tue, 16 Jun 2026 11:18:50 +0200 Subject: [PATCH 5/8] feat(greffer): POST /api/controller/update/ spawns the v2 updater Wires the v2 remote-update engine into the live service. The route is fail-closed gated: greffer_remote_update_enabled off (default) -> 403 at the source; greffer_updater_image unset -> 503 (no silent :latest pull of the container that recreates the greffer). On accept it spawns the signed, digest-pinned updater container via the docker socket and returns 202. spawn_updater (apps/utils/docker/updater.py) discovers host mount sources off the greffer own container record (hostname == container id), so the compose dir -> /work and /data (bind or named volume, preserved) are mounted into the sibling exactly as the operator mounted the greffer. The target tag is validated by the model (Docker tag grammar, 400 on bad) and passed to the updater as a list arg (no shell); provenance + min_supported floor verification all run inside the spawned container before any recreate. Co-Authored-By: Claude Opus 4.8 --- app/models/controller.py | 29 ++++++ app/routers/controller.py | 59 ++++++++++++ app/settings.py | 14 +++ apps/utils/docker/updater.py | 126 +++++++++++++++++++++++++ tests/test_controller_update.py | 115 +++++++++++++++++++++++ tests/test_updater_spawn.py | 157 ++++++++++++++++++++++++++++++++ 6 files changed, 500 insertions(+) create mode 100644 apps/utils/docker/updater.py create mode 100644 tests/test_controller_update.py create mode 100644 tests/test_updater_spawn.py diff --git a/app/models/controller.py b/app/models/controller.py index 7b60587c..8cd8c364 100644 --- a/app/models/controller.py +++ b/app/models/controller.py @@ -177,6 +177,35 @@ class InstanceLogsResponse(BaseModel): truncated: bool = False +class RemoteUpdateRequest(BaseModel): + """Manager-triggered remote update (greffer self-update v2). + + ``target_tag`` is the version the operator picked in the manager UI (e.g. + ``"0.3.6"``). It is NOT trusted: the controller re-validates the tag grammar + and the spawned updater re-validates it again and runs the full provenance + + ``min_supported`` floor verification before any recreate. The tag is passed + to the updater as a list arg (no shell), so it can never be a command + injection vector; the grammar check is defense-in-depth against a malformed + ref reaching ``docker``. + + The pattern mirrors the v1 CLI's ``is_valid_image_tag`` Docker tag grammar + (leading alphanumeric/underscore, then alphanumeric/underscore/dot/dash, up + to 128 chars). A tag that fails it is a 422 before any handler body runs, so + a tampered manifest value can name only a tag in the known repo, never inject + a newline or a different image. + """ + target_tag: str = Field(pattern=r"^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$") + + +class RemoteUpdateResponse(BaseModel): + """202 ack: the updater container was spawned. The actual update runs + detached and reports its outcome out-of-band (the recreated greffer + re-registers / heartbeats at the new version). ``updater_id`` is the spawned + container id, for operator log correlation.""" + status: Literal["accepted"] = "accepted" + updater_id: str + + class TunnelConfigPushRequest(BaseModel): """v3 manager-pushed rathole client.toml — second-phase push for start/stop flows. diff --git a/app/routers/controller.py b/app/routers/controller.py index 66a4117f..e8e19804 100644 --- a/app/routers/controller.py +++ b/app/routers/controller.py @@ -31,6 +31,8 @@ InstanceDiskResponse, InstanceLogsResponse, InstanceStatsResponse, + RemoteUpdateRequest, + RemoteUpdateResponse, TunnelConfigPushRequest, TunnelConfigPushResponse, ) @@ -42,6 +44,7 @@ # Framework-agnostic shared code imported directly — no rewrite. from apps.utils.docker import compose, instance_logs, observe +from apps.utils.docker import updater as updater_spawn from apps.utils.greffon import repository from apps.utils.nginx import conf @@ -279,6 +282,62 @@ def _write_pushed_client_toml( return "ok" +@router.post("/update/", status_code=202) +def remote_update( + payload: RemoteUpdateRequest, request: Request +) -> RemoteUpdateResponse: + """Spawn the detached v2 updater container (greffer self-update v2). + + Fail-closed gating, in order: + * ``greffer_remote_update_enabled`` is the operator-sovereign switch. OFF + (default) -> 403 at the SOURCE, so remote update stays off even if a + manager is misconfigured to offer it. The flag is also advertised in the + register payload so a correct manager never shows the button when off. + * ``greffer_updater_image`` must be a configured, digest-pinned ref; + unset -> 503, never a silent ``:latest`` pull of the one container that + recreates the greffer. + + The handler does NOT verify provenance or recreate anything itself: it spawns + the signed updater, which takes the ``/data`` lock and runs the full verify + -> pin -> recreate -> health-gate -> rollback flow, then returns 202 with the + spawned container id. The target tag is already validated by the model and is + passed to the updater as a list arg (no shell).""" + settings = _settings(request) + if not settings.greffer_remote_update_enabled: + raise HTTPException( + status_code=403, + detail="remote_update_disabled", + ) + if not settings.greffer_updater_image: + # Flag on but image unwired: operator misconfiguration. 503 (not 500) + # so the manager reports a retry-after-config condition, not a bug. + logger.error( + "remote_update_enabled but greffer_updater_image is unset; refusing") + raise HTTPException( + status_code=503, + detail="updater_image_not_configured", + ) + + instance_id_var.set(None) # node-level op, not tied to a greffon instance + try: + updater_id = updater_spawn.spawn_updater( + image=settings.greffer_updater_image, + target_tag=payload.target_tag, + manifest_url=settings.greffer_version_manifest_url, + greffer_id=settings.greffer_id, + mode=settings.greffer_mode or "proxy", + data_dest=str(settings.greffon_path), + ) + except updater_spawn.UpdaterSpawnError as exc: + logger.error("remote_update_spawn_failed target=%s err=%s", + payload.target_tag, exc) + raise HTTPException(status_code=500, detail="updater_spawn_failed") from exc + + logger.info("remote_update_accepted target=%s updater=%s", + payload.target_tag, updater_id[:12]) + return RemoteUpdateResponse(updater_id=updater_id) + + @router.get("/greffon/{greffon_id}/") def greffon_status(greffon_id: UUID) -> GreffonStatusResponse: # Legacy Django view calls ``compose.status`` which does not exist — diff --git a/app/settings.py b/app/settings.py index 16eab418..40d46929 100644 --- a/app/settings.py +++ b/app/settings.py @@ -148,6 +148,20 @@ def _heartbeat_interval_in_range(cls, v): # GREFFER_REMOTE_UPDATE_ENABLED (the prefix pitfall noted above). greffer_remote_update_enabled: bool = False + # Remote-update wiring (greffer self-update v2), only consulted when + # ``greffer_remote_update_enabled`` is true. ``greffer_updater_image`` is the + # DIGEST-PINNED signed updater image the controller spawns + # (``greffon/greffer-updater@sha256:...``); pinning by digest is what stops a + # moved-tag swap of the one container that recreates the greffer. Left empty + # by default so an operator who flips the flag without wiring the image gets a + # clear refusal from the route (not a silent ``:latest`` pull). + # ``greffer_version_manifest_url`` is the signed version manifest the updater + # fetches to compute the ``min_supported`` floor; the same default the v1 CLI + # uses. Both carry the ``greffer_`` prefix to bind GREFFER_UPDATER_IMAGE / + # GREFFER_VERSION_MANIFEST_URL (the prefix pitfall noted above). + greffer_updater_image: str = "" + greffer_version_manifest_url: str = "https://greffon.io/greffer-version.json" + # Self-health watchdog (greffer-observability epic, Feature #3). The # watchdog evaluates /readyz's FATAL conditions and, when one is sustained # past the grace window, exits the uvicorn process so ``restart: diff --git a/apps/utils/docker/updater.py b/apps/utils/docker/updater.py new file mode 100644 index 00000000..d8fb0ff6 --- /dev/null +++ b/apps/utils/docker/updater.py @@ -0,0 +1,126 @@ +"""Spawn the detached ``greffon/greffer-updater`` container (self-update v2). + +A manager-triggered remote update cannot run in the greffer process: the +updater recreates the greffer's OWN container, so it has to outlive the process +it replaces. The controller therefore spawns a SEPARATE, short-lived container +from the signed, digest-pinned updater image, mounting the docker socket plus +the same host paths the greffer itself uses, and returns 202 right away. The +updater then takes the ``/data`` lock, verifies provenance, and recreates the +stack (see ``greffer_cli.updater``). + +Host-path discovery: inside a container the bind sources visible on ``/proc`` +are CONTAINER paths; to mount the same host directories into a SIBLING +container we need the HOST sources. We read them off the greffer's own +container record (looked up by ``hostname`` == container id), not from env, so +``/work`` (the compose dir) and ``/data`` always track however the operator +actually mounted the greffer. Reusing the recorded mount ``Type``/``Source`` +also preserves a named-volume ``/data`` as a volume mount rather than guessing a +host path. + +Fail-closed: any missing mount, unknown self-container, or docker error raises +``UpdaterSpawnError`` and the route surfaces it; nothing is spawned half-wired. +""" + +from __future__ import annotations + +import logging +import socket + +import docker +from docker.types import Mount + +logger = logging.getLogger("greffer") + +# The greffer mounts its compose dir at /app (``./:/app``) and uses +# ``$GREFFON_PATH`` (default /data) for persistent state. The updater image +# expects the compose dir at /work and the shared state at /data. +SELF_COMPOSE_DEST = "/app" +UPDATER_COMPOSE_DEST = "/work" +DOCKER_SOCK = "/var/run/docker.sock" + + +class UpdaterSpawnError(Exception): + """The updater container could not be wired/spawned. Fail-closed.""" + + +def _self_container(client): + """The greffer's own container, looked up by hostname (== container id + inside docker). Raises UpdaterSpawnError if it can't be resolved.""" + name = socket.gethostname() + try: + return client.containers.get(name) + except docker.errors.NotFound as exc: + raise UpdaterSpawnError( + f"cannot resolve own container (hostname={name!r}); " + "is the greffer running under docker with the socket mounted?" + ) from exc + except docker.errors.APIError as exc: + raise UpdaterSpawnError(f"docker error resolving self: {exc}") from exc + + +def _mount_for(self_attrs: dict, destination: str, *, target: str) -> Mount: + """Replicate the self-container's mount at ``destination`` onto a new + ``target``, preserving the mount Type (bind vs named volume) and Source. + Raises UpdaterSpawnError if the greffer has no such mount.""" + for m in self_attrs.get("Mounts", []): + if m.get("Destination") == destination: + mtype = m.get("Type", "bind") + # For a named volume the reusable source is the volume Name; for a + # bind it is the host path in Source. + source = m.get("Name") if mtype == "volume" else m.get("Source") + if not source: + raise UpdaterSpawnError( + f"mount at {destination} has no reusable source") + return Mount(target=target, source=source, type=mtype, + read_only=False) + raise UpdaterSpawnError( + f"greffer has no mount at {destination}; cannot wire the updater") + + +def spawn_updater( + *, image: str, target_tag: str, manifest_url: str, greffer_id: str | None, + mode: str, data_dest: str = "/data", client=None, +) -> str: + """Spawn the detached updater container and return its id. + + ``image`` MUST be a digest-pinned ref (caller's responsibility / settings + contract). Mounts: the greffer's compose dir -> /work, its ``data_dest`` + (default /data) -> /data, and the docker socket. The target tag is passed as + a list arg (no shell), and the updater re-validates it; provenance/floor + verification all happen inside the container before any recreate.""" + if not image: + raise UpdaterSpawnError("no updater image configured") + client = client or docker.from_env() + self_attrs = _self_container(client).attrs + + mounts = [ + _mount_for(self_attrs, SELF_COMPOSE_DEST, target=UPDATER_COMPOSE_DEST), + _mount_for(self_attrs, data_dest, target="/data"), + Mount(target=DOCKER_SOCK, source=DOCKER_SOCK, type="bind"), + ] + environment = { + "GREFFER_VERSION_MANIFEST_URL": manifest_url, + "GREFFER_ID": greffer_id or "", + "GREFFER_MODE": mode, + } + try: + container = client.containers.run( + image, + ["python", "-m", "greffer_cli.updater", target_tag], + detach=True, + # The updater is one-shot; drop the container when it exits so a + # series of updates doesn't litter the host. Logs are captured by + # the manager-visible exit, not the container record. + remove=True, + environment=environment, + mounts=mounts, + # Default bridge: the updater needs egress to fetch the signed + # version manifest (HTTPS) and to resolve image digests at the + # registry (``buildx imagetools inspect`` / cosign run in-container). + # It exposes no inbound port. + ) + except docker.errors.APIError as exc: + raise UpdaterSpawnError(f"failed to spawn updater: {exc}") from exc + logger.info("remote_update_spawned image=%s target=%s container=%s", + image, target_tag, container.id[:12]) + return container.id diff --git a/tests/test_controller_update.py b/tests/test_controller_update.py new file mode 100644 index 00000000..4bfad22a --- /dev/null +++ b/tests/test_controller_update.py @@ -0,0 +1,115 @@ +"""Tests for POST /api/controller/update/ (greffer self-update v2). + +The spawn module (docker SDK) is patched, so no real docker. Focus: the +fail-closed gating (flag off -> 403, image unset -> 503), the tag-grammar 422, +the spawn-failure 500, and the 202 happy path with the updater wired from +settings. +""" + +from __future__ import annotations + +from unittest.mock import patch + +import pytest +from httpx import ASGITransport, AsyncClient + +from app.auth import TOKEN_HEADER +from app.main import create_app +from app.settings import get_settings +from apps.utils.docker import updater as updater_spawn + +_PINNED = "greffon/greffer-updater@sha256:" + "a" * 64 + + +def _client(settings) -> AsyncClient: + app = create_app(token="test-token", settings=settings) + return AsyncClient(transport=ASGITransport(app=app), base_url="http://test") + + +def _settings(monkeypatch, tmp_path, *, enabled=True, image=_PINNED): + monkeypatch.setenv("GREFFER_ID", "g1") + monkeypatch.setenv("GREFFON_PATH", str(tmp_path)) + if enabled: + monkeypatch.setenv("GREFFER_REMOTE_UPDATE_ENABLED", "true") + monkeypatch.setenv("GREFFER_UPDATER_IMAGE", image) + monkeypatch.setenv("GREFFER_VERSION_MANIFEST_URL", "https://x/m.json") + return get_settings() + + +@pytest.mark.asyncio +async def test_update_disabled_returns_403(monkeypatch, tmp_path) -> None: + settings = _settings(monkeypatch, tmp_path, enabled=False) + with patch.object(updater_spawn, "spawn_updater") as spawn: + async with _client(settings) as ac: + r = await ac.post("/api/controller/update/", json={"target_tag": "0.3.6"}, + headers={TOKEN_HEADER: "test-token"}) + assert r.status_code == 403 + assert r.json()["detail"] == "remote_update_disabled" + spawn.assert_not_called() # gated at the source, nothing spawned + + +@pytest.mark.asyncio +async def test_update_image_unset_returns_503(monkeypatch, tmp_path) -> None: + settings = _settings(monkeypatch, tmp_path, image="") + with patch.object(updater_spawn, "spawn_updater") as spawn: + async with _client(settings) as ac: + r = await ac.post("/api/controller/update/", json={"target_tag": "0.3.6"}, + headers={TOKEN_HEADER: "test-token"}) + assert r.status_code == 503 + assert r.json()["detail"] == "updater_image_not_configured" + spawn.assert_not_called() + + +@pytest.mark.asyncio +async def test_update_happy_spawns_and_returns_202(monkeypatch, tmp_path) -> None: + settings = _settings(monkeypatch, tmp_path) + with patch.object(updater_spawn, "spawn_updater", return_value="cid123") as spawn: + async with _client(settings) as ac: + r = await ac.post("/api/controller/update/", json={"target_tag": "0.3.6"}, + headers={TOKEN_HEADER: "test-token"}) + assert r.status_code == 202 + body = r.json() + assert body == {"status": "accepted", "updater_id": "cid123"} + spawn.assert_called_once() + kw = spawn.call_args.kwargs + assert kw["image"] == _PINNED + assert kw["target_tag"] == "0.3.6" + assert kw["manifest_url"] == "https://x/m.json" + assert kw["greffer_id"] == "g1" + assert kw["data_dest"] == str(tmp_path) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("bad", ["bad:tag", "0.3.6\n", "../evil", "-leading", ""]) +async def test_update_bad_tag_rejected(monkeypatch, tmp_path, bad) -> None: + # The greffer maps RequestValidationError to 400 (app/errors.py), so a tag + # failing the model grammar is a 400 before the handler runs. + settings = _settings(monkeypatch, tmp_path) + with patch.object(updater_spawn, "spawn_updater") as spawn: + async with _client(settings) as ac: + r = await ac.post("/api/controller/update/", json={"target_tag": bad}, + headers={TOKEN_HEADER: "test-token"}) + assert r.status_code == 400 + spawn.assert_not_called() # rejected by the model before the handler runs + + +@pytest.mark.asyncio +async def test_update_spawn_failure_returns_500(monkeypatch, tmp_path) -> None: + settings = _settings(monkeypatch, tmp_path) + with patch.object(updater_spawn, "spawn_updater", + side_effect=updater_spawn.UpdaterSpawnError("no socket")): + async with _client(settings) as ac: + r = await ac.post("/api/controller/update/", json={"target_tag": "0.3.6"}, + headers={TOKEN_HEADER: "test-token"}) + assert r.status_code == 500 + assert r.json()["detail"] == "updater_spawn_failed" + + +@pytest.mark.asyncio +async def test_update_requires_token(monkeypatch, tmp_path) -> None: + settings = _settings(monkeypatch, tmp_path) + with patch.object(updater_spawn, "spawn_updater") as spawn: + async with _client(settings) as ac: + r = await ac.post("/api/controller/update/", json={"target_tag": "0.3.6"}) + assert r.status_code in (401, 403) + spawn.assert_not_called() diff --git a/tests/test_updater_spawn.py b/tests/test_updater_spawn.py new file mode 100644 index 00000000..16ace53d --- /dev/null +++ b/tests/test_updater_spawn.py @@ -0,0 +1,157 @@ +"""Tests for the v2 updater spawn module (apps/utils/docker/updater.py). + +The docker SDK client is faked, so no real daemon. Focus: host-path discovery +off the greffer's own container record (compose dir -> /work, /data preserved by +mount Type), the docker-socket mount, the run args, and the fail-closed errors. +""" + +from __future__ import annotations + +from unittest.mock import MagicMock + +import docker +import pytest + +from apps.utils.docker import updater + +_BIND_APP = {"Type": "bind", "Source": "/host/greffer", "Destination": "/app"} +_VOL_DATA = {"Type": "volume", "Name": "greffer-data", "Source": "/var/lib/docker/x", + "Destination": "/data"} + + +class _FakeContainers: + def __init__(self, attrs, *, run_id="cid0123456789", run_exc=None): + self._attrs = attrs + self._run_id = run_id + self._run_exc = run_exc + self.run_calls: list = [] + + def get(self, name): + c = MagicMock() + c.attrs = self._attrs + return c + + def run(self, image, command, **kwargs): + self.run_calls.append({"image": image, "command": command, **kwargs}) + if self._run_exc is not None: + raise self._run_exc + c = MagicMock() + c.id = self._run_id + return c + + +class _FakeClient: + def __init__(self, containers): + self.containers = containers + + +def _client(mounts, **kw): + return _FakeClient(_FakeContainers({"Mounts": mounts}, **kw)) + + +def _by_target(mounts): + return {m["Target"]: m for m in mounts} + + +def test_spawn_happy_wires_mounts_env_and_command(): + client = _client([_BIND_APP, _VOL_DATA]) + cid = updater.spawn_updater( + image="greffon/greffer-updater@sha256:" + "a" * 64, + target_tag="0.3.6", manifest_url="https://x/m.json", + greffer_id="g1", mode="tunnel", client=client) + assert cid == "cid0123456789" + call = client.containers.run_calls[0] + assert call["command"] == ["python", "-m", "greffer_cli.updater", "0.3.6"] + assert call["detach"] is True + assert call["environment"]["GREFFER_VERSION_MANIFEST_URL"] == "https://x/m.json" + assert call["environment"]["GREFFER_ID"] == "g1" + assert call["environment"]["GREFFER_MODE"] == "tunnel" + mounts = _by_target(call["mounts"]) + # compose dir host source -> /work + assert mounts["/work"]["Source"] == "/host/greffer" + assert mounts["/work"]["Type"] == "bind" + # /data preserved as a NAMED VOLUME (source = volume name, not host path) + assert mounts["/data"]["Source"] == "greffer-data" + assert mounts["/data"]["Type"] == "volume" + # docker socket + assert mounts["/var/run/docker.sock"]["Source"] == "/var/run/docker.sock" + + +def test_spawn_bind_data_preserves_host_path(): + bind_data = {"Type": "bind", "Source": "/host/data", "Destination": "/data"} + client = _client([_BIND_APP, bind_data]) + updater.spawn_updater( + image="img@sha256:x", target_tag="0.3.6", manifest_url="https://x", + greffer_id="g1", mode="proxy", client=client) + mounts = _by_target(client.containers.run_calls[0]["mounts"]) + assert mounts["/data"]["Source"] == "/host/data" + assert mounts["/data"]["Type"] == "bind" + + +def test_spawn_custom_data_dest(): + custom = {"Type": "volume", "Name": "v", "Destination": "/srv/state"} + client = _client([_BIND_APP, custom]) + updater.spawn_updater( + image="img@sha256:x", target_tag="0.3.6", manifest_url="https://x", + greffer_id="g1", mode="proxy", data_dest="/srv/state", client=client) + mounts = _by_target(client.containers.run_calls[0]["mounts"]) + assert mounts["/data"]["Source"] == "v" + + +def test_spawn_empty_image_refuses(): + with pytest.raises(updater.UpdaterSpawnError): + updater.spawn_updater( + image="", target_tag="0.3.6", manifest_url="https://x", + greffer_id="g1", mode="proxy", client=_client([_BIND_APP, _VOL_DATA])) + + +def test_spawn_missing_data_mount_refuses(): + client = _client([_BIND_APP]) # no /data + with pytest.raises(updater.UpdaterSpawnError): + updater.spawn_updater( + image="img@sha256:x", target_tag="0.3.6", manifest_url="https://x", + greffer_id="g1", mode="proxy", client=client) + assert client.containers.run_calls == [] # never spawned + + +def test_spawn_missing_compose_mount_refuses(): + client = _client([_VOL_DATA]) # no /app + with pytest.raises(updater.UpdaterSpawnError): + updater.spawn_updater( + image="img@sha256:x", target_tag="0.3.6", manifest_url="https://x", + greffer_id="g1", mode="proxy", client=client) + + +def test_spawn_volume_without_source_refuses(): + bad = {"Type": "volume", "Destination": "/data"} # no Name/Source + client = _client([_BIND_APP, bad]) + with pytest.raises(updater.UpdaterSpawnError): + updater.spawn_updater( + image="img@sha256:x", target_tag="0.3.6", manifest_url="https://x", + greffer_id="g1", mode="proxy", client=client) + + +def test_spawn_self_not_found_refuses(): + containers = _FakeContainers({"Mounts": [_BIND_APP, _VOL_DATA]}) + containers.get = MagicMock(side_effect=docker.errors.NotFound("nope")) + with pytest.raises(updater.UpdaterSpawnError): + updater.spawn_updater( + image="img@sha256:x", target_tag="0.3.6", manifest_url="https://x", + greffer_id="g1", mode="proxy", client=_FakeClient(containers)) + + +def test_spawn_run_api_error_refuses(): + client = _client([_BIND_APP, _VOL_DATA], + run_exc=docker.errors.APIError("daemon boom")) + with pytest.raises(updater.UpdaterSpawnError): + updater.spawn_updater( + image="img@sha256:x", target_tag="0.3.6", manifest_url="https://x", + greffer_id="g1", mode="proxy", client=client) + + +def test_spawn_none_greffer_id_becomes_empty_env(): + client = _client([_BIND_APP, _VOL_DATA]) + updater.spawn_updater( + image="img@sha256:x", target_tag="0.3.6", manifest_url="https://x", + greffer_id=None, mode="proxy", client=client) + assert client.containers.run_calls[0]["environment"]["GREFFER_ID"] == "" From 4b38d9d03c3da1796643225b2a017c479a59ad58 Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Tue, 16 Jun 2026 11:28:46 +0200 Subject: [PATCH 6/8] fix(greffer): address deep-review findings on v2 remote update Independent review (security + correctness + test lenses) surfaced two load-bearing defects and several gaps: P1 lock divergence: the remote updater locked /data/.greffer-update.lock while a host `greffer update` (v1) locks /.update.lock. Those are different inodes, so the documented "mutually exclusive" guarantee was broken and two updates could corrupt the shared compose file. Lock /work/.update.lock instead (/work is that same host compose dir bind-mount, same filename v1 uses). P2 spurious rollback: health_gate._version_applied looked up the local tag greffon/greffer:, but v2 pulls/pins by digest and never creates that tag, so every successful digest update read None -> GATE_NOT_APPLIED -> rollback. Thread the verified greffer digest through health_gate(applied_ref=) so it verifies against the digest actually running. P2 unenforced digest-pin: the updater image (the one socket-mounted, root-equivalent container, itself unverified) was only checked non-empty. Enforce @sha256: pinning in spawn_updater and at the route (503 updater_image_not_digest_pinned) so a registry-side tag move cannot swap it. Tests: cover the previously-dead digest-unresolvable / pull-failure / empty-compose / compose-up-failure-rollback engine branches; assert the gate receives the verified digest; assert the route mode kwarg + tunnel mode + the non-pinned 503; assert remove=True + socket mount type + the lock-path inode. Doc: correct the model docstring (validation maps to 400, not 422). Co-Authored-By: Claude Opus 4.8 --- app/models/controller.py | 7 +++-- app/routers/controller.py | 11 +++++++ apps/utils/docker/updater.py | 18 +++++++++++ cli/greffer_cli/update.py | 26 +++++++++++----- cli/greffer_cli/updater/__main__.py | 19 ++++++++---- cli/greffer_cli/updater/engine.py | 6 +++- cli/tests/test_updater_engine.py | 46 +++++++++++++++++++++++++++++ cli/tests/test_updater_main.py | 9 ++++++ tests/test_controller_update.py | 25 ++++++++++++++++ tests/test_updater_spawn.py | 42 ++++++++++++++++++++------ 10 files changed, 183 insertions(+), 26 deletions(-) diff --git a/app/models/controller.py b/app/models/controller.py index 8cd8c364..c3263888 100644 --- a/app/models/controller.py +++ b/app/models/controller.py @@ -190,9 +190,10 @@ class RemoteUpdateRequest(BaseModel): The pattern mirrors the v1 CLI's ``is_valid_image_tag`` Docker tag grammar (leading alphanumeric/underscore, then alphanumeric/underscore/dot/dash, up - to 128 chars). A tag that fails it is a 422 before any handler body runs, so - a tampered manifest value can name only a tag in the known repo, never inject - a newline or a different image. + to 128 chars). A tag that fails it is rejected before any handler body runs; + the greffer maps the resulting RequestValidationError to 400 (app/errors.py), + so a tampered manifest value can name only a tag in the known repo, never + inject a newline or a different image. """ target_tag: str = Field(pattern=r"^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$") diff --git a/app/routers/controller.py b/app/routers/controller.py index e8e19804..a8bc3539 100644 --- a/app/routers/controller.py +++ b/app/routers/controller.py @@ -317,6 +317,17 @@ def remote_update( status_code=503, detail="updater_image_not_configured", ) + if not updater_spawn.is_digest_pinned(settings.greffer_updater_image): + # The most privileged container in the flow (docker.sock = host root) + # must be pinned by digest so a registry-side tag move can't swap it. + # Operator misconfiguration -> 503, fail-closed, nothing spawned. + logger.error( + "greffer_updater_image is not digest-pinned (%s); refusing", + settings.greffer_updater_image) + raise HTTPException( + status_code=503, + detail="updater_image_not_digest_pinned", + ) instance_id_var.set(None) # node-level op, not tied to a greffon instance try: diff --git a/apps/utils/docker/updater.py b/apps/utils/docker/updater.py index d8fb0ff6..7b0b60f3 100644 --- a/apps/utils/docker/updater.py +++ b/apps/utils/docker/updater.py @@ -24,6 +24,7 @@ from __future__ import annotations import logging +import re import socket import docker @@ -31,6 +32,18 @@ logger = logging.getLogger("greffer") +# The updater image MUST be digest-pinned: it is the one root-equivalent, +# socket-mounted container that recreates the greffer, and it is NOT itself run +# through the cosign/floor verification it performs on the target. A mutable tag +# (``:latest``) could be repointed registry-side to swap it. Require an explicit +# ``@sha256:<64 hex>`` so a tag move can never change what runs. +_DIGEST_PINNED_RE = re.compile(r"@sha256:[0-9a-f]{64}$") + + +def is_digest_pinned(ref: object) -> bool: + """True iff ``ref`` is an image reference pinned by a sha256 digest.""" + return isinstance(ref, str) and _DIGEST_PINNED_RE.search(ref) is not None + # The greffer mounts its compose dir at /app (``./:/app``) and uses # ``$GREFFON_PATH`` (default /data) for persistent state. The updater image # expects the compose dir at /work and the shared state at /data. @@ -90,6 +103,11 @@ def spawn_updater( verification all happen inside the container before any recreate.""" if not image: raise UpdaterSpawnError("no updater image configured") + if not is_digest_pinned(image): + # Defense-in-depth: the route also rejects this, but enforce it here so + # the contract holds for any caller of spawn_updater. + raise UpdaterSpawnError( + f"updater image must be digest-pinned (got {image!r})") client = client or docker.from_env() self_attrs = _self_container(client).attrs diff --git a/cli/greffer_cli/update.py b/cli/greffer_cli/update.py index 93e78303..31523c14 100644 --- a/cli/greffer_cli/update.py +++ b/cli/greffer_cli/update.py @@ -237,15 +237,22 @@ def _resolve_mode(env: env_file.EnvFile, compose_file: Path) -> str: return "tunnel" if "tunnel-sidecar" in running else "proxy" -def _version_applied(compose_file: Path, target: str) -> bool: - """Did the recreate actually advance the greffer to the pulled target? - - Compares the running greffer container's image id to the pulled - ``greffon/greffer:`` image id. A mispublished/moved tag or an - unbumped image leaves the old image running and fails this. +def _version_applied( + compose_file: Path, target: str, *, applied_ref: str | None = None +) -> bool: + """Did the recreate actually advance the greffer to the intended image? + + Compares the running greffer container's image id to the intended image id. + ``applied_ref`` overrides the lookup ref when the recreate pinned a DIGEST + rather than a tag (the v2 remote-update path: it pulls/pins + ``greffon/greffer@sha256:...`` and never creates the local + ``greffon/greffer:`` tag, so a tag lookup would spuriously read None + and fail the gate). When unset (the v1 tag path) it falls back to the + ``greffon/greffer:`` tag. A mispublished/moved tag or an unbumped + image leaves the old image running and fails this. """ running = compose.container_image_id(compose_file, "greffer") - target_id = compose.image_id(f"{GREFFER_REPO}:{target}") + target_id = compose.image_id(applied_ref or f"{GREFFER_REPO}:{target}") return bool(running and target_id and running == target_id) @@ -254,6 +261,7 @@ def health_gate( services: list[str], profile: str | None, timeout: float, poll_interval: float = 2.0, sleep: Callable[[float], None] = time.sleep, + applied_ref: str | None = None, ) -> str: """Poll until the recreated node is healthy or a failure is decided. @@ -279,7 +287,9 @@ def health_gate( ): return GATE_DEGRADED_OTHER if r.status == "ready": - if not _version_applied(compose_file, target): + if not _version_applied( + compose_file, target, applied_ref=applied_ref + ): return GATE_NOT_APPLIED svcs = compose.compose_services_running( compose_file, profile=profile, diff --git a/cli/greffer_cli/updater/__main__.py b/cli/greffer_cli/updater/__main__.py index d3f1b8f6..5fc004a0 100644 --- a/cli/greffer_cli/updater/__main__.py +++ b/cli/greffer_cli/updater/__main__.py @@ -2,10 +2,16 @@ ``python -m greffer_cli.updater `` (the rest of the config comes from the environment the greffer sets when it spawns the updater). It takes the -``/data`` update lock so a remote update and a host ``greffer update`` are -mutually exclusive (HLD "Concurrency"), runs the v2 verify -> pin -> recreate -engine, and exits with its code. The lock lives on the ``/data`` volume because -that is the only filesystem the updater and the recreated greffer share. +update lock so a remote update and a host ``greffer update`` are mutually +exclusive (HLD "Concurrency"), runs the v2 verify -> pin -> recreate engine, and +exits with its code. + +The lock file is ``/work/.update.lock``. ``/work`` is the host compose dir +bind-mounted into the updater, which is exactly the dir a host ``greffer +update`` locks (``/.update.lock`` in greffer_cli.update). Both sides +must lock the SAME host inode for ``flock`` to actually serialize them; locking +``/data`` instead would be a different inode and the two updaters could run +concurrently and corrupt the shared compose file. """ from __future__ import annotations @@ -21,7 +27,10 @@ # min_supported baseline into /etc/greffer at build time. DEFAULT_COMPOSE = Path("/work/docker-compose.yml") DEFAULT_RATCHET = Path("/data/.greffer-update-floor") -DEFAULT_LOCK = Path("/data/.greffer-update.lock") +# Same host inode a host ``greffer update`` locks (its ``/ +# .update.lock``); /work IS that config dir bind-mounted in. Must match the v1 +# filename ``.update.lock`` or the two locks miss each other (P1). +DEFAULT_LOCK = Path("/work/.update.lock") DEFAULT_COSIGN_PUB = "/etc/greffer/cosign.pub" DEFAULT_BASELINE_FILE = Path("/etc/greffer/min_supported_baseline") diff --git a/cli/greffer_cli/updater/engine.py b/cli/greffer_cli/updater/engine.py index a62225d3..496649d2 100644 --- a/cli/greffer_cli/updater/engine.py +++ b/cli/greffer_cli/updater/engine.py @@ -123,9 +123,13 @@ def run_remote_update( compose_file, profile=profile, services=services, old_refs=old_refs, greffer_id=greffer_id, timeout=timeout, sleep=sleep) + # v2 pins/pulls by digest, so the local ``greffon/greffer:`` tag never + # exists; tell the gate to verify "version applied" against the VERIFIED + # greffer digest instead, or it reads None and rolls back every success. outcome = update.health_gate( compose_file, greffer_id=greffer_id, target=target_tag, - services=services, profile=profile, timeout=timeout, sleep=sleep) + services=services, profile=profile, timeout=timeout, sleep=sleep, + applied_ref=verified.get(update.GREFFER_REPO)) if outcome == update.GATE_READY: logger.info("remote update applied: %s", target_tag) return EXIT_OK diff --git a/cli/tests/test_updater_engine.py b/cli/tests/test_updater_engine.py index 25fe1bae..6c11480a 100644 --- a/cli/tests/test_updater_engine.py +++ b/cli/tests/test_updater_engine.py @@ -116,6 +116,25 @@ def test_cohesion_mismatch_refuses(cf, monkeypatch): assert _run(cf, monkeypatch) == engine.EXIT_REFUSED +def test_digest_unresolvable_refuses(cf, monkeypatch): + _patch_verify(monkeypatch, digest_ok=False) # registry can't resolve a digest + monkeypatch.setattr(compose, "set_image_refs", lambda *a, **k: pytest.fail("recreated")) + assert _run(cf, monkeypatch) == engine.EXIT_REFUSED + + +def test_pull_failure_refuses(cf, monkeypatch): + _patch_verify(monkeypatch, pull_ok=False) # docker pull by digest fails + monkeypatch.setattr(compose, "set_image_refs", lambda *a, **k: pytest.fail("recreated")) + assert _run(cf, monkeypatch) == engine.EXIT_REFUSED + + +def test_empty_compose_refuses(cf, monkeypatch): + cf.write_text("services: {}\n", encoding="utf-8") # no greffon/* images + _patch_verify(monkeypatch) + monkeypatch.setattr(compose, "set_image_refs", lambda *a, **k: pytest.fail("recreated")) + assert _run(cf, monkeypatch) == engine.EXIT_REFUSED + + # --- run_remote_update recreate + rollback -------------------------- def test_happy_pins_digests_and_recreates(cf, monkeypatch): @@ -137,3 +156,30 @@ def test_gate_failure_rolls_back(cf, monkeypatch): monkeypatch.setattr(update, "health_gate", lambda *a, **k: update.GATE_FATAL) monkeypatch.setattr(update, "_rollback", lambda *a, **k: update.EXIT_FAILED_ROLLED_BACK) assert _run(cf, monkeypatch) == engine.EXIT_FAILED_ROLLED_BACK + + +def test_compose_up_failure_rolls_back_without_gate(cf, monkeypatch): + # A failed `compose up` rolls back immediately and never reaches the gate. + _patch_verify(monkeypatch) + monkeypatch.setattr(compose, "set_image_refs", lambda f, refs: None) + monkeypatch.setattr(compose, "compose_up", + lambda f, **k: compose.CommandResult(1, "", "up failed")) + monkeypatch.setattr(update, "health_gate", + lambda *a, **k: pytest.fail("gate reached after up failure")) + monkeypatch.setattr(update, "_rollback", lambda *a, **k: update.EXIT_FAILED_ROLLED_BACK) + assert _run(cf, monkeypatch) == engine.EXIT_FAILED_ROLLED_BACK + + +def test_gate_gets_verified_greffer_digest_not_tag(cf, monkeypatch): + # v2 pins by digest, so the gate must verify "version applied" against the + # verified greffon/greffer digest, never the (absent) local tag. + _patch_verify(monkeypatch) + monkeypatch.setattr(compose, "set_image_refs", lambda f, refs: None) + monkeypatch.setattr(compose, "compose_up", lambda f, **k: _ok()) + seen = {} + def fake_gate(*a, applied_ref=None, **k): + seen["applied_ref"] = applied_ref + return update.GATE_READY + monkeypatch.setattr(update, "health_gate", fake_gate) + assert _run(cf, monkeypatch) == engine.EXIT_OK + assert seen["applied_ref"] == f"greffon/greffer@sha256:{'a' * 64}" diff --git a/cli/tests/test_updater_main.py b/cli/tests/test_updater_main.py index ef9447bc..342a55a8 100644 --- a/cli/tests/test_updater_main.py +++ b/cli/tests/test_updater_main.py @@ -19,6 +19,15 @@ } +def test_lock_path_matches_v1_inode(): + # Must lock /work/.update.lock — /work is the host compose dir bind-mount, + # the same inode a host `greffer update` locks (.update.lock). A /data lock + # would be a different inode and miss the v1 lock (P1). + from greffer_cli import update + assert entry.DEFAULT_LOCK == Path("/work/.update.lock") + assert entry.DEFAULT_LOCK.name == update._update_lock_path(Path("/work")).name + + def test_config_from_env_maps_fields(): cfg = entry._config_from_env("0.3.6", dict(_ENV)) assert cfg["target_tag"] == "0.3.6" diff --git a/tests/test_controller_update.py b/tests/test_controller_update.py index 4bfad22a..962246c8 100644 --- a/tests/test_controller_update.py +++ b/tests/test_controller_update.py @@ -77,6 +77,31 @@ async def test_update_happy_spawns_and_returns_202(monkeypatch, tmp_path) -> Non assert kw["manifest_url"] == "https://x/m.json" assert kw["greffer_id"] == "g1" assert kw["data_dest"] == str(tmp_path) + assert kw["mode"] == "proxy" # GREFFER_MODE unset -> default proxy + + +@pytest.mark.asyncio +async def test_update_passes_tunnel_mode(monkeypatch, tmp_path) -> None: + monkeypatch.setenv("GREFFER_MODE", "tunnel") + settings = _settings(monkeypatch, tmp_path) + with patch.object(updater_spawn, "spawn_updater", return_value="cid") as spawn: + async with _client(settings) as ac: + r = await ac.post("/api/controller/update/", json={"target_tag": "0.3.6"}, + headers={TOKEN_HEADER: "test-token"}) + assert r.status_code == 202 + assert spawn.call_args.kwargs["mode"] == "tunnel" + + +@pytest.mark.asyncio +async def test_update_unpinned_image_returns_503(monkeypatch, tmp_path) -> None: + settings = _settings(monkeypatch, tmp_path, image="greffon/greffer-updater:latest") + with patch.object(updater_spawn, "spawn_updater") as spawn: + async with _client(settings) as ac: + r = await ac.post("/api/controller/update/", json={"target_tag": "0.3.6"}, + headers={TOKEN_HEADER: "test-token"}) + assert r.status_code == 503 + assert r.json()["detail"] == "updater_image_not_digest_pinned" + spawn.assert_not_called() @pytest.mark.asyncio diff --git a/tests/test_updater_spawn.py b/tests/test_updater_spawn.py index 16ace53d..039f2e27 100644 --- a/tests/test_updater_spawn.py +++ b/tests/test_updater_spawn.py @@ -14,6 +14,7 @@ from apps.utils.docker import updater +_IMG = "greffon/greffer-updater@sha256:" + "0" * 64 _BIND_APP = {"Type": "bind", "Source": "/host/greffer", "Destination": "/app"} _VOL_DATA = {"Type": "volume", "Name": "greffer-data", "Source": "/var/lib/docker/x", "Destination": "/data"} @@ -63,6 +64,7 @@ def test_spawn_happy_wires_mounts_env_and_command(): call = client.containers.run_calls[0] assert call["command"] == ["python", "-m", "greffer_cli.updater", "0.3.6"] assert call["detach"] is True + assert call["remove"] is True # one-shot: don't litter the host assert call["environment"]["GREFFER_VERSION_MANIFEST_URL"] == "https://x/m.json" assert call["environment"]["GREFFER_ID"] == "g1" assert call["environment"]["GREFFER_MODE"] == "tunnel" @@ -73,15 +75,37 @@ def test_spawn_happy_wires_mounts_env_and_command(): # /data preserved as a NAMED VOLUME (source = volume name, not host path) assert mounts["/data"]["Source"] == "greffer-data" assert mounts["/data"]["Type"] == "volume" - # docker socket + # docker socket, bind-mounted assert mounts["/var/run/docker.sock"]["Source"] == "/var/run/docker.sock" + assert mounts["/var/run/docker.sock"]["Type"] == "bind" + + +def test_spawn_unpinned_image_refuses(): + # The most privileged container must be digest-pinned; a mutable tag is + # refused fail-closed (nothing spawned). + client = _client([_BIND_APP, _VOL_DATA]) + for bad in ("greffon/greffer-updater:latest", "greffon/greffer-updater", + "greffon/greffer-updater@sha256:tooshort"): + with pytest.raises(updater.UpdaterSpawnError): + updater.spawn_updater( + image=bad, target_tag="0.3.6", manifest_url="https://x", + greffer_id="g1", mode="proxy", client=client) + assert client.containers.run_calls == [] + + +def test_is_digest_pinned(): + assert updater.is_digest_pinned("r@sha256:" + "a" * 64) is True + assert updater.is_digest_pinned("r:latest") is False + assert updater.is_digest_pinned("r@sha256:" + "a" * 63) is False + assert updater.is_digest_pinned("r@sha256:" + "g" * 64) is False + assert updater.is_digest_pinned(None) is False def test_spawn_bind_data_preserves_host_path(): bind_data = {"Type": "bind", "Source": "/host/data", "Destination": "/data"} client = _client([_BIND_APP, bind_data]) updater.spawn_updater( - image="img@sha256:x", target_tag="0.3.6", manifest_url="https://x", + image=_IMG, target_tag="0.3.6", manifest_url="https://x", greffer_id="g1", mode="proxy", client=client) mounts = _by_target(client.containers.run_calls[0]["mounts"]) assert mounts["/data"]["Source"] == "/host/data" @@ -92,7 +116,7 @@ def test_spawn_custom_data_dest(): custom = {"Type": "volume", "Name": "v", "Destination": "/srv/state"} client = _client([_BIND_APP, custom]) updater.spawn_updater( - image="img@sha256:x", target_tag="0.3.6", manifest_url="https://x", + image=_IMG, target_tag="0.3.6", manifest_url="https://x", greffer_id="g1", mode="proxy", data_dest="/srv/state", client=client) mounts = _by_target(client.containers.run_calls[0]["mounts"]) assert mounts["/data"]["Source"] == "v" @@ -109,7 +133,7 @@ def test_spawn_missing_data_mount_refuses(): client = _client([_BIND_APP]) # no /data with pytest.raises(updater.UpdaterSpawnError): updater.spawn_updater( - image="img@sha256:x", target_tag="0.3.6", manifest_url="https://x", + image=_IMG, target_tag="0.3.6", manifest_url="https://x", greffer_id="g1", mode="proxy", client=client) assert client.containers.run_calls == [] # never spawned @@ -118,7 +142,7 @@ def test_spawn_missing_compose_mount_refuses(): client = _client([_VOL_DATA]) # no /app with pytest.raises(updater.UpdaterSpawnError): updater.spawn_updater( - image="img@sha256:x", target_tag="0.3.6", manifest_url="https://x", + image=_IMG, target_tag="0.3.6", manifest_url="https://x", greffer_id="g1", mode="proxy", client=client) @@ -127,7 +151,7 @@ def test_spawn_volume_without_source_refuses(): client = _client([_BIND_APP, bad]) with pytest.raises(updater.UpdaterSpawnError): updater.spawn_updater( - image="img@sha256:x", target_tag="0.3.6", manifest_url="https://x", + image=_IMG, target_tag="0.3.6", manifest_url="https://x", greffer_id="g1", mode="proxy", client=client) @@ -136,7 +160,7 @@ def test_spawn_self_not_found_refuses(): containers.get = MagicMock(side_effect=docker.errors.NotFound("nope")) with pytest.raises(updater.UpdaterSpawnError): updater.spawn_updater( - image="img@sha256:x", target_tag="0.3.6", manifest_url="https://x", + image=_IMG, target_tag="0.3.6", manifest_url="https://x", greffer_id="g1", mode="proxy", client=_FakeClient(containers)) @@ -145,13 +169,13 @@ def test_spawn_run_api_error_refuses(): run_exc=docker.errors.APIError("daemon boom")) with pytest.raises(updater.UpdaterSpawnError): updater.spawn_updater( - image="img@sha256:x", target_tag="0.3.6", manifest_url="https://x", + image=_IMG, target_tag="0.3.6", manifest_url="https://x", greffer_id="g1", mode="proxy", client=client) def test_spawn_none_greffer_id_becomes_empty_env(): client = _client([_BIND_APP, _VOL_DATA]) updater.spawn_updater( - image="img@sha256:x", target_tag="0.3.6", manifest_url="https://x", + image=_IMG, target_tag="0.3.6", manifest_url="https://x", greffer_id=None, mode="proxy", client=client) assert client.containers.run_calls[0]["environment"]["GREFFER_ID"] == "" From 13923126f519e460ccda9c14cc44f2a1fd0abfbe Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Tue, 16 Jun 2026 11:33:15 +0200 Subject: [PATCH 7/8] refactor(greffer): tighten digest-pin check + fix stale lock docstring Round-2 review nits (both non-blocking): is_digest_pinned now fullmatches (repo segment + exactly one @sha256:<64hex>, no trailing junk) so a double-digest or trailing-junk ref cannot slip past; correct the acquire_lock docstring /data -> /work after the lock-path move. Tests cover the rejected double-digest / trailing-junk cases. Co-Authored-By: Claude Opus 4.8 --- apps/utils/docker/updater.py | 9 ++++++--- cli/greffer_cli/updater/__main__.py | 2 +- cli/tests/test_updater_main.py | 2 +- tests/test_updater_spawn.py | 5 +++++ 4 files changed, 13 insertions(+), 5 deletions(-) diff --git a/apps/utils/docker/updater.py b/apps/utils/docker/updater.py index 7b0b60f3..59b71c85 100644 --- a/apps/utils/docker/updater.py +++ b/apps/utils/docker/updater.py @@ -36,13 +36,16 @@ # socket-mounted container that recreates the greffer, and it is NOT itself run # through the cosign/floor verification it performs on the target. A mutable tag # (``:latest``) could be repointed registry-side to swap it. Require an explicit -# ``@sha256:<64 hex>`` so a tag move can never change what runs. -_DIGEST_PINNED_RE = re.compile(r"@sha256:[0-9a-f]{64}$") +# ``@sha256:<64 hex>`` so a tag move can never change what runs. Anchored with +# fullmatch (repo segment, then exactly one ``@sha256:<64 hex>``, nothing +# trailing) so a pathological ref like ``a@sha256:<64hex>@sha256:<64hex>`` or +# trailing junk cannot slip past. +_DIGEST_PINNED_RE = re.compile(r"[^@\s]+@sha256:[0-9a-f]{64}") def is_digest_pinned(ref: object) -> bool: """True iff ``ref`` is an image reference pinned by a sha256 digest.""" - return isinstance(ref, str) and _DIGEST_PINNED_RE.search(ref) is not None + return isinstance(ref, str) and _DIGEST_PINNED_RE.fullmatch(ref) is not None # The greffer mounts its compose dir at /app (``./:/app``) and uses # ``$GREFFON_PATH`` (default /data) for persistent state. The updater image diff --git a/cli/greffer_cli/updater/__main__.py b/cli/greffer_cli/updater/__main__.py index 5fc004a0..6230bf0b 100644 --- a/cli/greffer_cli/updater/__main__.py +++ b/cli/greffer_cli/updater/__main__.py @@ -66,7 +66,7 @@ def _config_from_env(target_tag: str, env: dict) -> dict: def acquire_lock(lock_path: Path = DEFAULT_LOCK): - """Exclusive flock on the /data update lock. Returns a handle to release, or + """Exclusive flock on the /work update lock. Returns a handle to release, or None if another actor already holds it (the caller refuses), or the ``_NO_LOCK`` sentinel on a platform without fcntl.""" try: diff --git a/cli/tests/test_updater_main.py b/cli/tests/test_updater_main.py index 342a55a8..0a0f83ea 100644 --- a/cli/tests/test_updater_main.py +++ b/cli/tests/test_updater_main.py @@ -20,7 +20,7 @@ def test_lock_path_matches_v1_inode(): - # Must lock /work/.update.lock — /work is the host compose dir bind-mount, + # Must lock /work/.update.lock. /work is the host compose dir bind-mount, # the same inode a host `greffer update` locks (.update.lock). A /data lock # would be a different inode and miss the v1 lock (P1). from greffer_cli import update diff --git a/tests/test_updater_spawn.py b/tests/test_updater_spawn.py index 039f2e27..f8a1c6a7 100644 --- a/tests/test_updater_spawn.py +++ b/tests/test_updater_spawn.py @@ -95,10 +95,15 @@ def test_spawn_unpinned_image_refuses(): def test_is_digest_pinned(): assert updater.is_digest_pinned("r@sha256:" + "a" * 64) is True + assert updater.is_digest_pinned("greffon/greffer-updater@sha256:" + "0" * 64) is True assert updater.is_digest_pinned("r:latest") is False assert updater.is_digest_pinned("r@sha256:" + "a" * 63) is False assert updater.is_digest_pinned("r@sha256:" + "g" * 64) is False assert updater.is_digest_pinned(None) is False + # fullmatch: a double-digest or trailing junk cannot slip past + assert updater.is_digest_pinned( + "a@sha256:" + "a" * 64 + "@sha256:" + "b" * 64) is False + assert updater.is_digest_pinned("r@sha256:" + "a" * 64 + " evil") is False def test_spawn_bind_data_preserves_host_path(): From 29f1cf8322b551ed23fc7647c5b62d0bcb0a5101 Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Tue, 16 Jun 2026 12:50:24 +0200 Subject: [PATCH 8/8] docs(greffer): correct stale /data lock references to /work The v2 lock moved to /work/.update.lock (P1 fix) but five references still named the old /data path (and engine.py named the wrong filename .greffer-update.lock). One is operator-visible: the lock-contention stderr in __main__. No behavioral change (all paths use DEFAULT_LOCK), but stale comments pointing at the wrong path invite a regression of the very divergence the P1 fix closed. Caught by the final convergence review. DEFAULT_RATCHET stays on /data (the ratchet legitimately lives there). Co-Authored-By: Claude Opus 4.8 --- app/routers/controller.py | 2 +- apps/utils/docker/updater.py | 2 +- cli/greffer_cli/updater/__main__.py | 4 ++-- cli/greffer_cli/updater/engine.py | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/app/routers/controller.py b/app/routers/controller.py index a8bc3539..6a671657 100644 --- a/app/routers/controller.py +++ b/app/routers/controller.py @@ -298,7 +298,7 @@ def remote_update( recreates the greffer. The handler does NOT verify provenance or recreate anything itself: it spawns - the signed updater, which takes the ``/data`` lock and runs the full verify + the signed updater, which takes the ``/work`` lock and runs the full verify -> pin -> recreate -> health-gate -> rollback flow, then returns 202 with the spawned container id. The target tag is already validated by the model and is passed to the updater as a list arg (no shell).""" diff --git a/apps/utils/docker/updater.py b/apps/utils/docker/updater.py index 59b71c85..8858b85a 100644 --- a/apps/utils/docker/updater.py +++ b/apps/utils/docker/updater.py @@ -5,7 +5,7 @@ it replaces. The controller therefore spawns a SEPARATE, short-lived container from the signed, digest-pinned updater image, mounting the docker socket plus the same host paths the greffer itself uses, and returns 202 right away. The -updater then takes the ``/data`` lock, verifies provenance, and recreates the +updater then takes the ``/work`` lock, verifies provenance, and recreates the stack (see ``greffer_cli.updater``). Host-path discovery: inside a container the bind sources visible on ``/proc`` diff --git a/cli/greffer_cli/updater/__main__.py b/cli/greffer_cli/updater/__main__.py index 6230bf0b..d00b6c64 100644 --- a/cli/greffer_cli/updater/__main__.py +++ b/cli/greffer_cli/updater/__main__.py @@ -93,7 +93,7 @@ def release_lock(handle) -> None: def main(argv=None, *, env=None, run=engine.run_remote_update, lock_acquire=acquire_lock, lock_release=release_lock) -> int: - """Resolve config, take the /data lock, run the engine. ``run`` / + """Resolve config, take the /work lock, run the engine. ``run`` / ``lock_acquire`` are injectable for tests.""" argv = sys.argv[1:] if argv is None else argv env = os.environ if env is None else env @@ -108,7 +108,7 @@ def main(argv=None, *, env=None, run=engine.run_remote_update, handle = lock_acquire() if handle is None: - print("another update is in progress (/data lock held)", file=sys.stderr) + print("another update is in progress (/work lock held)", file=sys.stderr) return engine.EXIT_REFUSED try: return run(**cfg) diff --git a/cli/greffer_cli/updater/engine.py b/cli/greffer_cli/updater/engine.py index 496649d2..94b2fe7c 100644 --- a/cli/greffer_cli/updater/engine.py +++ b/cli/greffer_cli/updater/engine.py @@ -8,7 +8,7 @@ any verification or floor failure aborts before the node is recreated. Concurrency: the caller (the updater entrypoint) holds the -``/data/.greffer-update.lock`` across this call so the recreated controller and a +``/work/.update.lock`` across this call so the recreated controller and a host ``greffer update`` are mutually exclusive (HLD "Concurrency"). The lock is out of this module's scope so the verify/recreate logic stays unit-testable. """