Skip to content
30 changes: 30 additions & 0 deletions app/models/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,36 @@ class InstanceLogsResponse(BaseModel):
truncated: bool = False


class RemoteUpdateRequest(BaseModel):
"""Manager-triggered remote update (greffer self-update v2).

``target_tag`` is the version the operator picked in the manager UI (e.g.
``"0.3.6"``). It is NOT trusted: the controller re-validates the tag grammar
and the spawned updater re-validates it again and runs the full provenance +
``min_supported`` floor verification before any recreate. The tag is passed
to the updater as a list arg (no shell), so it can never be a command
injection vector; the grammar check is defense-in-depth against a malformed
ref reaching ``docker``.

The pattern mirrors the v1 CLI's ``is_valid_image_tag`` Docker tag grammar
(leading alphanumeric/underscore, then alphanumeric/underscore/dot/dash, up
to 128 chars). A tag that fails it is rejected before any handler body runs;
the greffer maps the resulting RequestValidationError to 400 (app/errors.py),
so a tampered manifest value can name only a tag in the known repo, never
inject a newline or a different image.
"""
target_tag: str = Field(pattern=r"^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$")


class RemoteUpdateResponse(BaseModel):
"""202 ack: the updater container was spawned. The actual update runs
detached and reports its outcome out-of-band (the recreated greffer
re-registers / heartbeats at the new version). ``updater_id`` is the spawned
container id, for operator log correlation."""
status: Literal["accepted"] = "accepted"
updater_id: str


class TunnelConfigPushRequest(BaseModel):
"""v3 manager-pushed rathole client.toml — second-phase push for
start/stop flows.
Expand Down
70 changes: 70 additions & 0 deletions app/routers/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
InstanceDiskResponse,
InstanceLogsResponse,
InstanceStatsResponse,
RemoteUpdateRequest,
RemoteUpdateResponse,
TunnelConfigPushRequest,
TunnelConfigPushResponse,
)
Expand All @@ -42,6 +44,7 @@

# Framework-agnostic shared code imported directly — no rewrite.
from apps.utils.docker import compose, instance_logs, observe
from apps.utils.docker import updater as updater_spawn
from apps.utils.greffon import repository
from apps.utils.nginx import conf

Expand Down Expand Up @@ -279,6 +282,73 @@ def _write_pushed_client_toml(
return "ok"


@router.post("/update/", status_code=202)
def remote_update(
payload: RemoteUpdateRequest, request: Request
) -> RemoteUpdateResponse:
"""Spawn the detached v2 updater container (greffer self-update v2).

Fail-closed gating, in order:
* ``greffer_remote_update_enabled`` is the operator-sovereign switch. OFF
(default) -> 403 at the SOURCE, so remote update stays off even if a
manager is misconfigured to offer it. The flag is also advertised in the
register payload so a correct manager never shows the button when off.
* ``greffer_updater_image`` must be a configured, digest-pinned ref;
unset -> 503, never a silent ``:latest`` pull of the one container that
recreates the greffer.

