Skip to content

feat(greffer-cli): greffer update self-update engine (v1) - #76

Merged
omarsy merged 8 commits into
mainfrom
feat/greffer-update
Jun 15, 2026
Merged

omarsy merged 8 commits into
mainfrom
feat/greffer-update

Conversation

@omarsy

@omarsy omarsy commented Jun 15, 2026

Copy link
Copy Markdown
Member

What

Implements the v1 operator-consented self-update engine for the greffer node: a new greffer update CLI subcommand that pulls a newer published image, recreates the node, health-gates on /readyz, and rolls back on any failure.

Design: greffon/greffon docs/features/greffer-self-update/{epic,hld}.md (merged greffon#165).

The 5-step engine (greffer_cli/update.py)

  1. Resolve target — --to <tag> wins, else latest from the HTTPS version manifest (greffon.io/greffer-version.json); no reachable target aborts before touching anything.
  2. Pre-flight (abort before any pull):
    • GREFFER_ID present (else the post-recreate id-match check is a silent no-op).
    • /data is a persistent named volume (identity survives recreate).
    • rollback-safety: a no_rollback_from pair, or an unreachable manifest, requires --confirm-no-rollback.
    • idempotent by running-image digest (already on target => no-op).
  3. Rewrite + pull + recreate — retag every greffon/* image line (greffer + greffer-nginx + the profile-gated tunnel-sidecar) to the target, pull, compose up -d. A failed pull restores the prior refs (no recreate happened).
  4. Health-gate — /healthz live, then /readyz ready + id-match + version actually applied (running digest == pulled target) + all active services running; waits through degraded: registration_pending (a recreate always re-registers); fails fast on fatal, wrong id, any other degraded reason, or a climbing restart count.
  5. Rollback (the authority) — restore the prior refs (still cached locally) and recreate; verify the rolled-back node is healthy. Distinct exit codes: 0 ok / 1 failed+rolled-back / 2 rollback also failed / 3 pre-flight refused.

Mode (proxy vs tunnel) and the matching compose profile / service set are resolved from env.env, falling back to detecting the mode from the running node when GREFFER_MODE is absent.

greffer_cli/compose.py gains the supporting helpers (compose_pull, image-line rewrite + atomic write, /readyz + /healthz in-container probes, image-id / restart-count inspection). greffer update --check is read-only (prints current / target / available, changes nothing).

Tests

tests/test_update.py + tests/test_compose.py cover the engine with no Docker (compose layer monkeypatched, sleep stubbed): target resolution, rollback-safety gate, /readyz parsing, idempotency, pull-failure restore, every health-gate outcome (ready / timeout / fatal / wrong-id / degraded-other / crash-loop / not-applied), both rollback-failure paths, mode auto-detection, and the pre-flight refusals. 129 passing.

Review

Hardened via an adversarial pre-PR review (last commit). Two flagged items were deliberately kept: the crash-loop threshold (> 1 new restart) matches the HLD and the /readyz timeout is the backstop; pull-failure returns exit 1 because the node is untouched at its prior healthy version and the 4-code contract is what the merged HLD documents.

Scope

CLI engine only (v1). Out of scope here: the manager-side "update available" surfacing (Feature 1, separate manager PR) and v2 manager-triggered remote push.

🤖 Generated with Claude Code

omarsy and others added 3 commits June 15, 2026 14:47
…eadyz 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 <noreply@anthropic.com>
…ll, 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

omarsy and others added 5 commits June 15, 2026 15:47
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…l all images

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 <noreply@anthropic.com>
…n new paths

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 <noreply@anthropic.com>
…fest

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 <noreply@anthropic.com>
@omarsy

omarsy commented Jun 15, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@omarsy
omarsy merged commit be89b32 into main Jun 15, 2026
6 checks passed
@omarsy

omarsy commented Jun 15, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant