From d37a1c552630c7dde8024ddb349d9c25d9c9e4c9 Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Mon, 15 Jun 2026 14:47:01 +0200 Subject: [PATCH 1/8] feat(cli): update-engine compose helpers (pull, image-ref rewrite, /readyz probe, digests) First increment of the `greffer update` v1 engine (design: greffon docs/features/ greffer-self-update, merged greffon#165). Adds the compose.py primitives the engine builds on, each unit-tested (no Docker needed): - compose_pull: explicit pull of node images (incl. profile-gated ones) before recreate, since `up` reuses the cached image when only the tag changed in-file. - set_image_tag / set_image_refs: rewrite every greffon/* image line (tagged or digest-pinned) atomically; set_image_tag returns prior refs for rollback. - data_volume_is_named: pre-flight that /data is a named volume (so identity survives recreate), distinguishing a named source from a bind path; no YAML dep. - exec_in_greffer_readyz: probe /readyz inside the container with the resolved X-GREFFON-TOKEN, returning the {id,status,reasons} body for the health gate. - image_id / container_image_id: verify the recreate advanced to the pulled target and capture the running image for rollback. 105 CLI tests pass. Next: update.py engine + `greffer update` command + strings. Co-Authored-By: Claude Opus 4.8 --- cli/greffer_cli/compose.py | 225 +++++++++++++++++++++++++++++++++++++ cli/tests/test_compose.py | 158 ++++++++++++++++++++++++++ 2 files changed, 383 insertions(+) diff --git a/cli/greffer_cli/compose.py b/cli/greffer_cli/compose.py index 9b5182c6..8bda634b 100644 --- a/cli/greffer_cli/compose.py +++ b/cli/greffer_cli/compose.py @@ -9,8 +9,11 @@ from __future__ import annotations import json +import os +import re import shlex import subprocess +import tempfile from dataclasses import dataclass from pathlib import Path @@ -256,6 +259,228 @@ def docker_inspect_restart_count(container_id: str) -> int: return 0 +# --- Update engine: pull, image-ref rewrite, readiness, digests ----- + +def compose_pull( + compose_file: Path, *, profile: str | None = None, + services: list[str] | None = None, +) -> CommandResult: + """``docker compose pull`` the node images before a recreate. + + A plain ``up`` reuses the locally-cached image when only the tag + changed in the compose file, so an explicit pull is required to + actually fetch the target. Pass explicit ``services`` to pull (and + thereby validate) even profile-gated ones (the ``tunnel-sidecar`` in + proxy mode): an update rewrites its image line too, so a missing or + bad target tag must be caught here rather than silently leaving an + inactive service pointed at an unpullable image. + """ + args = ["docker", "compose", "-f", str(compose_file)] + if profile: + args.extend(["--profile", profile]) + args.append("pull") + if services: + args.extend(services) + return _run(args, timeout=300) + + +# An ``image:`` line for one of our published node images. Matches a +# bare repo, a tagged ref, or a digest-pinned ref (a prior rollback may +# have left ``greffon/greffer@sha256:...``). The compose template keeps +# each image on its own line with no trailing inline comment, so a +# line-oriented rewrite is safe and avoids a YAML round-trip that would +# reorder keys / strip comments. +_IMAGE_LINE_RE = re.compile( + r"^(?P\s*image:\s*)" + r"(?Pgreffon/[A-Za-z0-9._-]+)" + r"(?::[^\s@]+|@sha256:[0-9a-fA-F]+)?" + r"(?P\s*)$" +) + + +def _rewrite_image_lines(text: str, resolve) -> tuple[str, dict[str, str]]: + """Rewrite every ``greffon/*`` image line via ``resolve(repo, old_ref)``. + + ``resolve`` returns the new full ref (e.g. ``greffon/greffer:0.3.4`` + or ``greffon/greffer@sha256:...``) or ``None`` to leave the line + unchanged. Returns ``(new_text, old_refs)`` where ``old_refs`` maps + repo -> the full ref that was there before (for rollback). + """ + out: list[str] = [] + old_refs: dict[str, str] = {} + for line in text.splitlines(keepends=True): + nl = "\n" if line.endswith("\n") else "" + m = _IMAGE_LINE_RE.match(line.rstrip("\n")) + if not m: + out.append(line) + continue + repo = m.group("repo") + old_full = m.group("indent").strip() and line.strip()[len("image:"):].strip() + old_refs[repo] = old_full or repo + new_ref = resolve(repo, old_refs[repo]) + if new_ref is None: + out.append(line) + else: + out.append(f"{m.group('indent')}{new_ref}{nl}") + return "".join(out), old_refs + + +def _atomic_write(path: Path, text: str) -> None: + fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.name}.tmp.") + tmp_path = Path(tmp) + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write(text) + os.replace(tmp_path, path) + except Exception: + try: + tmp_path.unlink() + except FileNotFoundError: + pass + raise + + +def set_image_tag(compose_file: Path, target: str) -> dict[str, str]: + """Rewrite **every** ``greffon/*`` image line to ``:``. + + Covers greffer + greffer-nginx + the profile-gated tunnel-sidecar: + the set is derived from the file, not a hard-coded count, so a node + update retags the whole node whatever the mode renders. Returns the + map of repo -> prior full ref, so a rollback can restore the exact + refs that were there before (`set_image_refs`). + """ + text = compose_file.read_text(encoding="utf-8") + new_text, old_refs = _rewrite_image_lines( + text, lambda repo, _old: f"{repo}:{target}", + ) + _atomic_write(compose_file, new_text) + return old_refs + + +def set_image_refs(compose_file: Path, refs: dict[str, str]) -> None: + """Rewrite ``greffon/*`` image lines to the given full refs. + + ``refs`` maps repo -> full image ref (tag or digest). Lines whose + repo is absent from ``refs`` are left untouched. Used by rollback to + restore captured prior refs, pinning active services to their + captured running digest where a moved tag would otherwise resolve + to the bad image. + """ + text = compose_file.read_text(encoding="utf-8") + new_text, _ = _rewrite_image_lines( + text, lambda repo, _old: refs.get(repo), + ) + _atomic_write(compose_file, new_text) + + +# A compose short-syntax volume mount onto /data: ``- :/data[:opts]``. +_DATA_MOUNT_RE = re.compile(r"^\s*-\s*(?P[^\s:]+):/data(?::[a-zA-Z,]+)?\s*$") + + +def data_volume_is_named(compose_file: Path) -> bool: + """Pre-flight: is /data backed by a NAMED volume (not a bind / nothing)? + + A named volume (``greffon-data:/data``) survives a container recreate, + which is what keeps the persisted token / TLS key / migration ledger + and so the greffer's identity. A bind mount (``/host/path:/data``) or + no /data mount at all fails this check: an update that recreates the + container would otherwise drop identity and `409` on re-register. + + The discriminator without a YAML dependency: a named-volume source is + a bare name (no path separator, not relative/absolute/home), whereas a + bind-mount source is a path. The CLI always renders the short syntax, + so a line match is sufficient and avoids a YAML round-trip. + """ + try: + text = compose_file.read_text(encoding="utf-8") + except OSError: + return False + for line in text.splitlines(): + m = _DATA_MOUNT_RE.match(line) + if m: + src = m.group("src") + return "/" not in src and not src.startswith((".", "~")) + return False + + +def exec_in_greffer_readyz(compose_file: Path) -> CommandResult: + """Probe ``/readyz`` from inside the greffer container, returning its body. + + Unlike ``exec_in_greffer_healthz`` (which only maps a 200 to exit 0), + this returns the parsed-able JSON body on stdout so the caller can + read ``id`` / ``status`` / ``reasons``. ``/readyz`` is authed, so the + probe resolves ``X-GREFFON-TOKEN`` the way the service does (env + ``GREFFER_TOKEN`` then the persisted ``/data/.greffer-token``) and + sends it. The token never leaves the container: the CLI only reads + the response body. Exit 0 on any HTTP response (200 or 503 — both + carry a JSON body the caller inspects); non-zero on a connection + error so the caller keeps polling. + """ + probe = ( + "import sys, os, urllib.request, urllib.error\n" + "tok = os.environ.get('GREFFER_TOKEN')\n" + "if not tok:\n" + " try:\n" + " tok = open('/data/.greffer-token', encoding='utf-8').read().strip()\n" + " except OSError:\n" + " tok = ''\n" + "req = urllib.request.Request(\n" + " 'http://localhost:8000/readyz',\n" + " headers={'X-GREFFON-TOKEN': tok},\n" + ")\n" + "try:\n" + " r = urllib.request.urlopen(req, timeout=5)\n" + " sys.stdout.write(r.read().decode()); sys.exit(0)\n" + "except urllib.error.HTTPError as e:\n" + " sys.stdout.write(e.read().decode()); sys.exit(0)\n" + "except urllib.error.URLError:\n" + " sys.exit(1)\n" + ) + return _run( + [ + "docker", "compose", "-f", str(compose_file), + "exec", "-T", "greffer", + "python", "-c", probe, + ], + timeout=15, + ) + + +def image_id(ref: str) -> str | None: + """Return the content image ID (``sha256:...``) of an image ref, or None. + + Used to (a) verify the recreate actually advanced to the pulled + target — the running greffer's image ID must equal the target ref's + image ID — and (b) detect a no-op recreate (image ID unchanged from + the captured prior). + """ + result = _run( + ["docker", "image", "inspect", ref, "--format", "{{.Id}}"], timeout=10, + ) + if not result.ok: + return None + out = result.stdout.strip() + return out or None + + +def container_image_id(compose_file: Path, service: str) -> str | None: + """Return the image ID the named compose service's container is running.""" + cid = _run( + ["docker", "compose", "-f", str(compose_file), "ps", "-q", service], + timeout=10, + ) + if not cid.ok or not cid.stdout.strip(): + return None + result = _run( + ["docker", "inspect", cid.stdout.strip(), "--format", "{{.Image}}"], + timeout=10, + ) + if not result.ok: + return None + out = result.stdout.strip() + return out or None + + def host_port_free(port: int) -> bool: """Doctor: is the given host port available for nginx to bind?""" import socket diff --git a/cli/tests/test_compose.py b/cli/tests/test_compose.py index 9b53df93..2c900a9b 100644 --- a/cli/tests/test_compose.py +++ b/cli/tests/test_compose.py @@ -103,3 +103,161 @@ def test_compose_services_running_tolerates_warning_line( ) services = compose.compose_services_running(Path("/tmp/compose.yml")) assert services == {"greffer": True} + + +# --- Update engine helpers ------------------------------------------- + +_SAMPLE_COMPOSE = """\ +version: "3.8" +name: greffer +services: + greffer: + image: greffon/greffer:0.3.3 + restart: unless-stopped + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - greffon-data:/data + nginx: + image: greffon/greffer-nginx:0.3.3 + tunnel-sidecar: + image: greffon/tunnel-sidecar:0.3.3 + profiles: ["tunnel"] + other: + image: postgres:16 +volumes: + greffon-data: +""" + + +def test_compose_pull_args(monkeypatch: pytest.MonkeyPatch) -> None: + captured: dict[str, list[str]] = {} + monkeypatch.setattr( + compose, "_run", + lambda args, *, timeout=None: ( + captured.update(args=list(args)) + or compose.CommandResult(0, "", "") + ), + ) + compose.compose_pull( + Path("/tmp/c.yml"), profile="tunnel", + services=["greffer", "nginx", "tunnel-sidecar"], + ) + a = captured["args"] + assert a[:4] == ["docker", "compose", "-f", "/tmp/c.yml"] + assert "--profile" in a and a[a.index("--profile") + 1] == "tunnel" + assert a[a.index("pull") + 1:] == ["greffer", "nginx", "tunnel-sidecar"] + + +def test_set_image_tag_rewrites_all_greffon_images(tmp_path: Path) -> None: + f = tmp_path / "docker-compose.yml" + f.write_text(_SAMPLE_COMPOSE, encoding="utf-8") + old = compose.set_image_tag(f, "0.3.4") + out = f.read_text(encoding="utf-8") + # every greffon/* image is now :0.3.4 + assert "image: greffon/greffer:0.3.4" in out + assert "image: greffon/greffer-nginx:0.3.4" in out + assert "image: greffon/tunnel-sidecar:0.3.4" in out + # non-greffon image untouched + assert "image: postgres:16" in out + # prior refs returned for rollback + assert old == { + "greffon/greffer": "greffon/greffer:0.3.3", + "greffon/greffer-nginx": "greffon/greffer-nginx:0.3.3", + "greffon/tunnel-sidecar": "greffon/tunnel-sidecar:0.3.3", + } + + +def test_set_image_tag_rewrites_digest_pinned_ref(tmp_path: Path) -> None: + f = tmp_path / "docker-compose.yml" + f.write_text( + "services:\n greffer:\n" + " image: greffon/greffer@sha256:" + "a" * 64 + "\n", + encoding="utf-8", + ) + old = compose.set_image_tag(f, "0.3.5") + assert "image: greffon/greffer:0.3.5" in f.read_text(encoding="utf-8") + assert old["greffon/greffer"] == "greffon/greffer@sha256:" + "a" * 64 + + +def test_set_image_refs_restores_per_repo(tmp_path: Path) -> None: + f = tmp_path / "docker-compose.yml" + f.write_text(_SAMPLE_COMPOSE, encoding="utf-8") + compose.set_image_tag(f, "0.3.4") + # rollback: pin greffer to a digest, restore the others to their tag + compose.set_image_refs(f, { + "greffon/greffer": "greffon/greffer@sha256:" + "b" * 64, + "greffon/greffer-nginx": "greffon/greffer-nginx:0.3.3", + "greffon/tunnel-sidecar": "greffon/tunnel-sidecar:0.3.3", + }) + out = f.read_text(encoding="utf-8") + assert "image: greffon/greffer@sha256:" + "b" * 64 in out + assert "image: greffon/greffer-nginx:0.3.3" in out + assert "image: greffon/tunnel-sidecar:0.3.3" in out + assert "image: postgres:16" in out # untouched (absent from refs) + + +def test_data_volume_is_named(tmp_path: Path) -> None: + f = tmp_path / "c.yml" + f.write_text(_SAMPLE_COMPOSE, encoding="utf-8") + assert compose.data_volume_is_named(f) is True + + +@pytest.mark.parametrize( + "mount, expected", + [ + (" - greffon-data:/data", True), + (" - greffon-data:/data:rw", True), + (" - /srv/greffer:/data", False), # absolute bind + (" - ./data:/data", False), # relative bind + (" - ~/data:/data", False), # home bind + (" - greffon-data:/other", False), # not /data + ], +) +def test_data_volume_named_vs_bind(tmp_path: Path, mount: str, expected: bool) -> None: + f = tmp_path / "c.yml" + f.write_text("services:\n greffer:\n volumes:\n" + mount + "\n", encoding="utf-8") + assert compose.data_volume_is_named(f) is expected + + +def test_data_volume_absent(tmp_path: Path) -> None: + f = tmp_path / "c.yml" + f.write_text("services:\n greffer:\n image: greffon/greffer:0.3.3\n", encoding="utf-8") + assert compose.data_volume_is_named(f) is False + + +def test_exec_in_greffer_readyz_probe(monkeypatch: pytest.MonkeyPatch) -> None: + captured: dict[str, list[str]] = {} + monkeypatch.setattr( + compose, "_run", + lambda args, *, timeout=None: ( + captured.update(args=list(args)) + or compose.CommandResult(0, '{"id":"x","status":"ready","reasons":[]}', "") + ), + ) + compose.exec_in_greffer_readyz(Path("/tmp/c.yml")) + a = captured["args"] + assert a[:7] == [ + "docker", "compose", "-f", "/tmp/c.yml", "exec", "-T", "greffer", + ] + probe = a[-1] + assert "/readyz" in probe + assert "X-GREFFON-TOKEN" in probe + assert "/data/.greffer-token" in probe + + +def test_image_id_and_container_image_id(monkeypatch: pytest.MonkeyPatch) -> None: + calls: list[list[str]] = [] + + def fake_run(args, *, timeout=None): + calls.append(list(args)) + if args[:3] == ["docker", "image", "inspect"]: + return compose.CommandResult(0, "sha256:deadbeef\n", "") + if args[:5] == ["docker", "compose", "-f", "/tmp/c.yml", "ps"]: + return compose.CommandResult(0, "container123\n", "") + if args[:2] == ["docker", "inspect"]: + return compose.CommandResult(0, "sha256:cafe\n", "") + return compose.CommandResult(1, "", "unexpected") + + monkeypatch.setattr(compose, "_run", fake_run) + assert compose.image_id("greffon/greffer:0.3.4") == "sha256:deadbeef" + assert compose.container_image_id(Path("/tmp/c.yml"), "greffer") == "sha256:cafe" From ebf29bee8ef358658f3a4f004344b2bc12b7ca6e Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Mon, 15 Jun 2026 15:01:27 +0200 Subject: [PATCH 2/8] feat(cli): `greffer update` engine + command (resolve, pre-flight, pull, recreate, /readyz gate, rollback) Increment 2 of the v1 update engine (design greffon#165). The 5-step host-side update: - update.py: HTTPS-only manifest fetch + target resolution (--to > manifest latest); no_rollback_from gate (reachable-but-silent manifest = rollback-safe; unreachable = needs --confirm-no-rollback); pre-flight /data named-volume check; snapshot via set_image_tag (prior refs) -> compose_pull (all node images incl the profile-gated sidecar) -> compose_up; health gate (/healthz live -> /readyz ready + id match + version-applied + all active services up; restart-count fail-fast); rollback restores prior refs and recreates from local cache (exit 1 rolled-back / 2 rollback-failed). Idempotent by running-image digest. --check is read-only. - compose.py: service_container_id + exec_greffer_version helpers. - main.py: `greffer update [--to] [--check] [--timeout] [--config-dir] [--confirm-no-rollback]`. - strings.py: operator-facing update strings (marketing review pending at PR time). - tests: 14 update tests (pure logic + engine paths via a FakeDocker harness, no Docker). Full CLI suite: 119 passed. Next: manager-side update_available/latest_version (Feature 1), cli-e2e, PR. Co-Authored-By: Claude Opus 4.8 --- cli/greffer_cli/compose.py | 37 +++- cli/greffer_cli/main.py | 42 +++++ cli/greffer_cli/strings.py | 55 ++++++ cli/greffer_cli/update.py | 358 +++++++++++++++++++++++++++++++++++++ cli/tests/test_update.py | 270 ++++++++++++++++++++++++++++ 5 files changed, 758 insertions(+), 4 deletions(-) create mode 100644 cli/greffer_cli/update.py create mode 100644 cli/tests/test_update.py diff --git a/cli/greffer_cli/compose.py b/cli/greffer_cli/compose.py index 8bda634b..1412edc9 100644 --- a/cli/greffer_cli/compose.py +++ b/cli/greffer_cli/compose.py @@ -463,16 +463,45 @@ def image_id(ref: str) -> str | None: return out or None -def container_image_id(compose_file: Path, service: str) -> str | None: - """Return the image ID the named compose service's container is running.""" +def service_container_id(compose_file: Path, service: str) -> str | None: + """Return the running container id for a compose service, or None.""" cid = _run( ["docker", "compose", "-f", str(compose_file), "ps", "-q", service], timeout=10, ) - if not cid.ok or not cid.stdout.strip(): + if not cid.ok: + return None + out = cid.stdout.strip() + return out or None + + +def container_image_id(compose_file: Path, service: str) -> str | None: + """Return the image ID the named compose service's container is running.""" + cid = service_container_id(compose_file, service) + if not cid: + return None + result = _run( + ["docker", "inspect", cid, "--format", "{{.Image}}"], timeout=10, + ) + if not result.ok: return None + out = result.stdout.strip() + return out or None + + +def exec_greffer_version(compose_file: Path) -> str | None: + """Read the running greffer's ``app.__version__`` via ``docker exec``. + + This is the value the greffer reports to the manager as + ``Greffer.version`` (see app/settings.py), so it is what the update's + "did the version actually advance" check and the ``no_rollback_from`` + current->target pair compare against. + """ result = _run( - ["docker", "inspect", cid.stdout.strip(), "--format", "{{.Image}}"], + [ + "docker", "compose", "-f", str(compose_file), "exec", "-T", "greffer", + "python", "-c", "import app; print(app.__version__)", + ], timeout=10, ) if not result.ok: diff --git a/cli/greffer_cli/main.py b/cli/greffer_cli/main.py index a89b4876..40ab15bf 100644 --- a/cli/greffer_cli/main.py +++ b/cli/greffer_cli/main.py @@ -17,6 +17,7 @@ from . import status as status_mod from . import strings as strings_mod from . import up as up_mod +from . import update as update_mod app = typer.Typer( @@ -203,6 +204,47 @@ def up( raise typer.Exit(code=rc) +@app.command() +def update( + to: Optional[str] = typer.Option( + None, "--to", help="Target version tag (default: latest from the manifest)", + ), + check: bool = typer.Option( + False, "--check", help="Read-only: print current/target/available, change nothing", + ), + timeout: int = typer.Option( + 600, "--timeout", help="Health-gate timeout in seconds (default 10 min)", + ), + config_dir: Optional[str] = typer.Option( + None, "--config-dir", help="Override the default ~/.greffer/ location", + ), + confirm_no_rollback: bool = typer.Option( + False, "--confirm-no-rollback", + help="Proceed even if rollback safety for this version pair can't be confirmed", + ), +) -> None: + """Update the greffer node to a newer published image. + + Pulls the target, recreates the node, health-gates on /readyz, and + rolls back to the previous version on any failure. + """ + cfg = paths.resolve_config_dir(config_dir) + if not paths.docker_compose_yml_path(cfg).exists(): + typer.echo( + "no greffer install found here — run `greffer up` first.", err=True, + ) + raise typer.Exit(code=update_mod.EXIT_PREFLIGHT_REFUSED) + rc = update_mod.run_update( + cfg, + target=to, + timeout=float(timeout), + confirm_no_rollback=confirm_no_rollback, + check_only=check, + ) + if rc != update_mod.EXIT_OK: + raise typer.Exit(code=rc) + + @app.command() def status( config_dir: Optional[str] = typer.Option( diff --git a/cli/greffer_cli/strings.py b/cli/greffer_cli/strings.py index 09f094e1..594d0192 100644 --- a/cli/greffer_cli/strings.py +++ b/cli/greffer_cli/strings.py @@ -277,3 +277,58 @@ "⚠ reachable but greffer is not responding cleanly; " "try `docker compose logs greffer`." ) + + +# --- greffer update -------------------------------------------------- + +UPDATE_NO_TARGET = ( + "✗ Can't determine the latest greffer version (the version manifest is " + "unreachable).\n → re-run with an explicit target: `greffer update --to `" +) + +UPDATE_CHECK = """\ +greffer update --check + current: {current} + target: {target} + available: {available} +(no changes made) +""" + +UPDATE_PREFLIGHT_NO_DATA_VOLUME = ( + "✗ Refusing to update: /data is not a persistent named volume.\n" + " An update recreates the container; without a named /data volume the\n" + " greffer would lose its identity and fail to re-register. Fix the\n" + " docker-compose.yml /data mount (or re-run `greffer up`) and try again." +) + +UPDATE_NEEDS_CONFIRM_NO_ROLLBACK = ( + "✗ Rollback safety for {current} → {target} can't be confirmed " + "(the release is flagged no-in-place-rollback, or the version manifest is " + "unreachable).\n → re-run with `--confirm-no-rollback` to proceed anyway." +) + +UPDATE_ALREADY = "✓ Already up to date (running {target}). Nothing to do." + +UPDATE_PULL_FAILED = ( + "✗ Couldn't pull the {target} images. The compose file was restored and " + "the greffer is still running its previous version. Check connectivity to " + "the image registry and retry." +) + +UPDATE_OK = "✓ Updated to {target}. The greffer re-registered and is ready." + +UPDATE_GATE_FAILED = ( + "✗ The {reason} check failed after recreate — rolling back to the previous " + "version." +) + +UPDATE_ROLLED_BACK = ( + "✓ Rolled back to the previous version, which is healthy. The update did " + "not apply; see the logs above for why." +) + +UPDATE_ROLLBACK_FAILED = ( + "✗ The update failed AND the rollback did not come back healthy. Manual " + "recovery needed: inspect `docker compose -f {compose_path} ps` and logs, " + "then re-run `greffer up` once the cause is fixed." +) diff --git a/cli/greffer_cli/update.py b/cli/greffer_cli/update.py new file mode 100644 index 00000000..bc31f726 --- /dev/null +++ b/cli/greffer_cli/update.py @@ -0,0 +1,358 @@ +"""``greffer update`` — update a running greffer node to a newer image. + +Five-step engine (design: greffon docs/features/greffer-self-update, +merged greffon#165): + + 1. resolve the target tag (--to > manifest latest) + 2. pre-flight (persistent /data volume, rollback-safety gate) + 3. rewrite every greffon/* image line -> target, pull, recreate + 4. health-gate (/healthz live -> /readyz ready + id + version applied + + all active services running; restart-count fail-fast) + 5. roll back to the prior refs on any failure (the authority) + +Mirrors up.py's structure. The compose layer (compose.py) is called +directly so tests monkeypatch it; ``sleep`` is injected so the polling +loop is testable without real waits. No Docker is needed for the unit +tests. +""" + +from __future__ import annotations + +import dataclasses +import json +import sys +import time +import urllib.error +import urllib.request +from pathlib import Path +from typing import Callable + +from . import compose, env_file, paths, strings + +# The published node images this engine retags, pulls, and recreates +# together. greffer-cli pins all three to the same in the rendered +# compose, so a node update moves the whole node. +GREFFER_REPO = "greffon/greffer" +NGINX_REPO = "greffon/greffer-nginx" +SIDECAR_REPO = "greffon/tunnel-sidecar" +SERVICE_REPO = { + "greffer": GREFFER_REPO, + "nginx": NGINX_REPO, + "tunnel-sidecar": SIDECAR_REPO, +} + +DEFAULT_MANIFEST_URL = "https://greffon.io/greffer-version.json" + +# Exit codes (subcommand-specific; see HLD § "v1 CLI surface"). +EXIT_OK = 0 # success or no-op +EXIT_FAILED_ROLLED_BACK = 1 # update failed, rolled back cleanly +EXIT_FAILED_ROLLBACK_FAILED = 2 # update failed AND rollback failed +EXIT_PREFLIGHT_REFUSED = 3 # refused before any pull + +# Health-gate outcomes. +GATE_READY = "ready" +GATE_TIMEOUT = "timeout" +GATE_FATAL = "fatal" +GATE_WRONG_ID = "wrong_id" +GATE_NOT_APPLIED = "not_applied" +GATE_DEGRADED_OTHER = "degraded_other" +GATE_CRASH_LOOP = "crash_loop" + + +# --- Version manifest ------------------------------------------------ + +@dataclasses.dataclass +class Manifest: + latest: str | None = None + min_supported: str | None = None + no_rollback_from: list[str] = dataclasses.field(default_factory=list) + + +def fetch_manifest( + url: str = DEFAULT_MANIFEST_URL, *, timeout: float = 10.0, +) -> Manifest | None: + """GET the version manifest over HTTPS. Returns ``None`` if unreachable + or malformed — the caller treats that as "unknown", not a hard error.""" + if not url.startswith("https://"): + # The manifest carries update targets; never fetch it over plaintext. + return None + try: + # https-only is enforced by the guard above. + with urllib.request.urlopen(url, timeout=timeout) as r: + body = r.read().decode("utf-8") + except (urllib.error.URLError, OSError, ValueError): + return None + try: + data = json.loads(body) + except json.JSONDecodeError: + return None + if not isinstance(data, dict): + return None + nrf = data.get("no_rollback_from") or [] + if not isinstance(nrf, list): + nrf = [] + return Manifest( + latest=data.get("latest"), + min_supported=data.get("min_supported"), + no_rollback_from=[str(x) for x in nrf], + ) + + +def resolve_target( + *, explicit_to: str | None, manifest: Manifest | None, +) -> str | None: + """Resolve the target tag. ``--to`` wins; else the manifest's latest; + else ``None`` (auto-latest with an unreachable manifest -> abort).""" + if explicit_to: + return explicit_to + if manifest and manifest.latest: + return manifest.latest + return None + + +def no_rollback_blocked( + manifest: Manifest | None, current: str | None, target: str, +) -> bool | None: + """Is current->target flagged "no in-place rollback"? + + ``True`` = the pair is listed (blocked; needs --confirm-no-rollback). + ``False`` = manifest reachable and the pair is absent => rollback-safe. + ``None`` = unknown (manifest unreachable, or current version unknown). + """ + if manifest is None or current is None: + return None + return f"{current}->{target}" in manifest.no_rollback_from + + +# --- /readyz parsing ------------------------------------------------- + +@dataclasses.dataclass +class Readiness: + ok: bool # got an HTTP response with a JSON body + id: str | None + status: str | None # "ready" | "degraded" | "fatal" + reasons: list[str] + + +def parse_readyz(result: compose.CommandResult) -> Readiness: + if not result.ok: + return Readiness(ok=False, id=None, status=None, reasons=[]) + try: + data = json.loads(result.stdout.strip() or "{}") + except json.JSONDecodeError: + return Readiness(ok=False, id=None, status=None, reasons=[]) + if not isinstance(data, dict): + return Readiness(ok=False, id=None, status=None, reasons=[]) + reasons = data.get("reasons") or [] + if not isinstance(reasons, list): + reasons = [] + return Readiness( + ok=True, id=data.get("id"), status=data.get("status"), + reasons=[str(r) for r in reasons], + ) + + +def active_services(mode: str) -> list[str]: + """Control-plane services the rendered compose runs for the mode. + + nginx runs in both modes; the tunnel-sidecar only under --profile tunnel. + """ + svcs = ["greffer", "nginx"] + if mode == "tunnel": + svcs.append("tunnel-sidecar") + return svcs + + +def profile_for_mode(mode: str) -> str | None: + return "tunnel" if mode == "tunnel" else None + + +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. + """ + running = compose.container_image_id(compose_file, "greffer") + target_id = compose.image_id(f"{GREFFER_REPO}:{target}") + return bool(running and target_id and running == target_id) + + +def health_gate( + compose_file: Path, *, greffer_id: str | None, target: str, + services: list[str], profile: str | None, + timeout: float, poll_interval: float = 2.0, + sleep: Callable[[float], None] = time.sleep, +) -> str: + """Poll until the recreated node is healthy or a failure is decided. + + Success (``GATE_READY``) requires all of: ``/healthz`` live, ``/readyz`` + ``ready`` with matching ``id``, the greffer version actually applied, + and every active service running. ``degraded: registration_pending`` is + awaited (the greffer is re-registering). A non-matching id, a ``fatal``, + any other ``degraded`` reason, a crash-loop, or the timeout fail. + """ + deadline = time.monotonic() + timeout + cid = compose.service_container_id(compose_file, "greffer") + base_restarts = compose.docker_inspect_restart_count(cid) if cid else 0 + while time.monotonic() < deadline: + if compose.exec_in_greffer_healthz(compose_file).ok: + r = parse_readyz(compose.exec_in_greffer_readyz(compose_file)) + if r.ok: + if greffer_id and r.id and r.id != greffer_id: + return GATE_WRONG_ID + if r.status == "fatal": + return GATE_FATAL + if r.status == "degraded" and r.reasons != ["registration_pending"]: + return GATE_DEGRADED_OTHER + if r.status == "ready": + if not _version_applied(compose_file, target): + return GATE_NOT_APPLIED + svcs = compose.compose_services_running( + compose_file, profile=profile, + ) + if svcs and all(svcs.get(s, False) for s in services): + return GATE_READY + # greffer ready but a retagged sibling (nginx / sidecar) + # is not up yet; keep polling, the timeout is the backstop. + # Supplementary fail-fast: a climbing restart count past the + # post-recreate baseline means the new image is crash-looping. + if cid and compose.docker_inspect_restart_count(cid) - base_restarts > 1: + return GATE_CRASH_LOOP + sleep(poll_interval) + return GATE_TIMEOUT + + +def _rollback( + compose_file: Path, *, profile: str | None, services: list[str], + old_refs: dict[str, str], greffer_id: str | None, + timeout: float, sleep: Callable[[float], None], +) -> int: + """Restore the prior image refs and recreate. The prior images are still + cached locally (we only pulled the target tag, never re-pulled the prior), + so restoring the refs + ``up`` (no pull) brings the exact prior node back. + + Returns ``EXIT_FAILED_ROLLED_BACK`` if the rolled-back node is healthy, + else ``EXIT_FAILED_ROLLBACK_FAILED`` (no loop, manual recovery).""" + compose.set_image_refs(compose_file, old_refs) + up = compose.compose_up(compose_file, profile=profile) + if up.ok and _rollback_health( + compose_file, services=services, profile=profile, + greffer_id=greffer_id, timeout=min(timeout, 120.0), sleep=sleep, + ): + print(strings.UPDATE_ROLLED_BACK, file=sys.stderr) + return EXIT_FAILED_ROLLED_BACK + print(strings.UPDATE_ROLLBACK_FAILED.format(compose_path=compose_file), file=sys.stderr) + return EXIT_FAILED_ROLLBACK_FAILED + + +def _rollback_health( + compose_file: Path, *, services: list[str], profile: str | None, + greffer_id: str | None, timeout: float, + sleep: Callable[[float], None], +) -> bool: + """Confirm the rolled-back node reaches /readyz ready + all services up. + No version check (rollback restores the prior version, not the target).""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if compose.exec_in_greffer_healthz(compose_file).ok: + r = parse_readyz(compose.exec_in_greffer_readyz(compose_file)) + if r.ok and r.status == "ready" and not ( + greffer_id and r.id and r.id != greffer_id + ): + svcs = compose.compose_services_running(compose_file, profile=profile) + if svcs and all(svcs.get(s, False) for s in services): + return True + sleep(2.0) + return False + + +def run_update( + cfg: Path, *, + target: str | None = None, + manifest_url: str = DEFAULT_MANIFEST_URL, + timeout: float = 600.0, + confirm_no_rollback: bool = False, + check_only: bool = False, + sleep: Callable[[float], None] = time.sleep, +) -> int: + """Drive the update. Returns one of the EXIT_* codes.""" + compose_file = paths.docker_compose_yml_path(cfg) + env = env_file.EnvFile.read(paths.env_env_path(cfg)) + greffer_id = env.get("GREFFER_ID") + mode = env.get("GREFFER_MODE") or "tunnel" + profile = profile_for_mode(mode) + services = active_services(mode) + + # ---- 1. Resolve target ------------------------------------------- + manifest = fetch_manifest(manifest_url) + resolved = resolve_target(explicit_to=target, manifest=manifest) + current_version = compose.exec_greffer_version(compose_file) + if resolved is None: + print(strings.UPDATE_NO_TARGET, file=sys.stderr) + return EXIT_PREFLIGHT_REFUSED + + if check_only: + behind = ( + current_version is not None + and resolved != current_version + ) + print(strings.UPDATE_CHECK.format( + current=current_version or "unknown", target=resolved, + available=("yes" if behind else "no/unknown"), + )) + return EXIT_OK + + # ---- 2. Pre-flight (abort before any pull) ----------------------- + if not compose.data_volume_is_named(compose_file): + print(strings.UPDATE_PREFLIGHT_NO_DATA_VOLUME, file=sys.stderr) + return EXIT_PREFLIGHT_REFUSED + + blocked = no_rollback_blocked(manifest, current_version, resolved) + if blocked is not False and not confirm_no_rollback: + # listed (True) or unknown (None) -> require explicit confirmation + print(strings.UPDATE_NEEDS_CONFIRM_NO_ROLLBACK.format( + current=current_version or "unknown", target=resolved, + ), file=sys.stderr) + return EXIT_PREFLIGHT_REFUSED + + # Idempotency: already running the target image? (digest compare, so it + # holds even if a prior rollback left the compose digest-pinned.) + running_id = compose.container_image_id(compose_file, "greffer") + target_id = compose.image_id(f"{GREFFER_REPO}:{resolved}") + if running_id and target_id and running_id == target_id: + print(strings.UPDATE_ALREADY.format(target=resolved)) + return EXIT_OK + + # ---- 3. Rewrite + pull + recreate -------------------------------- + old_refs = compose.set_image_tag(compose_file, resolved) + pull = compose.compose_pull(compose_file, profile=profile, services=services) + if not pull.ok: + # No recreate happened; restore the prior refs so a later `up` + # can't recreate into the unvalidated target. Old containers run on. + compose.set_image_refs(compose_file, old_refs) + print(strings.UPDATE_PULL_FAILED.format(target=resolved), file=sys.stderr) + return EXIT_FAILED_ROLLED_BACK + up = compose.compose_up(compose_file, profile=profile) + if not up.ok: + return _rollback( + compose_file, profile=profile, services=services, + old_refs=old_refs, greffer_id=greffer_id, timeout=timeout, sleep=sleep, + ) + + # ---- 4. Health-gate ---------------------------------------------- + outcome = health_gate( + compose_file, greffer_id=greffer_id, target=resolved, + services=services, profile=profile, timeout=timeout, sleep=sleep, + ) + if outcome == GATE_READY: + print(strings.UPDATE_OK.format(target=resolved)) + return EXIT_OK + + # ---- 5. Rollback (the authority) --------------------------------- + print(strings.UPDATE_GATE_FAILED.format(reason=outcome), file=sys.stderr) + return _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_update.py b/cli/tests/test_update.py new file mode 100644 index 00000000..63d4adeb --- /dev/null +++ b/cli/tests/test_update.py @@ -0,0 +1,270 @@ +"""Tests for greffer_cli.update — the `greffer update` engine. + +The compose layer is monkeypatched (no Docker) and ``sleep`` is stubbed +so the polling loops run instantly. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from greffer_cli import compose, update + + +def _ok(stdout: str = "") -> compose.CommandResult: + return compose.CommandResult(returncode=0, stdout=stdout, stderr="") + + +def _fail() -> compose.CommandResult: + return compose.CommandResult(returncode=1, stdout="", stderr="boom") + + +_COMPOSE = """\ +version: "3.8" +name: greffer +services: + greffer: + image: greffon/greffer:0.3.3 + volumes: + - greffon-data:/data + nginx: + image: greffon/greffer-nginx:0.3.3 + tunnel-sidecar: + image: greffon/tunnel-sidecar:0.3.3 + profiles: ["tunnel"] +volumes: + greffon-data: +""" + + +# --- pure logic ------------------------------------------------------ + +def test_resolve_target_precedence() -> None: + m = update.Manifest(latest="0.3.5") + assert update.resolve_target(explicit_to="0.3.9", manifest=m) == "0.3.9" + assert update.resolve_target(explicit_to=None, manifest=m) == "0.3.5" + assert update.resolve_target(explicit_to=None, manifest=None) is None + assert update.resolve_target(explicit_to=None, manifest=update.Manifest()) is None + + +def test_no_rollback_blocked() -> None: + m = update.Manifest(no_rollback_from=["0.3.3->0.3.4"]) + assert update.no_rollback_blocked(m, "0.3.3", "0.3.4") is True # listed + assert update.no_rollback_blocked(m, "0.3.3", "0.3.5") is False # reachable, absent => safe + assert update.no_rollback_blocked(None, "0.3.3", "0.3.4") is None # unreachable + assert update.no_rollback_blocked(m, None, "0.3.4") is None # current unknown + + +def test_parse_readyz() -> None: + ready = update.parse_readyz(_ok(json.dumps({"id": "g1", "status": "ready", "reasons": []}))) + assert ready.ok and ready.id == "g1" and ready.status == "ready" + deg = update.parse_readyz(_ok(json.dumps({"id": "g1", "status": "degraded", "reasons": ["registration_pending"]}))) + assert deg.status == "degraded" and deg.reasons == ["registration_pending"] + bad = update.parse_readyz(_fail()) + assert not bad.ok + assert not update.parse_readyz(_ok("not json")).ok + + +def test_active_services() -> None: + assert update.active_services("proxy") == ["greffer", "nginx"] + assert update.active_services("tunnel") == ["greffer", "nginx", "tunnel-sidecar"] + + +def test_fetch_manifest_rejects_plaintext() -> None: + assert update.fetch_manifest("http://greffon.io/x.json") is None + + +# --- FakeDocker harness ---------------------------------------------- + +class FakeDocker: + def __init__(self) -> None: + self.running_image = "sha256:OLD" + self.target_image = "sha256:NEW" + self.readyz = {"id": "g1", "status": "ready", "reasons": []} + self.pull_ok = True + self.up_ok = True + self.services_up = True + self.restart = 0 + self.healthz_ok = True + + def install(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(compose, "exec_greffer_version", lambda f: "0.3.3") + monkeypatch.setattr(compose, "container_image_id", lambda f, s: self.running_image) + monkeypatch.setattr(compose, "image_id", lambda ref: self.target_image) + monkeypatch.setattr(compose, "service_container_id", lambda f, s: "cid") + monkeypatch.setattr(compose, "docker_inspect_restart_count", lambda c: self.restart) + monkeypatch.setattr( + compose, "exec_in_greffer_healthz", + lambda f: _ok() if self.healthz_ok else _fail(), + ) + monkeypatch.setattr( + compose, "exec_in_greffer_readyz", + lambda f: _ok(json.dumps(self.readyz)), + ) + monkeypatch.setattr( + compose, "compose_services_running", + lambda f, *, profile=None: { + s: self.services_up for s in ("greffer", "nginx", "tunnel-sidecar") + }, + ) + monkeypatch.setattr( + compose, "compose_pull", + lambda f, *, profile=None, services=None: _ok() if self.pull_ok else _fail(), + ) + + def fake_up(f, *, profile=None): + # a successful recreate advances the running image to the target + if self.up_ok: + self.running_image = self.target_image + return _ok() + return _fail() + + monkeypatch.setattr(compose, "compose_up", fake_up) + monkeypatch.setattr( + update, "fetch_manifest", lambda url, timeout=10.0: update.Manifest(latest="0.3.4"), + ) + + +@pytest.fixture +def cfg(tmp_path: Path) -> Path: + (tmp_path / "docker-compose.yml").write_text(_COMPOSE, encoding="utf-8") + (tmp_path / "env.env").write_text( + 'GREFFER_ID="g1"\nGREFFER_MODE="proxy"\n', encoding="utf-8", + ) + return tmp_path + + +def _run(cfg: Path, **kw) -> int: + kw.setdefault("sleep", lambda _s: None) + return update.run_update(cfg, **kw) + + +# --- engine paths ---------------------------------------------------- + +def test_happy_path(cfg: Path, monkeypatch: pytest.MonkeyPatch, capsys) -> None: + FakeDocker().install(monkeypatch) + rc = _run(cfg, target="0.3.4") + assert rc == update.EXIT_OK + assert "Updated to 0.3.4" in capsys.readouterr().out + # compose file was retagged to the target + assert "greffon/greffer:0.3.4" in (cfg / "docker-compose.yml").read_text() + + +def test_check_only_changes_nothing(cfg: Path, monkeypatch: pytest.MonkeyPatch, capsys) -> None: + FakeDocker().install(monkeypatch) + before = (cfg / "docker-compose.yml").read_text() + rc = _run(cfg, target="0.3.4", check_only=True) + assert rc == update.EXIT_OK + assert (cfg / "docker-compose.yml").read_text() == before # untouched + assert "no changes made" in capsys.readouterr().out + + +def test_idempotent_when_already_target(cfg: Path, monkeypatch: pytest.MonkeyPatch, capsys) -> None: + fd = FakeDocker() + fd.running_image = "sha256:SAME" + fd.target_image = "sha256:SAME" # running already == target + fd.install(monkeypatch) + rc = _run(cfg, target="0.3.4") + assert rc == update.EXIT_OK + assert "Already up to date" in capsys.readouterr().out + + +def test_preflight_refuses_without_named_data_volume(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + # /data is a bind mount, not a named volume + (tmp_path / "docker-compose.yml").write_text( + "services:\n greffer:\n image: greffon/greffer:0.3.3\n" + " volumes:\n - /srv/greffer:/data\n", + encoding="utf-8", + ) + (tmp_path / "env.env").write_text('GREFFER_ID="g1"\nGREFFER_MODE="proxy"\n', encoding="utf-8") + FakeDocker().install(monkeypatch) + assert _run(tmp_path, target="0.3.4") == update.EXIT_PREFLIGHT_REFUSED + + +def test_pull_failure_restores_compose_and_reports(cfg: Path, monkeypatch: pytest.MonkeyPatch) -> None: + fd = FakeDocker() + fd.pull_ok = False + fd.install(monkeypatch) + rc = _run(cfg, target="0.3.4") + assert rc == update.EXIT_FAILED_ROLLED_BACK + # compose restored to the prior tag (no recreate happened) + text = (cfg / "docker-compose.yml").read_text() + assert "greffon/greffer:0.3.3" in text + assert "greffon/greffer:0.3.4" not in text + + +def test_gate_fatal_rolls_back(cfg: Path, monkeypatch: pytest.MonkeyPatch) -> None: + fd = FakeDocker() + fd.install(monkeypatch) + # After recreate, /readyz reports fatal; rollback then comes up healthy. + calls = {"n": 0} + orig_readyz = {"fatal": {"id": "g1", "status": "fatal", "reasons": ["docker_unreachable"]}, + "ready": {"id": "g1", "status": "ready", "reasons": []}} + + def staged_readyz(f): + # first poll: fatal (the update); after rollback recreate: ready + return _ok(json.dumps(orig_readyz["ready" if fd.running_image == "sha256:OLD" else "fatal"])) + + # rollback restores old image (set_image_refs writes prior tag; we model + # the running image flipping back to OLD on the rollback compose_up). + def fake_up(f, *, profile=None): + # forward recreate -> NEW; rollback recreate -> OLD (refs restored) + text = (cfg / "docker-compose.yml").read_text() + fd.running_image = "sha256:NEW" if "greffon/greffer:0.3.4" in text else "sha256:OLD" + return _ok() + + monkeypatch.setattr(compose, "compose_up", fake_up) + monkeypatch.setattr(compose, "exec_in_greffer_readyz", staged_readyz) + rc = _run(cfg, target="0.3.4") + assert rc == update.EXIT_FAILED_ROLLED_BACK + # ended back on the prior tag + assert "greffon/greffer:0.3.3" in (cfg / "docker-compose.yml").read_text() + + +def test_needs_confirm_when_rollback_unknown(cfg: Path, monkeypatch: pytest.MonkeyPatch) -> None: + fd = FakeDocker() + fd.install(monkeypatch) + # manifest unreachable => no_rollback status unknown => needs --confirm + monkeypatch.setattr(update, "fetch_manifest", lambda url, timeout=10.0: None) + assert _run(cfg, target="0.3.4") == update.EXIT_PREFLIGHT_REFUSED + assert _run(cfg, target="0.3.4", confirm_no_rollback=True) == update.EXIT_OK + + +def test_health_gate_waits_through_registration_pending(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + f = tmp_path / "c.yml" + f.write_text(_COMPOSE, encoding="utf-8") + seq = [ + {"id": "g1", "status": "degraded", "reasons": ["registration_pending"]}, + {"id": "g1", "status": "ready", "reasons": []}, + ] + monkeypatch.setattr(compose, "exec_in_greffer_healthz", lambda f: _ok()) + monkeypatch.setattr(compose, "exec_in_greffer_readyz", lambda f: _ok(json.dumps(seq.pop(0) if seq else seq[-1]))) + monkeypatch.setattr(compose, "service_container_id", lambda f, s: "cid") + monkeypatch.setattr(compose, "docker_inspect_restart_count", lambda c: 0) + monkeypatch.setattr(compose, "container_image_id", lambda f, s: "sha256:X") + monkeypatch.setattr(compose, "image_id", lambda ref: "sha256:X") + monkeypatch.setattr(compose, "compose_services_running", lambda f, *, profile=None: {"greffer": True, "nginx": True}) + outcome = update.health_gate( + f, greffer_id="g1", target="0.3.4", services=["greffer", "nginx"], + profile=None, timeout=10.0, poll_interval=0.0, sleep=lambda _s: None, + ) + assert outcome == update.GATE_READY + + +def test_health_gate_version_not_applied(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + f = tmp_path / "c.yml" + f.write_text(_COMPOSE, encoding="utf-8") + monkeypatch.setattr(compose, "exec_in_greffer_healthz", lambda f: _ok()) + monkeypatch.setattr(compose, "exec_in_greffer_readyz", lambda f: _ok(json.dumps({"id": "g1", "status": "ready", "reasons": []}))) + monkeypatch.setattr(compose, "service_container_id", lambda f, s: "cid") + monkeypatch.setattr(compose, "docker_inspect_restart_count", lambda c: 0) + monkeypatch.setattr(compose, "container_image_id", lambda f, s: "sha256:OLD") + monkeypatch.setattr(compose, "image_id", lambda ref: "sha256:NEW") # target != running + outcome = update.health_gate( + f, greffer_id="g1", target="0.3.4", services=["greffer"], + profile=None, timeout=10.0, sleep=lambda _s: None, + ) + assert outcome == update.GATE_NOT_APPLIED From 3974cb168d78093dbe9de1d23632565c77583b2b Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Mon, 15 Jun 2026 15:40:37 +0200 Subject: [PATCH 3/8] fix(greffer-cli): harden update engine after adversarial review Address findings from a pre-PR adversarial review of the `greffer update` v1 engine: - mode resolution: when env.env lacks GREFFER_MODE (hand-edited / legacy install), detect the mode from the running node (tunnel-sidecar present => tunnel) instead of assuming a static default, so the health gate waits on the right service set. Explicit GREFFER_MODE still wins. - pre-flight: refuse the update when GREFFER_ID is missing from env.env, since the post-recreate gate's id-match check would otherwise be a silent no-op (updating blind). - health gate: tolerate degraded reasons via set membership (TOLERABLE_DEGRADED_REASONS) rather than exact-list equality, so a registration_pending paired with any other reason still fails. - compose: enforce the full 64-char sha256 length in the image-line regex; simplify the old-ref extraction (drop a misleading `and`/dead fallback); close the raw fd if os.fdopen raises in _atomic_write. Tests: add the 5 missing health-gate failure outcomes (timeout, fatal, wrong-id, degraded-other, crash-loop), both rollback-failure paths (rollback compose up fails / rollback never healthy => exit 2), mode auto-detection, and the no-GREFFER_ID pre-flight refusal. 129 passing. Co-Authored-By: Claude Opus 4.8 --- cli/greffer_cli/compose.py | 17 ++++- cli/greffer_cli/strings.py | 9 ++- cli/greffer_cli/update.py | 37 +++++++++- cli/tests/test_update.py | 145 +++++++++++++++++++++++++++++++++++++ 4 files changed, 201 insertions(+), 7 deletions(-) diff --git a/cli/greffer_cli/compose.py b/cli/greffer_cli/compose.py index 1412edc9..4544e25c 100644 --- a/cli/greffer_cli/compose.py +++ b/cli/greffer_cli/compose.py @@ -293,7 +293,7 @@ def compose_pull( _IMAGE_LINE_RE = re.compile( r"^(?P\s*image:\s*)" r"(?Pgreffon/[A-Za-z0-9._-]+)" - r"(?::[^\s@]+|@sha256:[0-9a-fA-F]+)?" + r"(?::[^\s@]+|@sha256:[0-9a-fA-F]{64})?" r"(?P\s*)$" ) @@ -315,8 +315,9 @@ def _rewrite_image_lines(text: str, resolve) -> tuple[str, dict[str, str]]: out.append(line) continue repo = m.group("repo") - old_full = m.group("indent").strip() and line.strip()[len("image:"):].strip() - old_refs[repo] = old_full or repo + # The regex guarantees the repo is present, so the ref after + # "image:" is always non-empty, so extract it directly. + old_refs[repo] = line.strip()[len("image:"):].strip() new_ref = resolve(repo, old_refs[repo]) if new_ref is None: out.append(line) @@ -329,7 +330,15 @@ def _atomic_write(path: Path, text: str) -> None: fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.name}.tmp.") tmp_path = Path(tmp) try: - with os.fdopen(fd, "w", encoding="utf-8") as f: + # If fdopen raises it does NOT take ownership of the descriptor, + # so close the raw fd ourselves to avoid leaking it. On success + # the `with` owns and closes it. + try: + f = os.fdopen(fd, "w", encoding="utf-8") + except Exception: + os.close(fd) + raise + with f: f.write(text) os.replace(tmp_path, path) except Exception: diff --git a/cli/greffer_cli/strings.py b/cli/greffer_cli/strings.py index 594d0192..9991cd0d 100644 --- a/cli/greffer_cli/strings.py +++ b/cli/greffer_cli/strings.py @@ -301,6 +301,13 @@ " docker-compose.yml /data mount (or re-run `greffer up`) and try again." ) +UPDATE_PREFLIGHT_NO_ID = ( + "✗ Refusing to update: GREFFER_ID is missing from env.env.\n" + " The post-recreate health check verifies the node still answers as\n" + " this greffer; without a known id it can't, so updating would be blind.\n" + " Restore GREFFER_ID (or re-run `greffer up`) and try again." +) + UPDATE_NEEDS_CONFIRM_NO_ROLLBACK = ( "✗ Rollback safety for {current} → {target} can't be confirmed " "(the release is flagged no-in-place-rollback, or the version manifest is " @@ -318,7 +325,7 @@ UPDATE_OK = "✓ Updated to {target}. The greffer re-registered and is ready." UPDATE_GATE_FAILED = ( - "✗ The {reason} check failed after recreate — rolling back to the previous " + "✗ The {reason} check failed after recreate. Rolling back to the previous " "version." ) diff --git a/cli/greffer_cli/update.py b/cli/greffer_cli/update.py index bc31f726..abd495b1 100644 --- a/cli/greffer_cli/update.py +++ b/cli/greffer_cli/update.py @@ -58,6 +58,12 @@ GATE_DEGRADED_OTHER = "degraded_other" GATE_CRASH_LOOP = "crash_loop" +# Degraded /readyz reasons the gate waits through rather than failing on +# (the greffer is mid-re-registration, which a recreate always triggers). +# A set so the gate stays correct if the app ever reports several reasons +# at once; any reason outside this set fails the gate. +TOLERABLE_DEGRADED_REASONS = {"registration_pending"} + # --- Version manifest ------------------------------------------------ @@ -167,6 +173,24 @@ def profile_for_mode(mode: str) -> str | None: return "tunnel" if mode == "tunnel" else None +def _resolve_mode(env: env_file.EnvFile, compose_file: Path) -> str: + """Deployment mode for the running node. + + Prefer the persisted ``GREFFER_MODE`` (``greffer up`` always writes it). + If it's absent (a hand-edited or pre-``GREFFER_MODE`` env.env), detect + it from the running node rather than guessing a static default: the + tunnel-sidecar only has a container under ``--profile tunnel``, so its + presence means tunnel mode. Falls back to proxy (the smaller service + set) when nothing is running to inspect, an edge that ``greffer up`` + (which always stamps the field) prevents in practice. + """ + persisted = env.get("GREFFER_MODE") + if persisted: + return persisted + running = compose.compose_services_running(compose_file, profile="tunnel") + 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? @@ -204,7 +228,9 @@ def health_gate( return GATE_WRONG_ID if r.status == "fatal": return GATE_FATAL - if r.status == "degraded" and r.reasons != ["registration_pending"]: + if r.status == "degraded" and any( + reason not in TOLERABLE_DEGRADED_REASONS for reason in r.reasons + ): return GATE_DEGRADED_OTHER if r.status == "ready": if not _version_applied(compose_file, target): @@ -281,7 +307,7 @@ def run_update( compose_file = paths.docker_compose_yml_path(cfg) env = env_file.EnvFile.read(paths.env_env_path(cfg)) greffer_id = env.get("GREFFER_ID") - mode = env.get("GREFFER_MODE") or "tunnel" + mode = _resolve_mode(env, compose_file) profile = profile_for_mode(mode) services = active_services(mode) @@ -305,6 +331,13 @@ def run_update( return EXIT_OK # ---- 2. Pre-flight (abort before any pull) ----------------------- + if not greffer_id: + # The post-recreate gate confirms the node still answers as this + # greffer; with no known id it can't, so refuse rather than update + # blind. `greffer up` always stamps GREFFER_ID, so a missing one + # means a hand-corrupted env.env. + print(strings.UPDATE_PREFLIGHT_NO_ID, file=sys.stderr) + return EXIT_PREFLIGHT_REFUSED if not compose.data_volume_is_named(compose_file): print(strings.UPDATE_PREFLIGHT_NO_DATA_VOLUME, file=sys.stderr) return EXIT_PREFLIGHT_REFUSED diff --git a/cli/tests/test_update.py b/cli/tests/test_update.py index 63d4adeb..fc4e4d89 100644 --- a/cli/tests/test_update.py +++ b/cli/tests/test_update.py @@ -268,3 +268,148 @@ def test_health_gate_version_not_applied(monkeypatch: pytest.MonkeyPatch, tmp_pa profile=None, timeout=10.0, sleep=lambda _s: None, ) assert outcome == update.GATE_NOT_APPLIED + + +# --- health-gate failure outcomes ------------------------------------ + +def _gate_with_readyz(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, readyz: dict) -> str: + """Run health_gate with a fixed /readyz body and healthz live.""" + f = tmp_path / "c.yml" + f.write_text(_COMPOSE, encoding="utf-8") + monkeypatch.setattr(compose, "exec_in_greffer_healthz", lambda f: _ok()) + monkeypatch.setattr(compose, "exec_in_greffer_readyz", lambda f: _ok(json.dumps(readyz))) + monkeypatch.setattr(compose, "service_container_id", lambda f, s: "cid") + monkeypatch.setattr(compose, "docker_inspect_restart_count", lambda c: 0) + # version-applied helpers (only reached on a "ready" status) + monkeypatch.setattr(compose, "container_image_id", lambda f, s: "sha256:X") + monkeypatch.setattr(compose, "image_id", lambda ref: "sha256:X") + monkeypatch.setattr(compose, "compose_services_running", lambda f, *, profile=None: {"greffer": True}) + return update.health_gate( + f, greffer_id="g1", target="0.3.4", services=["greffer"], + profile=None, timeout=10.0, poll_interval=0.0, sleep=lambda _s: None, + ) + + +def test_health_gate_fatal(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + outcome = _gate_with_readyz( + monkeypatch, tmp_path, + {"id": "g1", "status": "fatal", "reasons": ["docker_unreachable"]}, + ) + assert outcome == update.GATE_FATAL + + +def test_health_gate_wrong_id(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + outcome = _gate_with_readyz( + monkeypatch, tmp_path, + {"id": "someone-else", "status": "ready", "reasons": []}, + ) + assert outcome == update.GATE_WRONG_ID + + +def test_health_gate_degraded_other_reason(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + # a degraded reason outside the tolerated set fails (not registration_pending) + outcome = _gate_with_readyz( + monkeypatch, tmp_path, + {"id": "g1", "status": "degraded", "reasons": ["disk_full"]}, + ) + assert outcome == update.GATE_DEGRADED_OTHER + + +def test_health_gate_degraded_mixed_reasons_fails(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + # registration_pending alone is tolerated, but paired with another reason + # the gate must still fail (set-membership, not exact-list equality). + outcome = _gate_with_readyz( + monkeypatch, tmp_path, + {"id": "g1", "status": "degraded", "reasons": ["registration_pending", "disk_full"]}, + ) + assert outcome == update.GATE_DEGRADED_OTHER + + +def test_health_gate_crash_loop(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + f = tmp_path / "c.yml" + f.write_text(_COMPOSE, encoding="utf-8") + # never live, so the gate falls through to the crash-loop check + monkeypatch.setattr(compose, "exec_in_greffer_healthz", lambda f: _fail()) + monkeypatch.setattr(compose, "service_container_id", lambda f, s: "cid") + counts = iter([0, 2, 2, 2]) # baseline 0, then climbed by 2 -> crash-loop + monkeypatch.setattr(compose, "docker_inspect_restart_count", lambda c: next(counts)) + outcome = update.health_gate( + f, greffer_id="g1", target="0.3.4", services=["greffer"], + profile=None, timeout=10.0, poll_interval=0.0, sleep=lambda _s: None, + ) + assert outcome == update.GATE_CRASH_LOOP + + +def test_health_gate_timeout(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + f = tmp_path / "c.yml" + f.write_text(_COMPOSE, encoding="utf-8") + # drive the monotonic clock: deadline then one in-window tick, then past it + times = iter([0.0, 0.0, 100.0]) + monkeypatch.setattr(update.time, "monotonic", lambda: next(times)) + monkeypatch.setattr(compose, "exec_in_greffer_healthz", lambda f: _fail()) + monkeypatch.setattr(compose, "service_container_id", lambda f, s: "cid") + monkeypatch.setattr(compose, "docker_inspect_restart_count", lambda c: 0) + outcome = update.health_gate( + f, greffer_id="g1", target="0.3.4", services=["greffer"], + profile=None, timeout=5.0, poll_interval=0.0, sleep=lambda _s: None, + ) + assert outcome == update.GATE_TIMEOUT + + +# --- rollback that itself fails (EXIT_FAILED_ROLLBACK_FAILED) --------- + +def test_rollback_compose_up_fails_exits_2(cfg: Path, monkeypatch: pytest.MonkeyPatch) -> None: + FakeDocker().install(monkeypatch) + # gate sees fatal -> rollback; the rollback `up` (2nd compose_up) fails + monkeypatch.setattr( + compose, "exec_in_greffer_readyz", + lambda f: _ok(json.dumps({"id": "g1", "status": "fatal", "reasons": ["docker_unreachable"]})), + ) + calls = {"n": 0} + + def up(f, *, profile=None): + calls["n"] += 1 + return _ok() if calls["n"] == 1 else _fail() # forward ok, rollback fails + + monkeypatch.setattr(compose, "compose_up", up) + assert _run(cfg, target="0.3.4") == update.EXIT_FAILED_ROLLBACK_FAILED + + +def test_rollback_health_never_ready_exits_2(cfg: Path, monkeypatch: pytest.MonkeyPatch) -> None: + FakeDocker().install(monkeypatch) + # gate fatal -> rollback recreate succeeds but never reaches /readyz ready + monkeypatch.setattr( + compose, "exec_in_greffer_readyz", + lambda f: _ok(json.dumps({"id": "g1", "status": "fatal", "reasons": ["docker_unreachable"]})), + ) + monkeypatch.setattr(update, "_rollback_health", lambda *a, **k: False) + assert _run(cfg, target="0.3.4") == update.EXIT_FAILED_ROLLBACK_FAILED + + +# --- mode resolution + id pre-flight --------------------------------- + +def test_resolve_mode(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + from greffer_cli import env_file + f = tmp_path / "docker-compose.yml" + f.write_text(_COMPOSE, encoding="utf-8") + # explicit GREFFER_MODE always wins, no detection + env = env_file.EnvFile.from_text('GREFFER_MODE="proxy"\n') + assert update._resolve_mode(env, f) == "proxy" + # missing -> detect tunnel when the sidecar has a container + monkeypatch.setattr( + compose, "compose_services_running", + lambda cf, *, profile=None: {"greffer": True, "tunnel-sidecar": True}, + ) + assert update._resolve_mode(env_file.EnvFile.from_text('GREFFER_ID="g1"\n'), f) == "tunnel" + # missing -> proxy when no sidecar container is present + monkeypatch.setattr( + compose, "compose_services_running", + lambda cf, *, profile=None: {"greffer": True, "nginx": True}, + ) + assert update._resolve_mode(env_file.EnvFile.from_text('GREFFER_ID="g1"\n'), f) == "proxy" + + +def test_preflight_refuses_without_greffer_id(cfg: Path, monkeypatch: pytest.MonkeyPatch) -> None: + (cfg / "env.env").write_text('GREFFER_MODE="proxy"\n', encoding="utf-8") # no GREFFER_ID + FakeDocker().install(monkeypatch) + assert _run(cfg, target="0.3.4") == update.EXIT_PREFLIGHT_REFUSED From ebb741b524c55809ee3735a65522519f2b3fb1c6 Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Mon, 15 Jun 2026 15:47:52 +0200 Subject: [PATCH 4/8] test(greffer-cli): make compose-arg assertions OS-portable The Windows CI build failed: three update-engine tests hardcoded the POSIX string "/tmp/c.yml" and asserted it verbatim in the docker args, but str(Path("/tmp/c.yml")) is "\tmp\c.yml" on Windows. The product code is correct (it passes str(compose_file), right per-OS); only the test assertions baked in a POSIX path. Compare against str(Path(...)) instead. Co-Authored-By: Claude Opus 4.8 --- cli/tests/test_compose.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/cli/tests/test_compose.py b/cli/tests/test_compose.py index 2c900a9b..1ae3f596 100644 --- a/cli/tests/test_compose.py +++ b/cli/tests/test_compose.py @@ -138,12 +138,14 @@ def test_compose_pull_args(monkeypatch: pytest.MonkeyPatch) -> None: or compose.CommandResult(0, "", "") ), ) + cpath = Path("/tmp/c.yml") compose.compose_pull( - Path("/tmp/c.yml"), profile="tunnel", + cpath, profile="tunnel", services=["greffer", "nginx", "tunnel-sidecar"], ) a = captured["args"] - assert a[:4] == ["docker", "compose", "-f", "/tmp/c.yml"] + # str(Path(...)) so the assertion holds on Windows too (\tmp\c.yml). + assert a[:4] == ["docker", "compose", "-f", str(cpath)] assert "--profile" in a and a[a.index("--profile") + 1] == "tunnel" assert a[a.index("pull") + 1:] == ["greffer", "nginx", "tunnel-sidecar"] @@ -234,10 +236,11 @@ def test_exec_in_greffer_readyz_probe(monkeypatch: pytest.MonkeyPatch) -> None: or compose.CommandResult(0, '{"id":"x","status":"ready","reasons":[]}', "") ), ) - compose.exec_in_greffer_readyz(Path("/tmp/c.yml")) + cpath = Path("/tmp/c.yml") + compose.exec_in_greffer_readyz(cpath) a = captured["args"] assert a[:7] == [ - "docker", "compose", "-f", "/tmp/c.yml", "exec", "-T", "greffer", + "docker", "compose", "-f", str(cpath), "exec", "-T", "greffer", ] probe = a[-1] assert "/readyz" in probe @@ -247,12 +250,13 @@ def test_exec_in_greffer_readyz_probe(monkeypatch: pytest.MonkeyPatch) -> None: def test_image_id_and_container_image_id(monkeypatch: pytest.MonkeyPatch) -> None: calls: list[list[str]] = [] + cpath = Path("/tmp/c.yml") def fake_run(args, *, timeout=None): calls.append(list(args)) if args[:3] == ["docker", "image", "inspect"]: return compose.CommandResult(0, "sha256:deadbeef\n", "") - if args[:5] == ["docker", "compose", "-f", "/tmp/c.yml", "ps"]: + if args[:5] == ["docker", "compose", "-f", str(cpath), "ps"]: return compose.CommandResult(0, "container123\n", "") if args[:2] == ["docker", "inspect"]: return compose.CommandResult(0, "sha256:cafe\n", "") @@ -260,4 +264,4 @@ def fake_run(args, *, timeout=None): monkeypatch.setattr(compose, "_run", fake_run) assert compose.image_id("greffon/greffer:0.3.4") == "sha256:deadbeef" - assert compose.container_image_id(Path("/tmp/c.yml"), "greffer") == "sha256:cafe" + assert compose.container_image_id(cpath, "greffer") == "sha256:cafe" From b51b804fa13e671576350414009d3dda115cb78d Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Mon, 15 Jun 2026 15:53:27 +0200 Subject: [PATCH 5/8] fix(greffer-cli): make /data named-volume preflight separator-agnostic data_volume_is_named distinguished a named volume from a bind mount with a POSIX-only test (`"/" not in src`). On Windows a relative, backslash- separated bind source onto /data (e.g. `data\sub:/data`) contains no "/" and so was misclassified as a named volume, letting the identity- preservation preflight pass and `greffer update` recreate a bind-backed /data, dropping the persisted token / TLS key / migration ledger. Use a positive allowlist matching Docker's own volume-name grammar ([A-Za-z0-9][A-Za-z0-9_.-]*): separator-agnostic, so the classification is identical on every host the CLI ships to. Add POSIX and Windows relative-bind regression cases. Found by a cross-platform portability audit of the update diff. Co-Authored-By: Claude Opus 4.8 --- cli/greffer_cli/compose.py | 7 ++++++- cli/tests/test_compose.py | 2 ++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/cli/greffer_cli/compose.py b/cli/greffer_cli/compose.py index 4544e25c..44974111 100644 --- a/cli/greffer_cli/compose.py +++ b/cli/greffer_cli/compose.py @@ -408,7 +408,12 @@ def data_volume_is_named(compose_file: Path) -> bool: m = _DATA_MOUNT_RE.match(line) if m: src = m.group("src") - return "/" not in src and not src.startswith((".", "~")) + # A Docker volume name is a bare token [A-Za-z0-9][A-Za-z0-9_.-]*; + # anything with a path separator (POSIX "/" or Windows "\") or a + # relative/home prefix is a bind mount. A positive allowlist is + # separator-agnostic, so the classification is identical on every + # host the CLI ships to (Linux/macOS/Windows), not just POSIX. + return re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", src) is not None return False diff --git a/cli/tests/test_compose.py b/cli/tests/test_compose.py index 1ae3f596..428eb6b9 100644 --- a/cli/tests/test_compose.py +++ b/cli/tests/test_compose.py @@ -212,6 +212,8 @@ def test_data_volume_is_named(tmp_path: Path) -> None: (" - /srv/greffer:/data", False), # absolute bind (" - ./data:/data", False), # relative bind (" - ~/data:/data", False), # home bind + (" - data/sub:/data", False), # relative bind (POSIX sep) + (" - data\\sub:/data", False), # relative bind (Windows sep) (" - greffon-data:/other", False), # not /data ], ) From f8a20f449f81a9d9776a9aa0598b85820d8b0611 Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Mon, 15 Jun 2026 16:49:41 +0200 Subject: [PATCH 6/8] fix(greffer-cli): validate update tag, disarm on interrupt, lock, pull all images MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Second review round on the update engine found, and this fixes: - SECURITY (tag injection -> RCE): the update target tag was written into docker-compose.yml with no grammar validation, and the default source is a network-fetched manifest. A manifest `latest` carrying a newline + YAML (e.g. a `command:` key) injected into the compose file, then `compose up` executed it. Add is_valid_image_tag (Docker tag grammar, fullmatch) and enforce it at every entry: fetch_manifest coerces non-string fields to None, resolve_target drops an invalid tag, `update --to` is validated at the CLI boundary, and set_image_tag raises rather than write an invalid tag. Restores the HLD's "a tampered manifest can name only a tag in the known repo, never an arbitrary image" invariant. - INTERRUPT SAFETY: a Ctrl-C / SIGTERM after the retag but before the gate passed left the compose file pinned to an un-gated target with no rollback, so a later bare `docker compose up` would recreate into it. Wrap rewrite->pull->recreate->gate in try/finally + a SIGTERM handler that restores the prior refs unless the gate passed. - CONCURRENCY: serialize the mutating path on a host flock (~/.greffer/.update.lock) so two concurrent runs can't race the rewrite / rollback-baseline capture; a second run refuses cleanly. POSIX flock (auto-releases on death); degrades to unlocked where fcntl is absent. - CONTRACT: pull/validate ALL three node images (incl. the profile-gated tunnel-sidecar in proxy mode), since set_image_tag retags all three; a bad sidecar tag is now caught at update time, not on a later proxy->tunnel switch. Recreate and the health gate stay mode-scoped. Tests: +26 — tag-grammar + injection refusal, manifest coercion/malformed, parse_readyz defensive shapes, listed-pair no-rollback gate, tunnel-profile recreate, partial-services-up timeout->rollback, single-restart tolerated, Ctrl-C disarm, lock-held refusal, idempotent file-untouched. 157 passing. Co-Authored-By: Claude Opus 4.8 --- cli/greffer_cli/compose.py | 25 +++++ cli/greffer_cli/main.py | 6 ++ cli/greffer_cli/strings.py | 12 +++ cli/greffer_cli/update.py | 186 ++++++++++++++++++++++++++++++------- cli/tests/test_compose.py | 45 +++++++++ cli/tests/test_update.py | 186 +++++++++++++++++++++++++++++++++++++ 6 files changed, 424 insertions(+), 36 deletions(-) diff --git a/cli/greffer_cli/compose.py b/cli/greffer_cli/compose.py index 44974111..ed6eb05e 100644 --- a/cli/greffer_cli/compose.py +++ b/cli/greffer_cli/compose.py @@ -298,6 +298,26 @@ def compose_pull( ) +# Docker image-tag grammar: up to 128 chars, leading char alphanumeric or +# "_", then alphanumeric / "_" / "." / "-". An update target is validated +# against this BEFORE it is written into a compose ``image:`` line, so a +# tampered version manifest (or a bad --to) can name only a tag in the known +# repo, never inject a newline / extra YAML key / a different image that +# `docker compose up` would then execute. (Signature / digest verification +# of the image itself is a separate, later trust gate.) +_IMAGE_TAG_RE = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}") + + +def is_valid_image_tag(tag: object) -> bool: + """True iff ``tag`` is a syntactically valid Docker image tag. + + Uses ``fullmatch`` so the whole string must be a valid tag, so a trailing + newline (``"latest\\n"``) can't slip past a ``$`` anchor and add a blank + line / break the rewrite. + """ + return isinstance(tag, str) and _IMAGE_TAG_RE.fullmatch(tag) is not None + + def _rewrite_image_lines(text: str, resolve) -> tuple[str, dict[str, str]]: """Rewrite every ``greffon/*`` image line via ``resolve(repo, old_ref)``. @@ -358,6 +378,11 @@ def set_image_tag(compose_file: Path, target: str) -> dict[str, str]: map of repo -> prior full ref, so a rollback can restore the exact refs that were there before (`set_image_refs`). """ + if not is_valid_image_tag(target): + # Defense in depth: callers validate the target, but never write an + # unvalidated tag into the compose file. An injected newline / YAML + # key would be executed by `docker compose up`. + raise ValueError(f"refusing to write invalid image tag: {target!r}") text = compose_file.read_text(encoding="utf-8") new_text, old_refs = _rewrite_image_lines( text, lambda repo, _old: f"{repo}:{target}", diff --git a/cli/greffer_cli/main.py b/cli/greffer_cli/main.py index 40ab15bf..3e547b58 100644 --- a/cli/greffer_cli/main.py +++ b/cli/greffer_cli/main.py @@ -228,6 +228,12 @@ def update( Pulls the target, recreates the node, health-gates on /readyz, and rolls back to the previous version on any failure. """ + # Validate --to at the boundary so a bad tag fails fast with a clear + # message (the engine also rejects it, but here we can be specific). + if to is not None and not compose_mod.is_valid_image_tag(to): + typer.echo(strings_mod.UPDATE_BAD_TARGET.format(target=to), err=True) + raise typer.Exit(code=2) + cfg = paths.resolve_config_dir(config_dir) if not paths.docker_compose_yml_path(cfg).exists(): typer.echo( diff --git a/cli/greffer_cli/strings.py b/cli/greffer_cli/strings.py index 9991cd0d..ba84c55c 100644 --- a/cli/greffer_cli/strings.py +++ b/cli/greffer_cli/strings.py @@ -308,6 +308,18 @@ " Restore GREFFER_ID (or re-run `greffer up`) and try again." ) +UPDATE_IN_PROGRESS = ( + "✗ Another `greffer update` is already running on this host " + "(lock: {lock_path}).\n Wait for it to finish, or if no update is " + "actually running, remove that lock file and retry." +) + +UPDATE_BAD_TARGET = ( + "✗ --to is not a valid image tag: {target}\n" + " A tag is up to 128 chars: letters, digits, '_', '.', '-' " + "(leading char a letter/digit/underscore)." +) + UPDATE_NEEDS_CONFIRM_NO_ROLLBACK = ( "✗ Rollback safety for {current} → {target} can't be confirmed " "(the release is flagged no-in-place-rollback, or the version manifest is " diff --git a/cli/greffer_cli/update.py b/cli/greffer_cli/update.py index abd495b1..d030c9c0 100644 --- a/cli/greffer_cli/update.py +++ b/cli/greffer_cli/update.py @@ -20,6 +20,7 @@ import dataclasses import json +import signal import sys import time import urllib.error @@ -97,9 +98,18 @@ def fetch_manifest( nrf = data.get("no_rollback_from") or [] if not isinstance(nrf, list): nrf = [] + # Coerce non-string version fields to None: a tampered/malformed manifest + # could carry a list or object here, which must never flow into an image + # ref. Tag *grammar* is enforced later (resolve_target / set_image_tag). + latest = data.get("latest") + if not isinstance(latest, str): + latest = None + min_supported = data.get("min_supported") + if not isinstance(min_supported, str): + min_supported = None return Manifest( - latest=data.get("latest"), - min_supported=data.get("min_supported"), + latest=latest, + min_supported=min_supported, no_rollback_from=[str(x) for x in nrf], ) @@ -108,10 +118,15 @@ def resolve_target( *, explicit_to: str | None, manifest: Manifest | None, ) -> str | None: """Resolve the target tag. ``--to`` wins; else the manifest's latest; - else ``None`` (auto-latest with an unreachable manifest -> abort).""" + else ``None`` (auto-latest with an unreachable manifest -> abort). + + A syntactically invalid tag (from a tampered manifest or a bad ``--to``) + is rejected here (-> ``None``) so it can never reach the compose file; + the CLI boundary (`main.update`) also rejects an invalid ``--to`` with a + precise message before we get here.""" if explicit_to: - return explicit_to - if manifest and manifest.latest: + return explicit_to if compose.is_valid_image_tag(explicit_to) else None + if manifest and manifest.latest and compose.is_valid_image_tag(manifest.latest): return manifest.latest return None @@ -294,6 +309,73 @@ def _rollback_health( return False +# --- concurrency lock + interrupt disarm ----------------------------- + +# Sentinel: platform without fcntl (Windows) -> proceed without a host lock. +_NO_HOST_LOCK = object() + + +def _update_lock_path(cfg: Path) -> Path: + return cfg / ".update.lock" + + +def _acquire_update_lock(cfg: Path): + """Take an exclusive host lock so two concurrent ``greffer update`` runs + can't interleave the compose rewrite and rollback-baseline capture (run B + reading the file after run A already retagged it would record A's + unvalidated target as the "prior" ref). + + Returns an open handle to release later, ``None`` if another run already + holds the lock, or ``_NO_HOST_LOCK`` on a platform without ``fcntl`` + (Windows) where we proceed unlocked; concurrent runs there are the + operator's responsibility (v1 is operator-run).""" + try: + import fcntl + except ImportError: + return _NO_HOST_LOCK + fh = open(_update_lock_path(cfg), "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_update_lock(handle) -> None: + if handle is None or handle is _NO_HOST_LOCK: + return + try: + handle.close() # closing the fd releases the flock + except OSError: + pass + + +def _install_sigterm_disarm(disarm: Callable[[], None]): + """Route a SIGTERM during the mutating window through ``disarm`` (restore + the prior refs) then exit, so a kill mid-update doesn't leave the compose + file pinned to an un-gated target. Ctrl-C (KeyboardInterrupt) and + exceptions are already covered by the surrounding ``finally``; this adds + the bare-SIGTERM case. Returns the prior handler to restore, or ``None`` + if one can't be installed (non-main thread / unsupported platform).""" + def _handler(_signum, _frame): + disarm() + raise SystemExit(143) + try: + return signal.signal(signal.SIGTERM, _handler) + except (ValueError, OSError, AttributeError): + return None + + +def _restore_sigterm(prev) -> None: + if prev is None: + return + try: + signal.signal(signal.SIGTERM, prev) + except (ValueError, OSError, AttributeError): + pass + + def run_update( cfg: Path, *, target: str | None = None, @@ -358,34 +440,66 @@ def run_update( print(strings.UPDATE_ALREADY.format(target=resolved)) return EXIT_OK - # ---- 3. Rewrite + pull + recreate -------------------------------- - old_refs = compose.set_image_tag(compose_file, resolved) - pull = compose.compose_pull(compose_file, profile=profile, services=services) - if not pull.ok: - # No recreate happened; restore the prior refs so a later `up` - # can't recreate into the unvalidated target. Old containers run on. - compose.set_image_refs(compose_file, old_refs) - print(strings.UPDATE_PULL_FAILED.format(target=resolved), file=sys.stderr) - return EXIT_FAILED_ROLLED_BACK - up = compose.compose_up(compose_file, profile=profile) - if not up.ok: - return _rollback( - compose_file, profile=profile, services=services, - old_refs=old_refs, greffer_id=greffer_id, timeout=timeout, sleep=sleep, - ) - - # ---- 4. Health-gate ---------------------------------------------- - outcome = health_gate( - compose_file, greffer_id=greffer_id, target=resolved, - services=services, profile=profile, timeout=timeout, sleep=sleep, - ) - if outcome == GATE_READY: - print(strings.UPDATE_OK.format(target=resolved)) - return EXIT_OK - - # ---- 5. Rollback (the authority) --------------------------------- - print(strings.UPDATE_GATE_FAILED.format(reason=outcome), file=sys.stderr) - return _rollback( - compose_file, profile=profile, services=services, - old_refs=old_refs, greffer_id=greffer_id, timeout=timeout, sleep=sleep, - ) + # Serialize the mutating path on a host lock so two concurrent updates + # can't race the compose rewrite / rollback-baseline capture. + lock = _acquire_update_lock(cfg) + if lock is None: + print(strings.UPDATE_IN_PROGRESS.format(lock_path=_update_lock_path(cfg)), + file=sys.stderr) + return EXIT_PREFLIGHT_REFUSED + try: + # ---- 3. Rewrite + pull + recreate ---------------------------- + old_refs = compose.set_image_tag(compose_file, resolved) + gate_passed = False + + def _disarm() -> None: + # Backstop for an interrupt/crash between the retag and a passed + # gate: restore the prior refs so a later bare `docker compose up` + # (operator, deploy script, host reboot) can't recreate the node + # into the un-gated target. The failure branches below reach this + # via the same flag; it also covers Ctrl-C / SIGTERM mid-pull or + # mid-gate, which would otherwise skip rollback entirely. + if not gate_passed: + compose.set_image_refs(compose_file, old_refs) + + prev_sigterm = _install_sigterm_disarm(_disarm) + try: + # Pull (and thereby validate) ALL node images, including the + # profile-gated tunnel-sidecar in proxy mode: set_image_tag + # retagged its line too, so a bad target tag must be caught here + # rather than left to break a later proxy->tunnel switch. Recreate + # and the health gate stay mode-scoped below. + pull = compose.compose_pull( + compose_file, profile="tunnel", services=list(SERVICE_REPO), + ) + if not pull.ok: + print(strings.UPDATE_PULL_FAILED.format(target=resolved), file=sys.stderr) + return EXIT_FAILED_ROLLED_BACK # _disarm() (finally) restores refs + up = compose.compose_up(compose_file, profile=profile) + if not up.ok: + return _rollback( + compose_file, profile=profile, services=services, + old_refs=old_refs, greffer_id=greffer_id, timeout=timeout, sleep=sleep, + ) + + # ---- 4. Health-gate -------------------------------------- + outcome = health_gate( + compose_file, greffer_id=greffer_id, target=resolved, + services=services, profile=profile, timeout=timeout, sleep=sleep, + ) + if outcome == GATE_READY: + gate_passed = True + print(strings.UPDATE_OK.format(target=resolved)) + return EXIT_OK + + # ---- 5. Rollback (the authority) ------------------------- + print(strings.UPDATE_GATE_FAILED.format(reason=outcome), file=sys.stderr) + return _rollback( + compose_file, profile=profile, services=services, + old_refs=old_refs, greffer_id=greffer_id, timeout=timeout, sleep=sleep, + ) + finally: + _disarm() + _restore_sigterm(prev_sigterm) + finally: + _release_update_lock(lock) diff --git a/cli/tests/test_compose.py b/cli/tests/test_compose.py index 428eb6b9..2c09a78d 100644 --- a/cli/tests/test_compose.py +++ b/cli/tests/test_compose.py @@ -229,6 +229,51 @@ def test_data_volume_absent(tmp_path: Path) -> None: assert compose.data_volume_is_named(f) is False +@pytest.mark.parametrize( + "tag, ok", + [ + ("0.3.4", True), + ("latest", True), + ("v1.2.3-rc1", True), + ("a_b.c-d", True), + ("_underscore_lead", True), + ("", False), + ("bad:tag", False), # ':' separates repo:tag, never inside a tag + ("with@sha256", False), # '@' is the digest separator + ("has space", False), + ("line\nbreak", False), # embedded newline (YAML injection vector) + ("trailing\n", False), # trailing newline must not slip past + (".leadingdot", False), + ("-leadingdash", False), + ("a" * 128, True), # max length + ("a" * 129, False), # one over + ], +) +def test_is_valid_image_tag(tag: str, ok: bool) -> None: + assert compose.is_valid_image_tag(tag) is ok + + +def test_is_valid_image_tag_non_str() -> None: + assert compose.is_valid_image_tag(["a", "b"]) is False + assert compose.is_valid_image_tag(None) is False + + +def test_set_image_tag_rejects_invalid_tag(tmp_path: Path) -> None: + f = tmp_path / "c.yml" + f.write_text( + "services:\n greffer:\n image: greffon/greffer:0.3.3\n", encoding="utf-8", + ) + before = f.read_text() + # a YAML-injection target must be refused, and the file left untouched + with pytest.raises(ValueError): + compose.set_image_tag(f, 'x\n command: ["sh", "-c", "evil"]') + assert f.read_text() == before + # a ':'-bearing target (would corrupt repo:tag) is likewise refused + with pytest.raises(ValueError): + compose.set_image_tag(f, "bad:tag") + assert f.read_text() == before + + def test_exec_in_greffer_readyz_probe(monkeypatch: pytest.MonkeyPatch) -> None: captured: dict[str, list[str]] = {} monkeypatch.setattr( diff --git a/cli/tests/test_update.py b/cli/tests/test_update.py index fc4e4d89..cb66cdcd 100644 --- a/cli/tests/test_update.py +++ b/cli/tests/test_update.py @@ -167,9 +167,14 @@ def test_idempotent_when_already_target(cfg: Path, monkeypatch: pytest.MonkeyPat fd.running_image = "sha256:SAME" fd.target_image = "sha256:SAME" # running already == target fd.install(monkeypatch) + before = (cfg / "docker-compose.yml").read_text() rc = _run(cfg, target="0.3.4") assert rc == update.EXIT_OK assert "Already up to date" in capsys.readouterr().out + # the short-circuit must return BEFORE set_image_tag; file untouched + text = (cfg / "docker-compose.yml").read_text() + assert text == before + assert "greffon/greffer:0.3.3" in text and "greffon/greffer:0.3.4" not in text def test_preflight_refuses_without_named_data_volume(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: @@ -413,3 +418,184 @@ def test_preflight_refuses_without_greffer_id(cfg: Path, monkeypatch: pytest.Mon (cfg / "env.env").write_text('GREFFER_MODE="proxy"\n', encoding="utf-8") # no GREFFER_ID FakeDocker().install(monkeypatch) assert _run(cfg, target="0.3.4") == update.EXIT_PREFLIGHT_REFUSED + + +# --- target / manifest hardening (tag injection) --------------------- + +def test_resolve_target_rejects_invalid_tag() -> None: + # a tampered manifest naming a tag with injected YAML / newline is dropped + evil = update.Manifest(latest='latest\n command: ["sh","-c","x"]') + assert update.resolve_target(explicit_to=None, manifest=evil) is None + # a non-string manifest latest never stringifies into a ref + assert update.resolve_target(explicit_to=None, manifest=update.Manifest(latest=None)) is None + # an invalid explicit --to is rejected too + assert update.resolve_target(explicit_to="bad:tag", manifest=None) is None + # a clean tag still resolves + assert update.resolve_target(explicit_to="0.3.4", manifest=None) == "0.3.4" + + +class _FakeResp: + def __init__(self, body: str) -> None: + self._body = body.encode("utf-8") + + def read(self) -> bytes: + return self._body + + def __enter__(self) -> "_FakeResp": + return self + + def __exit__(self, *a: object) -> bool: + return False + + +def test_fetch_manifest_coerces_and_tolerates_malformed(monkeypatch: pytest.MonkeyPatch) -> None: + holder: dict[str, str] = {} + monkeypatch.setattr( + update.urllib.request, "urlopen", + lambda url, timeout=None: _FakeResp(holder["body"]), + ) + # non-string latest (a list) is coerced to None, not stringified into a ref + holder["body"] = json.dumps({"latest": ["a", "b"]}) + assert update.fetch_manifest("https://x/m.json").latest is None + # malformed JSON body -> None manifest (treated as unreachable) + holder["body"] = "not json {" + assert update.fetch_manifest("https://x/m.json") is None + # a non-object JSON body -> None manifest + holder["body"] = "[]" + assert update.fetch_manifest("https://x/m.json") is None + # a well-formed manifest still parses + holder["body"] = json.dumps({"latest": "0.3.5", "no_rollback_from": ["a->b"]}) + m = update.fetch_manifest("https://x/m.json") + assert m.latest == "0.3.5" and m.no_rollback_from == ["a->b"] + + +def test_parse_readyz_defensive_shapes() -> None: + # JSON that isn't an object -> not ok + assert update.parse_readyz(_ok("[]")).ok is False + assert update.parse_readyz(_ok("5")).ok is False + # reasons present but not a list -> coerced to [] (guards char-iteration + # of a scalar into the degraded-reason check) + scalar = update.parse_readyz(_ok(json.dumps({"status": "degraded", "reasons": "oops"}))) + assert scalar.ok is True and scalar.status == "degraded" and scalar.reasons == [] + + +# --- rollback-safety gate: listed (True) branch ---------------------- + +def test_needs_confirm_when_rollback_listed(cfg: Path, monkeypatch: pytest.MonkeyPatch) -> None: + FakeDocker().install(monkeypatch) + # manifest reachable AND the current->target pair is flagged no-rollback + monkeypatch.setattr( + update, "fetch_manifest", + lambda url, timeout=10.0: update.Manifest(latest="0.3.4", no_rollback_from=["0.3.3->0.3.4"]), + ) + assert _run(cfg, target="0.3.4") == update.EXIT_PREFLIGHT_REFUSED + assert _run(cfg, target="0.3.4", confirm_no_rollback=True) == update.EXIT_OK + + +# --- tunnel mode + partial-services-up ------------------------------- + +@pytest.fixture +def tunnel_cfg(tmp_path: Path) -> Path: + (tmp_path / "docker-compose.yml").write_text(_COMPOSE, encoding="utf-8") + (tmp_path / "env.env").write_text( + 'GREFFER_ID="g1"\nGREFFER_MODE="tunnel"\n', encoding="utf-8", + ) + return tmp_path + + +def test_tunnel_mode_recreates_with_tunnel_profile(tunnel_cfg: Path, monkeypatch: pytest.MonkeyPatch) -> None: + fd = FakeDocker() + fd.install(monkeypatch) + rec: dict[str, object] = {} + + def up(f, *, profile=None): + rec["up_profile"] = profile + fd.running_image = fd.target_image + return _ok() + + monkeypatch.setattr(compose, "compose_up", up) + # the gate must see the sidecar up in tunnel mode + monkeypatch.setattr( + compose, "compose_services_running", + lambda f, *, profile=None: {"greffer": True, "nginx": True, "tunnel-sidecar": True}, + ) + assert _run(tunnel_cfg, target="0.3.4") == update.EXIT_OK + assert rec["up_profile"] == "tunnel" # recreate ran under --profile tunnel + + +def test_partial_services_up_rolls_back(cfg: Path, monkeypatch: pytest.MonkeyPatch) -> None: + fd = FakeDocker() + fd.install(monkeypatch) + # greffer is ready + version-applied, but nginx never comes up while on + # the target -> gate can't reach READY -> times out -> rollback. nginx + # comes back once the refs are restored, so the rollback is healthy. + def services_running(f, *, profile=None): + on_target = "greffon/greffer:0.3.4" in (cfg / "docker-compose.yml").read_text() + return {"greffer": True, "nginx": not on_target} + + monkeypatch.setattr(compose, "compose_services_running", services_running) + rc = _run(cfg, target="0.3.4", timeout=0.1) + assert rc == update.EXIT_FAILED_ROLLED_BACK + text = (cfg / "docker-compose.yml").read_text() + assert "greffon/greffer:0.3.3" in text and "greffon/greffer:0.3.4" not in text + + +def test_health_gate_single_restart_tolerated(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + f = tmp_path / "c.yml" + f.write_text(_COMPOSE, encoding="utf-8") + seq = [ + {"id": "g1", "status": "degraded", "reasons": ["registration_pending"]}, + {"id": "g1", "status": "ready", "reasons": []}, + ] + monkeypatch.setattr(compose, "exec_in_greffer_healthz", lambda f: _ok()) + monkeypatch.setattr( + compose, "exec_in_greffer_readyz", + lambda f: _ok(json.dumps(seq.pop(0) if seq else {"id": "g1", "status": "ready", "reasons": []})), + ) + monkeypatch.setattr(compose, "service_container_id", lambda f, s: "cid") + counts = iter([0, 1, 1, 1]) # baseline 0, then a single restart (delta 1, tolerated) + monkeypatch.setattr(compose, "docker_inspect_restart_count", lambda c: next(counts)) + monkeypatch.setattr(compose, "container_image_id", lambda f, s: "sha256:X") + monkeypatch.setattr(compose, "image_id", lambda ref: "sha256:X") + monkeypatch.setattr(compose, "compose_services_running", lambda f, *, profile=None: {"greffer": True}) + outcome = update.health_gate( + f, greffer_id="g1", target="0.3.4", services=["greffer"], + profile=None, timeout=10.0, poll_interval=0.0, sleep=lambda _s: None, + ) + assert outcome == update.GATE_READY # one restart is tolerated; boundary is strictly > 1 + + +# --- interrupt safety + concurrency lock ----------------------------- + +def test_interrupt_after_retag_disarms_compose(cfg: Path, monkeypatch: pytest.MonkeyPatch) -> None: + FakeDocker().install(monkeypatch) + + def boom(f, *, profile=None): + raise KeyboardInterrupt # operator Ctrl-C mid-recreate (after retag) + + monkeypatch.setattr(compose, "compose_up", boom) + with pytest.raises(KeyboardInterrupt): + _run(cfg, target="0.3.4") + # the finally-disarm must have restored the prior refs so a later bare + # `docker compose up` can't recreate into the un-gated target + text = (cfg / "docker-compose.yml").read_text() + assert "greffon/greffer:0.3.3" in text and "greffon/greffer:0.3.4" not in text + + +def test_update_refused_when_lock_held(cfg: Path, monkeypatch: pytest.MonkeyPatch) -> None: + fcntl = pytest.importorskip("fcntl") # POSIX-only; skip on Windows + FakeDocker().install(monkeypatch) + # set_image_tag must NOT run while another process holds the lock + tagged = {"called": False} + real_set = compose.set_image_tag + monkeypatch.setattr( + compose, "set_image_tag", + lambda f, t: (tagged.__setitem__("called", True), real_set(f, t))[1], + ) + held = open(cfg / ".update.lock", "w", encoding="utf-8") + fcntl.flock(held.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + try: + assert _run(cfg, target="0.3.4") == update.EXIT_PREFLIGHT_REFUSED + assert tagged["called"] is False + finally: + held.close() From 77e1c7863061abf0f81063f0f8f4014c8241eb44 Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Mon, 15 Jun 2026 17:00:45 +0200 Subject: [PATCH 7/8] fix(greffer-cli): SIGTERM-on-success exit code + manifest message; pin new paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Third review round, addressing its findings: - SIGTERM on a *succeeded* update exited 143: the handler raised SystemExit(143) unconditionally, so a kill in the window after the gate passed but before the handler is restored reported failure for a confirmed success. The handler now exits 0 once gate_passed (a v2 wrapper keying on the exit code must not misread success). - Diagnostics: a reachable manifest whose `latest` is missing / non-string / an invalid tag now prints a distinct "manifest reached but no usable latest" message (UPDATE_BAD_MANIFEST) instead of the misleading "manifest unreachable" text. Tests pinning behavior the prior commit left unguarded: - compose_pull is called with profile="tunnel" + all three services in proxy mode (a revert to mode-scoped pull would now fail — this is the security-motivated sidecar-validation line). - the SIGTERM path: a bare kill mid-recreate disarms the compose file and exits 143, and the prior handler is restored. - the CLI --to boundary rejects an invalid tag with exit 2 before the engine runs. - the bad-manifest message branch. 161 passing. Co-Authored-By: Claude Opus 4.8 --- cli/greffer_cli/strings.py | 6 +++++ cli/greffer_cli/update.py | 35 ++++++++++++++++++-------- cli/tests/test_main.py | 24 ++++++++++++++++++ cli/tests/test_update.py | 51 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 105 insertions(+), 11 deletions(-) diff --git a/cli/greffer_cli/strings.py b/cli/greffer_cli/strings.py index ba84c55c..a0cb166e 100644 --- a/cli/greffer_cli/strings.py +++ b/cli/greffer_cli/strings.py @@ -320,6 +320,12 @@ "(leading char a letter/digit/underscore)." ) +UPDATE_BAD_MANIFEST = ( + "✗ The version manifest was reached but did not name a usable latest " + "version (missing, not a string, or not a valid tag).\n" + " → re-run with an explicit target: `greffer update --to `" +) + UPDATE_NEEDS_CONFIRM_NO_ROLLBACK = ( "✗ Rollback safety for {current} → {target} can't be confirmed " "(the release is flagged no-in-place-rollback, or the version manifest is " diff --git a/cli/greffer_cli/update.py b/cli/greffer_cli/update.py index d030c9c0..c26af294 100644 --- a/cli/greffer_cli/update.py +++ b/cli/greffer_cli/update.py @@ -351,16 +351,15 @@ def _release_update_lock(handle) -> None: pass -def _install_sigterm_disarm(disarm: Callable[[], None]): - """Route a SIGTERM during the mutating window through ``disarm`` (restore - the prior refs) then exit, so a kill mid-update doesn't leave the compose - file pinned to an un-gated target. Ctrl-C (KeyboardInterrupt) and - exceptions are already covered by the surrounding ``finally``; this adds - the bare-SIGTERM case. Returns the prior handler to restore, or ``None`` - if one can't be installed (non-main thread / unsupported platform).""" +def _install_sigterm_handler(on_signal: Callable[[], None]): + """Route a SIGTERM during the mutating window through ``on_signal`` (which + disarms and exits with the right code), so a kill mid-update doesn't leave + the compose file pinned to an un-gated target. Ctrl-C (KeyboardInterrupt) + and exceptions are already covered by the surrounding ``finally``; this adds + the bare-SIGTERM case. Returns the prior handler to restore, or ``None`` if + one can't be installed (non-main thread / unsupported platform).""" def _handler(_signum, _frame): - disarm() - raise SystemExit(143) + on_signal() try: return signal.signal(signal.SIGTERM, _handler) except (ValueError, OSError, AttributeError): @@ -398,7 +397,12 @@ def run_update( resolved = resolve_target(explicit_to=target, manifest=manifest) current_version = compose.exec_greffer_version(compose_file) if resolved is None: - print(strings.UPDATE_NO_TARGET, file=sys.stderr) + if manifest is not None and target is None: + # Manifest reached but its `latest` is missing / non-string / + # not a valid tag (a server-side problem, not connectivity). + print(strings.UPDATE_BAD_MANIFEST, file=sys.stderr) + else: + print(strings.UPDATE_NO_TARGET, file=sys.stderr) return EXIT_PREFLIGHT_REFUSED if check_only: @@ -462,7 +466,16 @@ def _disarm() -> None: if not gate_passed: compose.set_image_refs(compose_file, old_refs) - prev_sigterm = _install_sigterm_disarm(_disarm) + def _on_sigterm() -> None: + # A kill mid-update: disarm, then exit. Once the gate has passed the + # update is already applied and the file is correct, so exit success + # (0), not 143, so a wrapper keying on the exit code does not read a + # confirmed success as a failure during the brief window before the + # handler is restored. + _disarm() + raise SystemExit(EXIT_OK if gate_passed else 143) + + prev_sigterm = _install_sigterm_handler(_on_sigterm) try: # Pull (and thereby validate) ALL node images, including the # profile-gated tunnel-sidecar in proxy mode: set_image_tag diff --git a/cli/tests/test_main.py b/cli/tests/test_main.py index 01ce45c7..3b905f0f 100644 --- a/cli/tests/test_main.py +++ b/cli/tests/test_main.py @@ -45,6 +45,30 @@ def _write_proxy_env(cfg: Path, greffer_id: str) -> None: paths.docker_compose_yml_path(cfg).write_text("# placeholder", encoding="utf-8") +def test_update_rejects_invalid_to_at_cli_boundary( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """A bad --to fails at the CLI boundary (exit 2, UPDATE_BAD_TARGET) BEFORE + the engine runs (distinct from the engine's exit-3 / UPDATE_NO_TARGET), so + the operator gets a specific "not a valid tag" message and run_update is + never reached with an unvalidated tag.""" + cfg = tmp_path / ".greffer" + cfg.mkdir(parents=True) + paths.docker_compose_yml_path(cfg).write_text("# placeholder", encoding="utf-8") + + from greffer_cli import update as update_mod + + def _fail_if_called(*a: object, **k: object) -> int: + raise AssertionError("run_update reached despite an invalid --to") + + monkeypatch.setattr(update_mod, "run_update", _fail_if_called) + result = runner.invoke( + main.app, ["update", "--to", "bad:tag", "--config-dir", str(cfg)], + ) + assert result.exit_code == 2, result.output + assert "not a valid image tag" in result.output + + def _stub_run_state_machine(captured: dict) -> "callable": """Build a stub for up.run_state_machine that records its args. diff --git a/cli/tests/test_update.py b/cli/tests/test_update.py index cb66cdcd..80ee1100 100644 --- a/cli/tests/test_update.py +++ b/cli/tests/test_update.py @@ -599,3 +599,54 @@ def test_update_refused_when_lock_held(cfg: Path, monkeypatch: pytest.MonkeyPatc assert tagged["called"] is False finally: held.close() + + +def test_pull_validates_all_images_in_tunnel_profile(cfg: Path, monkeypatch: pytest.MonkeyPatch) -> None: + # Even in proxy mode (the cfg fixture), the pull must validate ALL node + # images under the tunnel profile (set_image_tag retagged the sidecar + # line too), so a bad sidecar tag is caught now, not on a later switch. + fd = FakeDocker() + fd.install(monkeypatch) + seen: dict[str, object] = {} + + def rec_pull(f, *, profile=None, services=None): + seen["profile"] = profile + seen["services"] = services + return _ok() + + monkeypatch.setattr(compose, "compose_pull", rec_pull) + assert _run(cfg, target="0.3.4") == update.EXIT_OK + assert seen["profile"] == "tunnel" # not the proxy profile + assert set(seen["services"]) == set(update.SERVICE_REPO) # all three, incl. sidecar + + +def test_sigterm_after_retag_disarms_and_exits_143(cfg: Path, monkeypatch: pytest.MonkeyPatch) -> None: + pytest.importorskip("fcntl") # POSIX signal path + import os + import signal + + FakeDocker().install(monkeypatch) + + def kill_self(f, *, profile=None): + os.kill(os.getpid(), signal.SIGTERM) # bare kill mid-recreate + return _ok() # not reached; the installed handler raises first + + monkeypatch.setattr(compose, "compose_up", kill_self) + prev = signal.getsignal(signal.SIGTERM) + with pytest.raises(SystemExit) as ei: + _run(cfg, target="0.3.4") + assert ei.value.code == 143 # killed before the gate passed + text = (cfg / "docker-compose.yml").read_text() + assert "greffon/greffer:0.3.3" in text and "greffon/greffer:0.3.4" not in text + assert signal.getsignal(signal.SIGTERM) is prev # _restore_sigterm ran in finally + + +def test_bad_manifest_message_distinct_from_unreachable( + cfg: Path, monkeypatch: pytest.MonkeyPatch, capsys, +) -> None: + FakeDocker().install(monkeypatch) + # manifest reachable but its `latest` is unusable (coerced to None) + monkeypatch.setattr(update, "fetch_manifest", lambda url, timeout=10.0: update.Manifest(latest=None)) + assert _run(cfg) == update.EXIT_PREFLIGHT_REFUSED # no --to -> auto-latest + err = capsys.readouterr().err + assert "did not name a usable latest" in err # UPDATE_BAD_MANIFEST, not "unreachable" From 2343c0da1cef83b0ccbb933eaa2692d9e780dfb9 Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Mon, 15 Jun 2026 17:10:37 +0200 Subject: [PATCH 8/8] fix(greffer-cli): refuse https->http downgrade when fetching the manifest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The first-hop `url.startswith("https://")` check did not bind redirects: the default urllib opener transparently follows a 302 to http://, so a MITM / misconfigured CDN could downgrade the manifest channel to plaintext and serve a forged manifest — suppressing the no_rollback_from safety confirmation (the manifest's only "proceed without --confirm" signal) and, in auto-latest mode, dictating the target tag. Fetch through a dedicated opener whose redirect handler re-checks the scheme on every hop and raises on any non-https target (a URLError subclass, so the existing except turns it into a fail-closed None -> treated as unreachable -> forces --confirm-no-rollback). Also bound the read (_MAX_MANIFEST_BYTES) so a hostile endpoint can't stream an unbounded body into the process. Tests: the redirect handler refuses an http downgrade and allows an https redirect; an oversized body yields None. 163 passing. Co-Authored-By: Claude Opus 4.8 --- cli/greffer_cli/update.py | 37 ++++++++++++++++++++++++++++++++++--- cli/tests/test_update.py | 31 ++++++++++++++++++++++++++++--- 2 files changed, 62 insertions(+), 6 deletions(-) diff --git a/cli/greffer_cli/update.py b/cli/greffer_cli/update.py index c26af294..93e78303 100644 --- a/cli/greffer_cli/update.py +++ b/cli/greffer_cli/update.py @@ -75,6 +75,32 @@ class Manifest: no_rollback_from: list[str] = dataclasses.field(default_factory=list) +# A tiny JSON manifest; cap the read so a hostile endpoint can't stream an +# unbounded body into the operator's process. +_MAX_MANIFEST_BYTES = 256 * 1024 + + +class _HttpsOnlyRedirectHandler(urllib.request.HTTPRedirectHandler): + """Refuse a redirect that would downgrade the manifest fetch to plaintext. + + The default handler follows an https->http 302 transparently, which would + defeat the first-hop https guard in fetch_manifest. Re-check the scheme on + every hop and raise an HTTPError (a URLError subclass, so fetch_manifest's + ``except`` turns it into a fail-closed ``None``) on any non-https target. + """ + + def redirect_request(self, req, fp, code, msg, headers, newurl): + if not newurl.startswith("https://"): + raise urllib.error.HTTPError( + newurl, code, "refusing redirect off https for the manifest", + headers, fp, + ) + return super().redirect_request(req, fp, code, msg, headers, newurl) + + +_MANIFEST_OPENER = urllib.request.build_opener(_HttpsOnlyRedirectHandler) + + def fetch_manifest( url: str = DEFAULT_MANIFEST_URL, *, timeout: float = 10.0, ) -> Manifest | None: @@ -84,11 +110,16 @@ def fetch_manifest( # The manifest carries update targets; never fetch it over plaintext. return None try: - # https-only is enforced by the guard above. - with urllib.request.urlopen(url, timeout=timeout) as r: - body = r.read().decode("utf-8") + # _MANIFEST_OPENER re-checks the scheme on every redirect hop, so an + # https->http downgrade is refused rather than silently followed. The + # read is bounded (see _MAX_MANIFEST_BYTES). + with _MANIFEST_OPENER.open(url, timeout=timeout) as r: + raw = r.read(_MAX_MANIFEST_BYTES + 1) + body = raw.decode("utf-8") except (urllib.error.URLError, OSError, ValueError): return None + if len(raw) > _MAX_MANIFEST_BYTES: + return None # oversized -> treat as malformed/unreachable (fail-closed) try: data = json.loads(body) except json.JSONDecodeError: diff --git a/cli/tests/test_update.py b/cli/tests/test_update.py index 80ee1100..b616545a 100644 --- a/cli/tests/test_update.py +++ b/cli/tests/test_update.py @@ -438,8 +438,8 @@ class _FakeResp: def __init__(self, body: str) -> None: self._body = body.encode("utf-8") - def read(self) -> bytes: - return self._body + def read(self, n: int = -1) -> bytes: + return self._body if n < 0 else self._body[:n] def __enter__(self) -> "_FakeResp": return self @@ -451,7 +451,7 @@ def __exit__(self, *a: object) -> bool: def test_fetch_manifest_coerces_and_tolerates_malformed(monkeypatch: pytest.MonkeyPatch) -> None: holder: dict[str, str] = {} monkeypatch.setattr( - update.urllib.request, "urlopen", + update._MANIFEST_OPENER, "open", lambda url, timeout=None: _FakeResp(holder["body"]), ) # non-string latest (a list) is coerced to None, not stringified into a ref @@ -469,6 +469,31 @@ def test_fetch_manifest_coerces_and_tolerates_malformed(monkeypatch: pytest.Monk assert m.latest == "0.3.5" and m.no_rollback_from == ["a->b"] +def test_manifest_opener_refuses_https_downgrade() -> None: + # a 302 to http:// must raise (caught upstream -> fail-closed None), so the + # default urllib https->http downgrade can't reach a plaintext manifest + h = update._HttpsOnlyRedirectHandler() + with pytest.raises(update.urllib.error.HTTPError): + h.redirect_request( + req=update.urllib.request.Request("https://greffon.io/m.json"), + fp=None, code=302, msg="Found", headers={}, newurl="http://evil/m.json", + ) + # an https->https redirect is still allowed + new = h.redirect_request( + req=update.urllib.request.Request("https://greffon.io/m.json"), + fp=None, code=302, msg="Found", headers={}, newurl="https://greffon.io/v2.json", + ) + assert new is not None + + +def test_fetch_manifest_rejects_oversized_body(monkeypatch: pytest.MonkeyPatch) -> None: + big = "x" * (update._MAX_MANIFEST_BYTES + 10) + monkeypatch.setattr( + update._MANIFEST_OPENER, "open", lambda url, timeout=None: _FakeResp(big), + ) + assert update.fetch_manifest("https://x/m.json") is None + + def test_parse_readyz_defensive_shapes() -> None: # JSON that isn't an object -> not ok assert update.parse_readyz(_ok("[]")).ok is False