The handler does NOT verify provenance or recreate anything itself: it spawns
the signed updater, which takes the ``/work`` lock and runs the full verify
-> pin -> recreate -> health-gate -> rollback flow, then returns 202 with the
spawned container id. The target tag is already validated by the model and is
passed to the updater as a list arg (no shell)."""
settings = _settings(request)
if not settings.greffer_remote_update_enabled:
raise HTTPException(
status_code=403,
detail="remote_update_disabled",
)
if not settings.greffer_updater_image:
# Flag on but image unwired: operator misconfiguration. 503 (not 500)
# so the manager reports a retry-after-config condition, not a bug.
logger.error(
"remote_update_enabled but greffer_updater_image is unset; refusing")
raise HTTPException(
status_code=503,
detail="updater_image_not_configured",
)
if not updater_spawn.is_digest_pinned(settings.greffer_updater_image):
# The most privileged container in the flow (docker.sock = host root)
# must be pinned by digest so a registry-side tag move can't swap it.
# Operator misconfiguration -> 503, fail-closed, nothing spawned.
logger.error(
"greffer_updater_image is not digest-pinned (%s); refusing",
settings.greffer_updater_image)
raise HTTPException(
status_code=503,
detail="updater_image_not_digest_pinned",
)

instance_id_var.set(None) # node-level op, not tied to a greffon instance
try:
updater_id = updater_spawn.spawn_updater(
image=settings.greffer_updater_image,
target_tag=payload.target_tag,
manifest_url=settings.greffer_version_manifest_url,
greffer_id=settings.greffer_id,
mode=settings.greffer_mode or "proxy",
data_dest=str(settings.greffon_path),
)
except updater_spawn.UpdaterSpawnError as exc:
logger.error("remote_update_spawn_failed target=%s err=%s",
payload.target_tag, exc)
raise HTTPException(status_code=500, detail="updater_spawn_failed") from exc

logger.info("remote_update_accepted target=%s updater=%s",
payload.target_tag, updater_id[:12])
return RemoteUpdateResponse(updater_id=updater_id)


@router.get("/greffon/{greffon_id}/")
def greffon_status(greffon_id: UUID) -> GreffonStatusResponse:
# Legacy Django view calls ``compose.status`` which does not exist —
Expand Down
23 changes: 23 additions & 0 deletions app/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,29 @@ def _heartbeat_interval_in_range(cls, v):
# bug Codex caught before merge (greffon/greffer#17 review).
greffer_workers_enabled: bool = False

# Remote update opt-in (greffer self-update v2). Default OFF: a
# manager-triggered remote update is root-equivalent on the operator's host,
# so the authoritative switch is greffer-side and operator-sovereign. The
# value is advertised in the register payload so the manager knows whether to
# offer the button; the controller update route (a later v2 increment) is a
# clear no-op unless this is true. Carries the ``greffer_`` prefix to bind
# GREFFER_REMOTE_UPDATE_ENABLED (the prefix pitfall noted above).
greffer_remote_update_enabled: bool = False

# Remote-update wiring (greffer self-update v2), only consulted when
# ``greffer_remote_update_enabled`` is true. ``greffer_updater_image`` is the
# DIGEST-PINNED signed updater image the controller spawns
# (``greffon/greffer-updater@sha256:...``); pinning by digest is what stops a
# moved-tag swap of the one container that recreates the greffer. Left empty
# by default so an operator who flips the flag without wiring the image gets a
# clear refusal from the route (not a silent ``:latest`` pull).
# ``greffer_version_manifest_url`` is the signed version manifest the updater
# fetches to compute the ``min_supported`` floor; the same default the v1 CLI
# uses. Both carry the ``greffer_`` prefix to bind GREFFER_UPDATER_IMAGE /
# GREFFER_VERSION_MANIFEST_URL (the prefix pitfall noted above).
greffer_updater_image: str = ""
greffer_version_manifest_url: str = "https://greffon.io/greffer-version.json"

# Self-health watchdog (greffer-observability epic, Feature #3). The
# watchdog evaluates /readyz's FATAL conditions and, when one is sustained
# past the grace window, exits the uvicorn process so ``restart:
Expand Down
5 changes: 5 additions & 0 deletions app/workers/register.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,11 @@ def _post_register(settings: Settings, address: str, token: str) -> None:
# without this field leaves Greffer.version null -> treated as below any
# floor (fail-safe deny).
"version": settings.greffer_version,
# Remote-update opt-in (greffer self-update v2), operator-sovereign and
# default off. Advertised every (re-)register so the manager knows
# whether to offer the remote "Update" button; the manager mirrors it
# for UI only and is never the authority.
"remote_update_enabled": settings.greffer_remote_update_enabled,
}
# Include greffer_mode in the register payload only when the operator
# has set it explicitly. The manager's register endpoint accepts an
Expand Down
147 changes: 147 additions & 0 deletions apps/utils/docker/updater.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
"""Spawn the detached ``greffon/greffer-updater`` container (self-update v2).

A manager-triggered remote update cannot run in the greffer process: the
updater recreates the greffer's OWN container, so it has to outlive the process
it replaces. The controller therefore spawns a SEPARATE, short-lived container
from the signed, digest-pinned updater image, mounting the docker socket plus
the same host paths the greffer itself uses, and returns 202 right away. The
updater then takes the ``/work`` lock, verifies provenance, and recreates the
stack (see ``greffer_cli.updater``).

Host-path discovery: inside a container the bind sources visible on ``/proc``
are CONTAINER paths; to mount the same host directories into a SIBLING
container we need the HOST sources. We read them off the greffer's own
container record (looked up by ``hostname`` == container id), not from env, so
``/work`` (the compose dir) and ``/data`` always track however the operator
actually mounted the greffer. Reusing the recorded mount ``Type``/``Source``
also preserves a named-volume ``/data`` as a volume mount rather than guessing a
host path.

Fail-closed: any missing mount, unknown self-container, or docker error raises
``UpdaterSpawnError`` and the route surfaces it; nothing is spawned half-wired.
"""

from __future__ import annotations

import logging
import re
import socket

import docker
from docker.types import Mount

logger = logging.getLogger("greffer")

# The updater image MUST be digest-pinned: it is the one root-equivalent,
# socket-mounted container that recreates the greffer, and it is NOT itself run
# through the cosign/floor verification it performs on the target. A mutable tag
# (``:latest``) could be repointed registry-side to swap it. Require an explicit
# ``@sha256:<64 hex>`` so a tag move can never change what runs. Anchored with
# fullmatch (repo segment, then exactly one ``@sha256:<64 hex>``, nothing
# trailing) so a pathological ref like ``a@sha256:<64hex>@sha256:<64hex>`` or
# trailing junk cannot slip past.
_DIGEST_PINNED_RE = re.compile(r"[^@\s]+@sha256:[0-9a-f]{64}")


def is_digest_pinned(ref: object) -> bool:
"""True iff ``ref`` is an image reference pinned by a sha256 digest."""
return isinstance(ref, str) and _DIGEST_PINNED_RE.fullmatch(ref) is not None

# The greffer mounts its compose dir at /app (``./:/app``) and uses
# ``$GREFFON_PATH`` (default /data) for persistent state. The updater image
# expects the compose dir at /work and the shared state at /data.
SELF_COMPOSE_DEST = "/app"
UPDATER_COMPOSE_DEST = "/work"
DOCKER_SOCK = "/var/run/docker.sock"


class UpdaterSpawnError(Exception):
"""The updater container could not be wired/spawned. Fail-closed."""


def _self_container(client):
"""The greffer's own container, looked up by hostname (== container id
inside docker). Raises UpdaterSpawnError if it can't be resolved."""
name = socket.gethostname()
try:
return client.containers.get(name)
except docker.errors.NotFound as exc:
raise UpdaterSpawnError(
f"cannot resolve own container (hostname={name!r}); "
"is the greffer running under docker with the socket mounted?"
) from exc
except docker.errors.APIError as exc:
raise UpdaterSpawnError(f"docker error resolving self: {exc}") from exc


def _mount_for(self_attrs: dict, destination: str, *, target: str) -> Mount:
"""Replicate the self-container's mount at ``destination`` onto a new
``target``, preserving the mount Type (bind vs named volume) and Source.
Raises UpdaterSpawnError if the greffer has no such mount."""
for m in self_attrs.get("Mounts", []):
if m.get("Destination") == destination:
mtype = m.get("Type", "bind")
# For a named volume the reusable source is the volume Name; for a
# bind it is the host path in Source.
source = m.get("Name") if mtype == "volume" else m.get("Source")
if not source:
raise UpdaterSpawnError(
f"mount at {destination} has no reusable source")
return Mount(target=target, source=source, type=mtype,
read_only=False)
raise UpdaterSpawnError(
f"greffer has no mount at {destination}; cannot wire the updater")


def spawn_updater(
*, image: str, target_tag: str, manifest_url: str, greffer_id: str | None,
mode: str, data_dest: str = "/data", client=None,
) -> str:
"""Spawn the detached updater container and return its id.

``image`` MUST be a digest-pinned ref (caller's responsibility / settings
contract). Mounts: the greffer's compose dir -> /work, its ``data_dest``
(default /data) -> /data, and the docker socket. The target tag is passed as
a list arg (no shell), and the updater re-validates it; provenance/floor
verification all happen inside the container before any recreate."""
if not image:
raise UpdaterSpawnError("no updater image configured")
if not is_digest_pinned(image):
# Defense-in-depth: the route also rejects this, but enforce it here so
# the contract holds for any caller of spawn_updater.
raise UpdaterSpawnError(
f"updater image must be digest-pinned (got {image!r})")
client = client or docker.from_env()
self_attrs = _self_container(client).attrs

mounts = [
_mount_for(self_attrs, SELF_COMPOSE_DEST, target=UPDATER_COMPOSE_DEST),
_mount_for(self_attrs, data_dest, target="/data"),
Mount(target=DOCKER_SOCK, source=DOCKER_SOCK, type="bind"),
]
environment = {
"GREFFER_VERSION_MANIFEST_URL": manifest_url,
"GREFFER_ID": greffer_id or "",
"GREFFER_MODE": mode,
}
try:
container = client.containers.run(
image,
["python", "-m", "greffer_cli.updater", target_tag],
detach=True,
# The updater is one-shot; drop the container when it exits so a
# series of updates doesn't litter the host. Logs are captured by
# the manager-visible exit, not the container record.
remove=True,
environment=environment,
mounts=mounts,
# Default bridge: the updater needs egress to fetch the signed
# version manifest (HTTPS) and to resolve image digests at the
# registry (``buildx imagetools inspect`` / cosign run in-container).
# It exposes no inbound port.
)
except docker.errors.APIError as exc:
raise UpdaterSpawnError(f"failed to spawn updater: {exc}") from exc
logger.info("remote_update_spawned image=%s target=%s container=%s",
image, target_tag, container.id[:12])
return container.id
26 changes: 18 additions & 8 deletions cli/greffer_cli/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,15 +237,22 @@ def _resolve_mode(env: env_file.EnvFile, compose_file: Path) -> str:
return "tunnel" if "tunnel-sidecar" in running else "proxy"


def _version_applied(compose_file: Path, target: str) -> bool:
"""Did the recreate actually advance the greffer to the pulled target?

Compares the running greffer container's image id to the pulled
``greffon/greffer:<target>`` image id. A mispublished/moved tag or an
unbumped image leaves the old image running and fails this.
def _version_applied(
compose_file: Path, target: str, *, applied_ref: str | None = None
) -> bool:
"""Did the recreate actually advance the greffer to the intended image?

Compares the running greffer container's image id to the intended image id.
``applied_ref`` overrides the lookup ref when the recreate pinned a DIGEST
rather than a tag (the v2 remote-update path: it pulls/pins
``greffon/greffer@sha256:...`` and never creates the local
``greffon/greffer:<target>`` tag, so a tag lookup would spuriously read None
and fail the gate). When unset (the v1 tag path) it falls back to the
``greffon/greffer:<target>`` tag. A mispublished/moved tag or an unbumped
image leaves the old image running and fails this.
"""
running = compose.container_image_id(compose_file, "greffer")
target_id = compose.image_id(f"{GREFFER_REPO}:{target}")
target_id = compose.image_id(applied_ref or f"{GREFFER_REPO}:{target}")
return bool(running and target_id and running == target_id)


Expand All @@ -254,6 +261,7 @@ def health_gate(
services: list[str], profile: str | None,
timeout: float, poll_interval: float = 2.0,
sleep: Callable[[float], None] = time.sleep,
applied_ref: str | None = None,
) -> str:
"""Poll until the recreated node is healthy or a failure is decided.

Expand All @@ -279,7 +287,9 @@ def health_gate(
):
return GATE_DEGRADED_OTHER
if r.status == "ready":
if not _version_applied(compose_file, target):
if not _version_applied(
compose_file, target, applied_ref=applied_ref
):
return GATE_NOT_APPLIED
svcs = compose.compose_services_running(
compose_file, profile=profile,
Expand Down
13 changes: 13 additions & 0 deletions cli/greffer_cli/updater/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
"""Greffer self-update v2: the detached updater engine.

This package is the verification + recreate logic that the signed
``greffon/greffer-updater`` image runs when the manager triggers a remote
update. It enforces the trust model in
``docs/features/greffer-self-update/v2-image-provenance-and-trust-model.md``
(cosign verify + repo-binding + digest pin + the anti-replay ``min_supported``
floor) and then reuses the v1 ``greffer_cli`` compose engine to recreate the
node, health-gate on ``/readyz``, and roll back on failure.

Every check fails closed: any verification or floor failure aborts BEFORE the
node is recreated, leaving it on its current, already-trusted image.
"""
Loading
Loading