diff --git a/pkgs/deploy/deploy.py b/pkgs/deploy/deploy.py index 9ccb06c57b..e9a5f2c8ea 100644 --- a/pkgs/deploy/deploy.py +++ b/pkgs/deploy/deploy.py @@ -62,6 +62,35 @@ standalone stdlib script, for boots where no built deploy CLI is at hand yet. +The release slice (issue #13306, implementing the release-workflow +design record doc/2026-11-23T13-09-25Z_design_release-workflow-per-app-tags, +#11177) adds the estate's release actor to the same tool: + +- `deploy release [--version X.Y.Z] [--commit ] + [--bump minor|patch]`: verifies the commit is reachable from + origin/main, judges the attestation gate for that exact commit + (the main-gate watched set, judged by the same rules + .github/scripts/release-gate.sh implements, plus the app's own + evidence workflow when the watched set does not cover it), checks + the version against the ratified #5790 discipline (short app-name + prefix, first tag 0.1.0, 0.x only, next minor or next patch only), + cuts the annotated app tag carrying the release-attestation:v1 + block and the annotated repo tag for the release point, pushes + both, and appends the release record to the release ledger in the + state dir (releases.jsonl, beside the generation logs). +- The deploy-time refusal (design §6): a deploy whose artifact + self-reports a clean X.Y.Z version claims release status and is + refused unless an attested /vX.Y.Z tag exists at the + artifact's source commit with a verifiable attestation block. + Prerelease (-dev) artifacts are unaffected. +- `deploy status` reads the release ledger beside the per-target + report; where the ledger and the tags disagree, the tag wins and + the disagreement is reported. +- A definition may carry one more optional field, `evidenceWorkflow`: + the name of the app's own test workflow when it sits outside the + main-gate watched set (design §3 part 2). Absent means the watched + set is the app's whole attestation. + The registry is JSON baked into the package at build time (the Nix expression renders the attrset definitions, replacing each derivation with its store path, without depending on it: building the @@ -126,8 +155,11 @@ # how long activation keeps probing the healthCheck before it calls the # deploy failed (#11170). timer (slice 4, #5770) names a timer-driven # oneshot service — the §3 shape had no way to express one — and when -# present must carry exactly TIMER_FIELDS. -OPTIONAL_FIELDS = {"healthTimeoutSeconds", "timer"} +# present must carry exactly TIMER_FIELDS. evidenceWorkflow (release +# slice, #13306) names the app's own test workflow when it sits outside +# the main-gate watched set, per design §3 part 2 of the release +# workflow record. +OPTIONAL_FIELDS = {"healthTimeoutSeconds", "timer", "evidenceWorkflow"} TIMER_FIELDS = {"onCalendar", "persistent", "randomizedDelaySec"} DEFAULT_HEALTH_TIMEOUT_SECONDS = 120 MAX_HEALTH_TIMEOUT_SECONDS = 3600 @@ -249,6 +281,12 @@ def validate(registry): f"{where}: healthTimeoutSeconds must be an integer in " f"1..{MAX_HEALTH_TIMEOUT_SECONDS}" ) + if "evidenceWorkflow" in defn and not ( + isinstance(defn["evidenceWorkflow"], str) and defn["evidenceWorkflow"] + ): + errors.append( + f"{where}: evidenceWorkflow must be a non-empty workflow name" + ) if "timer" in defn: # Slice 4 (#5770): the timer is rendered verbatim into a # systemd .timer unit, so its shape is as strict as the @@ -1190,6 +1228,19 @@ def execute_deploy( current, _prev = current_previous(entries) generation = next_generation_id(entries) artifact = defn["package"] + refusal = release_claim_refusal(name, defn) + if refusal is not None: + record_generation( + name, + artifact=artifact, + source_rev=_source_rev(), + actor=actor, + action="deploy_failed", + generation=generation, + result=f"refused: {refusal}", + explicit_state=state, + ) + return 1, [f"deploy {name}: REFUSED: {refusal}"] lines = [] try: install_generation(name, artifact, generation, base) @@ -1385,6 +1436,19 @@ def execute_deploy_sandbox( current, _prev = current_previous(entries) generation = next_generation_id(entries) artifact = defn["package"] + refusal = release_claim_refusal(name, defn) + if refusal is not None: + record_generation( + name, + artifact=artifact, + source_rev=_source_rev(), + actor=actor, + action="deploy_failed", + generation=generation, + result=f"refused: {refusal}", + explicit_state=state, + ) + return 1, [f"deploy {name}: REFUSED: {refusal}"] lines = [] try: link = install_generation(name, artifact, generation, base) @@ -1493,6 +1557,863 @@ def _source_rev(): return os.environ.get("DEPLOY_SOURCE_REV") or "working-tree" + +# --- Releases (issue #13306) ------------------------------------------- +# +# Oracle: doc/2026-11-23T13-09-25Z_design_release-workflow-per-app-tags +# (the release-workflow design record, #11177), implementing the +# ratified #5790 tag scheme. The deploy tool is the estate's only +# release actor: `deploy release` cuts the tags, the annotated tag +# message is the attestation of record, the release ledger in the +# state dir is its cache, and the deploy path refuses a release claim +# with no attested tag behind it (design §6). Every external effect +# goes through run_cmd (git and gh alike), so tests drive the whole +# slice with fakes and fixture repositories. + + +class ReleaseError(Exception): + """A release precondition failed; the release is refused.""" + + +# The deploy tool's own version, as packaged (pkgs/deploy/default.nix +# names the package deploy-); carried in the attestation +# block's `tool:` line. +DEPLOY_TOOL_VERSION = "0.1.0" + +ATTESTATION_HEADER = "release-attestation:v1" + +# The main-gate watched set and its trigger classes, mirroring +# .github/scripts/release-gate.sh (which mirrors main-broken.yml's +# workflow_run.workflows list). Renaming a watched workflow means +# updating all three places together — the same instruction the gate +# script carries. Since 2026-11-16 every watched workflow is non-push +# (nightly main CI), so the non-push rule below is the live one; the +# push rules stay for any workflow that regains a push trigger. +WATCHED_WORKFLOWS = [ + "nix ci", + "id", + "mcpx", + "mcpx conformance", + "mcpx nix build", + "go modules build", + "identity build", + "map build", + "id bench", +] +NON_PUSH_WORKFLOWS = { + "nix ci", + "id", + "mcpx", + "mcpx conformance", + "mcpx nix build", + "go modules build", + "identity build", + "map build", + "id bench", +} +PATH_FILTERED_WORKFLOWS = set() + +VERSION_RE = re.compile(r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$") +REPO_TAG_RE = re.compile(r"^repo/v([0-9]{8})\.([0-9]+)\.([0-9]+)$") +FULL_SHA_RE = re.compile(r"^[0-9a-f]{40}$") + + +def parse_version(text): + """'X.Y.Z' -> (X, Y, Z), or None when not exactly that shape.""" + match = VERSION_RE.fullmatch(text or "") + if match is None: + return None + return tuple(int(part) for part in match.groups()) + + +def format_version(version): + return ".".join(str(part) for part in version) + + +def _git(repo, *args): + return run_cmd(["git", "-C", repo, *args]) + + +def _git_checked(repo, *args, what): + rc, out, err = _git(repo, *args) + if rc != 0: + raise ReleaseError(f"{what} failed (exit {rc}): {err.strip()}") + return out + + +def is_ancestor_or_equal(repo, maybe_ancestor, sha): + """True when maybe_ancestor is sha or provably an ancestor of it + in the local checkout. Unprovable (object missing) is False: + fail closed, exactly like the gate script's is_ancestor_or_equal.""" + if maybe_ancestor == sha: + return True + rc, _o, _e = _git(repo, "cat-file", "-e", f"{maybe_ancestor}^{{commit}}") + if rc != 0: + return False + rc, _o, _e = _git(repo, "cat-file", "-e", f"{sha}^{{commit}}") + if rc != 0: + return False + rc, _o, _e = _git(repo, "merge-base", "--is-ancestor", maybe_ancestor, sha) + return rc == 0 + + +def gh_repo_slug(repo): + """The owner/repo the gate is judged against: $DEPLOY_GH_REPO or + $GH_REPO when set, else the checkout's origin remote.""" + for var in ("DEPLOY_GH_REPO", "GH_REPO"): + slug = os.environ.get(var) + if slug: + return slug + rc, out, _err = _git(repo, "remote", "get-url", "origin") + if rc != 0: + return None + match = re.search(r"github\.com[:/]([^/]+)/([^/]+?)(?:\.git)?$", out.strip()) + if match is None: + return None + return f"{match.group(1)}/{match.group(2)}" + + +def _gh_api(slug, endpoint): + rc, out, err = run_cmd(["gh", "api", f"repos/{slug}/{endpoint}"]) + if rc != 0: + raise ReleaseError( + f"gh api repos/{slug}/{endpoint} failed (exit {rc}): {err.strip()}" + ) + try: + return json.loads(out) + except ValueError as exc: + raise ReleaseError( + f"gh api repos/{slug}/{endpoint} returned invalid JSON: {exc}" + ) from exc + + +def remote_tags(repo): + """{tag name: commit sha} from the remote's own advertisement — + the authority on which tags exist and where they point (annotated + tags peel to their commit).""" + out = _git_checked(repo, "ls-remote", "--tags", "origin", what="git ls-remote") + tags = {} + peeled = {} + for line in out.splitlines(): + sha, _, ref = line.partition("\t") + if not ref.startswith("refs/tags/"): + continue + name = ref[len("refs/tags/"):] + if name.endswith("^{}"): + peeled[name[:-3]] = sha + else: + tags[name] = sha + tags.update(peeled) + return tags + + +def plan_release_version(existing, requested, bump): + """The version a release may cut. `existing` is the app's tagged + versions; `requested` a parsed (X, Y, Z) or None; `bump` is + 'minor' or 'patch' and decides when no version is requested. + Returns the version tuple; raises ReleaseError on any discipline + violation (design §2 precondition 3, #5790: first tag 0.1.0, 0.x + only, next minor or next patch only).""" + if requested is not None and requested[0] != 0: + raise ReleaseError( + f"version {format_version(requested)} leaves 0.x; major bumps " + "need a separate 1.0 decision (#5790)" + ) + if not existing: + if requested is not None and requested != (0, 1, 0): + raise ReleaseError( + f"the first tag for an app is 0.1.0, not {format_version(requested)}" + ) + return (0, 1, 0) + latest = max(existing) + next_minor = (0, latest[1] + 1, 0) + next_patch = (0, latest[1], latest[2] + 1) + if requested is None: + return next_minor if bump == "minor" else next_patch + if requested not in (next_minor, next_patch): + raise ReleaseError( + f"version {format_version(requested)} is not the next minor " + f"({format_version(next_minor)}) or next patch " + f"({format_version(next_patch)}) after {format_version(latest)}" + ) + return requested + + +def next_repo_tag(existing_names, today, feature): + """The repo tag for a release point (design §5, #5790 rule 4): + repo/v... The (minor, patch) counter + continues from the latest earlier point; on a new date it resets + to a 0.0 base and the point's own increment applies (a point with + any app feature increments minor and resets patch; a fix-only + point increments patch).""" + points = [] + for name in existing_names: + match = REPO_TAG_RE.fullmatch(name) + if match is not None: + points.append((match.group(1), int(match.group(2)), int(match.group(3)))) + minor = patch = 0 + if points: + last_date, last_minor, last_patch = max(points) + if last_date >= today: + minor, patch = last_minor, last_patch + if feature: + minor, patch = minor + 1, 0 + else: + patch += 1 + return f"repo/v{today}.{minor}.{patch}" + + +def _runs_by_recency(runs): + return sorted(runs, key=lambda r: r.get("created_at") or "", reverse=True) + + +def _judge_runs(runs, workflow, commit, repo): + """Pick the run that judges `commit` for a non-push workflow and + return its attestation record. Design §3 part 1 (the gate + script's non-push rule): the latest completed run on main whose + head SHA is the release commit or an ancestor of it; it must + have concluded success.""" + completed = [r for r in runs if r.get("status") == "completed"] + for run in _runs_by_recency(completed): + head = run.get("head_sha") or "" + if head and is_ancestor_or_equal(repo, head, commit): + if run.get("conclusion") != "success": + raise ReleaseError( + f"{workflow}: latest completed main run at or before " + f"the release commit concluded {run.get('conclusion')!r} " + f"(run {run.get('id')}, head {head})" + ) + return { + "workflow": workflow, + "run_id": run.get("id"), + "head_sha": head, + "conclusion": "success", + } + raise ReleaseError( + f"{workflow}: no completed run on main at or before the release " + "commit (missing main-gate signal)" + ) + + +def _judge_push_runs(runs, workflow, commit): + """The gate script's push rules, for a watched workflow that has + regained a push trigger: an exact-SHA run judges; a path-filtered + workflow with no run on the SHA falls back to its latest push run + on main; any other workflow without an exact-SHA run refuses.""" + exact = [r for r in runs if r.get("head_sha") == commit] + if exact: + run = _runs_by_recency(exact)[0] + elif workflow in PATH_FILTERED_WORKFLOWS and runs: + run = _runs_by_recency(runs)[0] + else: + raise ReleaseError(f"{workflow}: no push run on the release commit") + if run.get("status") != "completed" or run.get("conclusion") != "success": + raise ReleaseError( + f"{workflow}: push run {run.get('id')} on {run.get('head_sha')} " + f"is status={run.get('status')!r} conclusion={run.get('conclusion')!r}" + ) + return { + "workflow": workflow, + "run_id": run.get("id"), + "head_sha": run.get("head_sha"), + "conclusion": "success", + } + + +def judge_gate(slug, repo, commit, evidence_workflow): + """Judge the attestation gate for `commit` (design §3): every + watched workflow, plus the app's evidence workflow when named and + not already watched (judged by the same ancestor rule). Returns + the judged run records in watched order. Raises ReleaseError + listing every failure — fail closed: a workflow that cannot be + judged is a workflow that is not green.""" + workflows = _gh_api(slug, "actions/workflows?per_page=100").get("workflows", []) + ids = {wf.get("name"): wf.get("id") for wf in workflows} + judged = [] + failures = [] + + def judge(name, push): + wid = ids.get(name) + if wid is None: + failures.append(f"{name}: no workflow with that name in {slug}") + return + try: + if push: + runs = _gh_api( + slug, + f"actions/workflows/{wid}/runs?branch=main&event=push&per_page=100", + ).get("workflow_runs", []) + judged.append(_judge_push_runs(runs, name, commit)) + else: + runs = _gh_api( + slug, + f"actions/workflows/{wid}/runs?branch=main&per_page=100", + ).get("workflow_runs", []) + judged.append(_judge_runs(runs, name, commit, repo)) + except ReleaseError as exc: + failures.append(str(exc)) + + for name in WATCHED_WORKFLOWS: + judge(name, push=name not in NON_PUSH_WORKFLOWS) + if evidence_workflow and evidence_workflow not in WATCHED_WORKFLOWS: + judge(evidence_workflow, push=False) + if failures: + raise ReleaseError("attestation gate is not green: " + "; ".join(failures)) + return judged + + +def compose_attestation(app, version, commit, evidence_workflow, runs, actor, at): + """The release-attestation:v1 block (design §4): the record of + authority, carried in the annotated tag message.""" + gate = ( + f"main-gate + {evidence_workflow}" + if evidence_workflow + else "main-gate + none" + ) + lines = [ + ATTESTATION_HEADER, + f"app: {app}", + f"version: {version}", + f"commit: {commit}", + f"gate: {gate}", + ] + for run in runs: + lines.append( + f"run: {run['workflow']} {run['run_id']} success {run['head_sha']}" + ) + lines += [ + f"actor: {actor}", + f"tool: deploy.py {DEPLOY_TOOL_VERSION}", + f"at: {at}", + ] + return "\n".join(lines) + + +def parse_attestation(message): + """Parse a release-attestation:v1 block out of a tag message. + Returns {app, version, commit, runs: [(workflow, run_id, + conclusion, head_sha)]} or None when no well-formed block is + present. Fail closed: a block that does not parse is no + attestation (design §6).""" + if not message: + return None + lines = message.splitlines() + try: + start = lines.index(ATTESTATION_HEADER) + except ValueError: + return None + fields = {} + runs = [] + for line in lines[start + 1:]: + if line.startswith("run: "): + # " "; workflow + # names contain spaces, so split from the right. + parts = line[len("run: "):].rsplit(" ", 3) + if len(parts) != 4: + return None + runs.append(tuple(parts)) + elif ": " in line: + key, value = line.split(": ", 1) + fields[key.strip()] = value.strip() + elif line.strip() == "": + continue + else: + break + app = fields.get("app") + version = fields.get("version") + commit = fields.get("commit") + if not app or not version or not commit or not runs: + return None + if parse_version(version) is None or not FULL_SHA_RE.fullmatch(commit): + return None + if any(conclusion != "success" for _w, _i, conclusion, _s in runs): + return None + return {"app": app, "version": version, "commit": commit, "runs": runs} + + +def verify_attestation(message, app, version, commit): + """The parsed attestation when it names exactly this app, + version and commit; otherwise None.""" + parsed = parse_attestation(message) + if parsed is None: + return None + if ( + parsed["app"] != app + or parsed["version"] != version + or parsed["commit"] != commit + ): + return None + return parsed + + +def app_evidence_workflow(registry, app): + """The app's recorded evidence workflow (design §3 part 2), or + None when the registry records none. An app resolves to the + definition named after it, or to the definitions whose entry + point is the app's binary (bin/) — the fleet app, for + instance, is deployed as the queue-broker and secrets-broker + services, both running bin/fleet. Definitions resolving to one + app must agree on the field; disagreement is registry data in + conflict and refuses. An app no definition resolves to is not + this tool's to release.""" + candidates = [] + if app in registry: + candidates.append(registry[app]) + else: + for defn in registry.values(): + if os.path.basename(defn.get("entryPoint", "")) == app: + candidates.append(defn) + if not candidates: + raise ReleaseError( + f"app {app!r} is not in the deploy registry (no definition " + "names it or runs its binary)" + ) + workflows = { + d["evidenceWorkflow"] for d in candidates if d.get("evidenceWorkflow") + } + if len(workflows) > 1: + raise ReleaseError( + f"registry definitions for app {app!r} disagree on " + f"evidenceWorkflow: {', '.join(sorted(workflows))}" + ) + return workflows.pop() if workflows else None + + +def releases_path(explicit_state=None): + return os.path.join(state_dir(explicit_state), "releases.jsonl") + + +def read_releases(explicit_state=None): + path = releases_path(explicit_state) + if not os.path.exists(path): + return [] + entries = [] + with open(path, "r", encoding="utf-8") as fh: + for lineno, line in enumerate(fh, 1): + line = line.strip() + if not line: + continue + try: + entries.append(json.loads(line)) + except ValueError as exc: + raise ValueError( + f"release ledger {path} line {lineno} is not valid JSON: {exc}" + ) from exc + return entries + + +def record_release(entry, explicit_state=None): + path = releases_path(explicit_state) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "a", encoding="utf-8") as fh: + fh.write(json.dumps(entry, sort_keys=True) + "\n") + return entry + + +def local_tag_attestations(repo): + """{tag name: parsed attestation} for the attested tags in the + local checkout, read from the tag messages (the record of + authority).""" + rc, out, _err = _git(repo, "tag", "--list") + if rc != 0: + return {} + found = {} + for name in out.split(): + rc, message, _err = _git( + repo, "for-each-ref", f"refs/tags/{name}", "--format=%(contents)" + ) + if rc != 0: + continue + parsed = parse_attestation(message) + if parsed is not None: + found[name] = parsed + return found + + +def format_releases(entries, tag_attestations): + """The `deploy status` release report (design §4): releases and + their gate evidence. With tag_attestations (the tags read from a + checkout), the tag is the authority: a ledger record the tags do + not confirm is a disagreement, never a release. With None (no + checkout at hand), the ledger is listed unverified.""" + lines = ["releases:"] + if tag_attestations is None: + if not entries: + lines.append(" none recorded") + for entry in entries: + lines.append( + f" {entry.get('tag')}: app {entry.get('app')} version " + f"{entry.get('version')} commit {entry.get('commit')} " + "(ledger only; tags not read)" + ) + return lines + by_tag = {entry.get("tag"): entry for entry in entries} + names = sorted(set(by_tag) | set(tag_attestations)) + if not names: + lines.append(" none recorded") + return lines + for name in names: + parsed = tag_attestations.get(name) + entry = by_tag.get(name) + if parsed is not None: + runs = ", ".join( + f"{wf} run {run_id}" for wf, run_id, _c, _s in parsed["runs"] + ) + lines.append( + f" {name}: app {parsed['app']} version {parsed['version']} " + f"commit {parsed['commit']} (attested; gate: {runs})" + ) + if entry is not None and ( + entry.get("commit") != parsed["commit"] + or entry.get("version") != parsed["version"] + ): + lines.append( + f" DISAGREEMENT: the ledger records {name} at commit " + f"{entry.get('commit')} version {entry.get('version')}; " + "the tag wins" + ) + elif entry is not None: + lines.append( + f" DISAGREEMENT: the ledger records {name} (app " + f"{entry.get('app')} version {entry.get('version')} commit " + f"{entry.get('commit')}) but no attested tag confirms it; " + "the tag wins — not a release" + ) + return lines + + + +def execute_release( + app, + registry, + *, + repo, + state=None, + requested_version=None, + commit_arg=None, + bump="minor", + dry_run=False, + actor=None, +): + """`deploy release `: cut the app's next release tag and the + release point's repo tag, per the design record §2's order: + verify preconditions, compose the attestation, create the + annotated tags, push, append the ledger record, print the tags + and the gate verdicts. Returns (exit_code, lines); every refusal + is reported with nothing pushed and nothing recorded. A failure + after a tag is created but before the push leaves only a local + tag, which the next invocation's precondition pass deletes.""" + actor = actor or getpass.getuser() + lines = [] + created = [] + try: + evidence = app_evidence_workflow(registry, app) + if not dry_run: + _git_checked(repo, "fetch", "origin", "main", what="git fetch origin main") + rc, origin_main, err = _git(repo, "rev-parse", "origin/main^{commit}") + if rc != 0: + raise ReleaseError(f"cannot resolve origin/main in {repo}: {err.strip()}") + origin_main = origin_main.strip() + commit = origin_main + if commit_arg: + rc, resolved, err = _git(repo, "rev-parse", f"{commit_arg}^{{commit}}") + if rc != 0: + raise ReleaseError( + f"cannot resolve commit {commit_arg!r}: {err.strip()}" + ) + commit = resolved.strip() + if not is_ancestor_or_equal(repo, commit, origin_main): + raise ReleaseError( + f"commit {commit} is not reachable from origin/main " + f"({origin_main}); releases are cut from main (design §2)" + ) + tags = remote_tags(repo) + existing = [] + for name in tags: + if name.startswith(f"{app}/v"): + version = parse_version(name[len(app) + 2:]) + if version is not None: + existing.append(version) + requested = None + if requested_version is not None: + requested = parse_version(requested_version) + if requested is None: + raise ReleaseError( + f"--version {requested_version!r} is not an X.Y.Z version" + ) + # Precondition 4 (design §2) is checked before the + # discipline: a requested tag that already exists is a + # duplicate or a collision, and says so. + requested_tag = f"{app}/v{format_version(requested)}" + if requested_tag in tags: + if tags[requested_tag] == commit: + raise ReleaseError( + f"{requested_tag} already exists at {commit}: " + "already released" + ) + raise ReleaseError( + f"{requested_tag} already exists at " + f"{tags[requested_tag]}, not at {commit}" + ) + version = plan_release_version(existing, requested, bump) + version_text = format_version(version) + app_tag = f"{app}/v{version_text}" + if app_tag in tags: + if tags[app_tag] == commit: + raise ReleaseError(f"{app_tag} already exists at {commit}: already released") + raise ReleaseError( + f"{app_tag} already exists at {tags[app_tag]}, not at {commit}" + ) + today = datetime.now(timezone.utc).strftime("%Y%m%d") + feature = not existing or version[2] == 0 + repo_tag = next_repo_tag(list(tags), today, feature) + if repo_tag in tags: + raise ReleaseError(f"{repo_tag} already exists on the remote") + # Unpublished local leftovers from a failed earlier run are + # deleted on this pass (design §2); a tag the remote also has + # was already refused above. + for name in (app_tag, repo_tag): + rc, local_commit, _e = _git(repo, "rev-parse", f"refs/tags/{name}^{{commit}}") + if rc == 0 and name not in tags: + _git(repo, "tag", "-d", name) + lines.append( + f"removed unpublished local tag {name} " + f"(leftover at {local_commit.strip()})" + ) + slug = gh_repo_slug(repo) + if slug is None: + raise ReleaseError( + "cannot determine the GitHub repo (no DEPLOY_GH_REPO/GH_REPO " + "and no github.com origin remote); the gate cannot be judged" + ) + runs = judge_gate(slug, repo, commit, evidence) + at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + block = compose_attestation(app, version_text, commit, evidence, runs, actor, at) + app_message = f"{app} v{version_text}\n\n{block}\n" + repo_version = repo_tag[len("repo/v"):] + repo_block = compose_attestation( + "repo", repo_version, commit, evidence, runs, actor, at + ) + repo_message = ( + f"repo release point {repo_version}\n\n" + f"app-tag: {app_tag}\n\n{repo_block}\n" + ) + verdicts = "; ".join( + f"{run['workflow']} run {run['run_id']} success at {run['head_sha']}" + for run in runs + ) + if dry_run: + lines.append( + "deploy release --dry-run: no tags cut, nothing recorded " + "(origin/main as last fetched)" + ) + lines.append(f" would cut {app_tag} at {commit}") + lines.append(f" would cut {repo_tag} at {commit}") + lines.append(f" gate: {verdicts}") + return 0, lines + _git_checked( + repo, "tag", "-a", app_tag, "-m", app_message, commit, + what=f"create tag {app_tag}", + ) + created.append(app_tag) + _git_checked( + repo, "tag", "-a", repo_tag, "-m", repo_message, commit, + what=f"create tag {repo_tag}", + ) + created.append(repo_tag) + _git_checked( + repo, "push", "origin", f"refs/tags/{app_tag}", f"refs/tags/{repo_tag}", + what="push the release tags", + ) + record_release( + { + "app": app, + "version": version_text, + "commit": commit, + "tag": app_tag, + "repo_tag": repo_tag, + "gate": runs, + "actor": actor, + "at": at, + }, + explicit_state=state, + ) + lines.append(f"released {app_tag} at {commit}") + lines.append(f"released {repo_tag} at {commit}") + lines.append(f"gate: {verdicts}") + return 0, lines + except ReleaseError as exc: + lines.append(f"deploy release {app}: REFUSED: {exc}") + if created: + lines.append( + f"note: local tag(s) {', '.join(created)} were created but " + "not pushed; the next invocation's precondition pass " + "removes them" + ) + return 1, lines + + +def probe_artifact_version(defn): + """The version the artifact self-reports, read from its own + `Derived version:` line (design §4 part 3; the fleet README's + release procedure step 3) by running its entry point with the + `version` argument. Returns the version token, or None when the + artifact reports none (not executable, no such line, any error). + A read-only probe; tests replace it like probe_health.""" + path = os.path.join(defn["package"], defn["entryPoint"]) + if not (os.path.isfile(path) and os.access(path, os.X_OK)): + return None + try: + proc = subprocess.run( + [path, "version"], capture_output=True, text=True, timeout=15 + ) + except (OSError, subprocess.SubprocessError): + return None + for line in proc.stdout.splitlines(): + if line.startswith("Derived version:"): + return line.split(":", 1)[1].strip() or None + return None + + +def _verify_release_claim(slug, app, version, source_rev): + """None when an attested /v tag exists at + source_rev with a verifiable attestation block; otherwise the + reason it does not verify.""" + tag = f"{app}/v{version}" + try: + ref = _gh_api(slug, f"git/ref/tags/{tag}") + obj = ref.get("object", {}) + if obj.get("type") != "tag": + return f"{tag} is not an annotated tag and carries no attestation" + tag_object = _gh_api(slug, f"git/tags/{obj.get('sha')}") + except ReleaseError as exc: + return f"the attested tag cannot be read: {exc}" + points_at = tag_object.get("object", {}).get("sha") + if points_at != source_rev: + return ( + f"{tag} points at {points_at}, not the artifact's " + f"source commit {source_rev}" + ) + if verify_attestation(tag_object.get("message"), app, version, source_rev) is None: + return ( + f"{tag} carries no verifiable release-attestation:v1 " + "block naming this commit" + ) + return None + + +def release_claim_refusal(name, defn): + """Design §6 point 1: a deploy whose artifact self-reports a + clean X.Y.Z claims release status and is refused unless an + attested /vX.Y.Z tag exists at the artifact's source commit + with a verifiable attestation block. The app a definition speaks + for is its own name or the app whose binary it runs (bin/) + — the fleet app is deployed as the queue-broker and + secrets-broker services — so a claim verifies under either name. + Returns the refusal reason, or None when the deploy may proceed + (no claim, or a verified attested tag). Fail closed: a claim + that cannot be verified is a claim refused.""" + reported = probe_artifact_version(defn) + if reported is None or parse_version(reported) is None: + # No version reported, or a -dev / prerelease string: no + # release claim, and prerelease deploys are untouched by the + # refusal (design §6). + return None + source_rev = _source_rev() + if not FULL_SHA_RE.fullmatch(source_rev): + return ( + f"artifact claims release {reported} but its source commit is " + f"not recorded (DEPLOY_SOURCE_REV={source_rev!r}); the attested " + "tag cannot be checked — deploy refused (design §6)" + ) + slug = gh_repo_slug(os.getcwd()) + if slug is None: + return ( + f"artifact claims release {reported} but the GitHub repo is " + "unknown (no DEPLOY_GH_REPO/GH_REPO and no github.com origin " + "in the working directory); the attested tag cannot be " + "checked — deploy refused (design §6)" + ) + apps = [name] + binary_app = os.path.basename(defn.get("entryPoint", "")) + if binary_app and binary_app != name: + apps.append(binary_app) + reasons = [] + for app in apps: + reason = _verify_release_claim(slug, app, reported, source_rev) + if reason is None: + return None + reasons.append(reason) + return ( + f"artifact claims release {reported} but no attested tag verifies: " + + "; ".join(reasons) + + " — deploy refused (design §6)" + ) + + +def _release_args(rest): + """Parse the arguments after `release`: one positional app plus + --version/--commit/--bump in '--flag value' or '--flag=value' + form. Returns (app, options) or (None, error).""" + app = None + options = {} + it = iter(rest) + for arg in it: + flag = next( + ( + f + for f in ("--version", "--commit", "--bump") + if arg == f or arg.startswith(f + "=") + ), + None, + ) + if flag is None: + if app is not None: + return None, f"unexpected argument {arg!r} after the app name" + app = arg + continue + if flag in options: + return None, f"{flag} given more than once" + value = next(it, None) if arg == flag else arg[len(flag) + 1:] + if not value: + return None, f"{flag} needs a value" + options[flag] = value + if app is None: + return None, "release needs an app name" + bump = options.get("--bump", "minor") + if bump not in ("minor", "patch"): + return None, f"--bump must be minor or patch, got {bump!r}" + return app, { + "requested_version": options.get("--version"), + "commit_arg": options.get("--commit"), + "bump": bump, + } + + +def cmd_status_all(registry, state, repo): + """Bare `deploy status`: every target's report (health unprobed), + then the release report (design §4) — the tags are read when a + git checkout is at hand, the ledger listed unverified otherwise.""" + for name in sorted(registry): + try: + entries = read_generations(name, state) + except ValueError as exc: + print(f"deploy: {exc}", file=sys.stderr) + return 1 + print(format_status(name, registry[name], entries)) + try: + entries = read_releases(state) + except ValueError as exc: + print(f"deploy: {exc}", file=sys.stderr) + return 1 + attestations = None + rc, _o, _e = _git(repo, "rev-parse", "--git-dir") + if rc == 0: + attestations = local_tag_attestations(repo) + for line in format_releases(entries, attestations): + print(line) + return 0 + # --- Command dispatch ------------------------------------------------------ NOT_IMPLEMENTED = ( @@ -1524,6 +2445,7 @@ def main(argv): "--profile-base", "--unit-dir", "--scope", + "--repo", ) if arg == f or arg.startswith(f + "=") ), @@ -1545,6 +2467,9 @@ def main(argv): explicit_state = flag_values.get("--state-dir") explicit_base = flag_values.get("--profile-base") explicit_units = flag_values.get("--unit-dir") + explicit_repo = ( + flag_values.get("--repo") or os.environ.get("DEPLOY_REPO") or os.getcwd() + ) scope = flag_values.get("--scope") or os.environ.get("DEPLOY_SCOPE") or "system" if scope not in ("system", "user"): print(f"deploy: --scope must be system or user, got {scope!r}", file=sys.stderr) @@ -1554,7 +2479,9 @@ def main(argv): usage = ( "usage: deploy [--registry PATH] [--state-dir PATH] " "[--profile-base PATH] [--unit-dir PATH] [--scope system|user] " - "list | restore | [rollback|status] [--dry-run]" + "[--repo PATH] list | restore | status | " + "release [--version X.Y.Z] [--commit SHA] [--bump minor|patch] | " + " [rollback|status] [--dry-run]" ) if not args: print(__doc__.splitlines()[0], file=sys.stderr) @@ -1609,6 +2536,25 @@ def main(argv): for err in errors: print(f"deploy: invalid definition: {err}", file=sys.stderr) return 1 + if args[0] == "release": + app, parsed = _release_args(args[1:]) + if app is None: + print(f"deploy: {parsed}", file=sys.stderr) + print(usage, file=sys.stderr) + return 2 + code, lines = execute_release( + app, + registry, + repo=explicit_repo, + state=explicit_state, + dry_run=dry_run, + **parsed, + ) + for line in lines: + print(line, file=sys.stderr if code else sys.stdout) + return code + if args[0] == "status" and len(args) == 1: + return cmd_status_all(registry, explicit_state, explicit_repo) name = args[0] if name not in registry: print(f"deploy: unknown target {name!r}", file=sys.stderr) @@ -1641,6 +2587,19 @@ def main(argv): if defn["healthCheck"] is not None: health = probe_health(defn["healthCheck"]) print(format_status(name, defn, entries, health)) + try: + app_releases = [ + e for e in read_releases(explicit_state) if e.get("app") == name + ] + except ValueError as exc: + print(f"deploy: {exc}", file=sys.stderr) + return 1 + for entry in app_releases: + print( + f"release: {entry.get('tag')} at {entry.get('commit')} " + f"(ledger record {entry.get('at')} by {entry.get('actor')}; " + "the tag's attestation block is the record of authority)" + ) return 0 if action == "deploy": steps = plan_deploy(name, defn, entries, explicit_base) diff --git a/pkgs/deploy/services.nix b/pkgs/deploy/services.nix index b5d0450bc8..ff9478b256 100644 --- a/pkgs/deploy/services.nix +++ b/pkgs/deploy/services.nix @@ -52,6 +52,11 @@ ports = [ 4801 ]; restart = "on-failure"; healthCheck = "http://100.99.113.103:4801/healthz"; + # Release attestation (release-workflow design §3 part 2, + # #13306): the fleet app's own test workflow sits outside the + # main-gate watched set, so the release verb requires it as + # per-app evidence. + evidenceWorkflow = "fleet-rust-tests"; targets = [ "laptop" ]; class = "systemd"; }; @@ -71,6 +76,11 @@ ports = [ 4800 ]; restart = "on-failure"; healthCheck = "http://100.99.113.103:4800/health"; + # Release attestation (release-workflow design §3 part 2, + # #13306): the fleet app's own test workflow sits outside the + # main-gate watched set, so the release verb requires it as + # per-app evidence. + evidenceWorkflow = "fleet-rust-tests"; targets = [ "laptop" ]; class = "systemd"; }; diff --git a/pkgs/deploy/test_deploy_release.py b/pkgs/deploy/test_deploy_release.py new file mode 100644 index 0000000000..811c0144e6 --- /dev/null +++ b/pkgs/deploy/test_deploy_release.py @@ -0,0 +1,516 @@ +#!/usr/bin/env python3 +"""Coverage for the deploy release slice (issue #13306). + +Oracle: doc/2026-11-23T13-09-25Z_design_release-workflow-per-app-tags +(the release-workflow design record, #11177) — §2 preconditions and +order, §3 attestation judging (the rules .github/scripts/release-gate.sh +implements), §4 the attestation block and the ledger, §5 the repo tag, +§6 the deploy-time refusal. + +git effects are REAL against a fixture repository and bare remote in a +temp dir; gh effects are faked by a run_cmd wrapper that delegates git +to the real runner and answers gh api endpoints from fixtures. The +artifact version probe is replaced like probe_health is in the +slice-3 tests. + +Usage: test_deploy_release.py [path-to-deploy.py] +""" + +import importlib.util +import json +import os +import subprocess +import sys +import tempfile +import unittest +from datetime import datetime, timezone + +DEPLOY_PATH = ( + sys.argv[1] + if len(sys.argv) > 1 + else os.path.join(os.path.dirname(os.path.abspath(__file__)), "deploy.py") +) +spec = importlib.util.spec_from_file_location("deploy", DEPLOY_PATH) +deploy = importlib.util.module_from_spec(spec) +spec.loader.exec_module(deploy) + +BASE_DEFN = { + "package": "/placeholder/pkg", + "entryPoint": "bin/svc", + "args": [], + "environment": {}, + "secrets": [], + "user": "user", + "ports": [8080], + "restart": "on-failure", + "healthCheck": None, + "targets": ["amd"], + "class": "systemd", +} + + +def defn(**overrides): + merged = dict(BASE_DEFN) + merged.update(overrides) + return merged + + +# The fleet app is deployed as two services running bin/fleet; mcpx is +# a definition named after its app with no evidence workflow. +REGISTRY = { + "queue-broker": defn( + entryPoint="bin/fleet", evidenceWorkflow="fleet-rust-tests" + ), + "secrets-broker": defn( + entryPoint="bin/fleet", evidenceWorkflow="fleet-rust-tests" + ), + "mcpx": defn(entryPoint="bin/mcpx"), +} + + +def git(repo, *args): + proc = subprocess.run( + ["git", "-C", repo, *args], capture_output=True, text=True + ) + if proc.returncode != 0: + raise AssertionError(f"git {' '.join(args)} failed: {proc.stderr}") + return proc.stdout.strip() + + +class FakeGh: + """Answers the gh api endpoints deploy.py reads, from fixtures.""" + + def __init__(self, parent_sha, head_sha): + self.workflows = [ + {"id": i + 1, "name": name} + for i, name in enumerate(deploy.WATCHED_WORKFLOWS) + ] + [{"id": 10, "name": "fleet-rust-tests"}] + self.runs = {} + for wf in self.workflows: + sha = head_sha if wf["name"] == "fleet-rust-tests" else parent_sha + self.runs[wf["id"]] = [ + { + "id": 100 + wf["id"], + "head_sha": sha, + "status": "completed", + "conclusion": "success", + "created_at": "2026-11-23T00:00:00Z", + } + ] + self.tag_refs = {} # tag name -> tag object sha + self.tag_objects = {} # tag object sha -> {"message", "commit"} + + def serve_tag(self, name, message, commit): + obj_sha = "a" * 40 if not self.tag_objects else "b" * 40 + self.tag_refs[name] = obj_sha + self.tag_objects[obj_sha] = {"message": message, "commit": commit} + + def __call__(self, argv): + if argv[0] == "gh": + endpoint = argv[2].split("/", 3)[3] # after repos// + if endpoint.startswith("actions/workflows?"): + return 0, json.dumps({"workflows": self.workflows}), "" + if endpoint.startswith("actions/workflows/"): + wid = int(endpoint.split("/")[2]) + return ( + 0, + json.dumps({"workflow_runs": self.runs.get(wid, [])}), + "", + ) + if endpoint.startswith("git/ref/tags/"): + name = endpoint[len("git/ref/tags/"):] + if name not in self.tag_refs: + return 1, "", "gh: Not Found (HTTP 404)" + return ( + 0, + json.dumps( + {"object": {"sha": self.tag_refs[name], "type": "tag"}} + ), + "", + ) + if endpoint.startswith("git/tags/"): + obj = self.tag_objects.get(endpoint[len("git/tags/"):]) + if obj is None: + return 1, "", "gh: Not Found (HTTP 404)" + return ( + 0, + json.dumps( + { + "message": obj["message"], + "object": {"sha": obj["commit"], "type": "commit"}, + } + ), + "", + ) + return 1, "", f"unexpected gh endpoint {endpoint}" + if argv[0] == "git": + return self.real_run_cmd(argv) + return 0, "", "" + + +class ReleaseFixture(unittest.TestCase): + def setUp(self): + self._real_run_cmd = deploy.run_cmd + self.tmp = tempfile.mkdtemp(prefix="deploy-release-test-") + self.remote = os.path.join(self.tmp, "remote.git") + self.work = os.path.join(self.tmp, "work") + self.state = os.path.join(self.tmp, "state") + subprocess.run( + ["git", "init", "--bare", self.remote], + capture_output=True, check=True, + ) + subprocess.run( + ["git", "init", self.work], capture_output=True, check=True + ) + git(self.work, "symbolic-ref", "HEAD", "refs/heads/main") + git(self.work, "config", "user.email", "test@example.invalid") + git(self.work, "config", "user.name", "deploy test") + git(self.work, "remote", "add", "origin", self.remote) + with open(os.path.join(self.work, "a.txt"), "w") as fh: + fh.write("one\n") + git(self.work, "add", "a.txt") + git(self.work, "commit", "-qm", "one") + self.parent = git(self.work, "rev-parse", "HEAD") + with open(os.path.join(self.work, "b.txt"), "w") as fh: + fh.write("two\n") + git(self.work, "add", "b.txt") + git(self.work, "commit", "-qm", "two") + self.head = git(self.work, "rev-parse", "HEAD") + git(self.work, "push", "origin", "main") + self.gh = FakeGh(self.parent, self.head) + self.gh.real_run_cmd = self._real_run_cmd + deploy.run_cmd = self.gh + self._old_env = { + k: os.environ.get(k) for k in ("DEPLOY_GH_REPO", "DEPLOY_SOURCE_REV") + } + os.environ["DEPLOY_GH_REPO"] = "owner/repo" + + def tearDown(self): + deploy.run_cmd = self._real_run_cmd + for key, value in self._old_env.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + + def remote_tag_names(self): + out = git(self.work, "ls-remote", "--tags", "origin") + names = [] + for line in out.splitlines(): + if not line: + continue + ref = line.split("\t")[1] + name = ref[len("refs/tags/"):] + if not name.endswith("^{}"): + names.append(name) + return sorted(names) + + def release(self, app="fleet", **kwargs): + kwargs.setdefault("repo", self.work) + kwargs.setdefault("state", self.state) + kwargs.setdefault("actor", "test-actor") + return deploy.execute_release(app, REGISTRY, **kwargs) + + def today(self): + return datetime.now(timezone.utc).strftime("%Y%m%d") + + +class TestReleaseSuccess(ReleaseFixture): + def test_release_against_fixture_remote(self): + code, lines = self.release() + self.assertEqual(code, 0, lines) + repo_tag = f"repo/v{self.today()}.1.0" + self.assertEqual(self.remote_tag_names(), ["fleet/v0.1.0", repo_tag]) + # Both tags point at the head commit. + self.assertEqual( + git(self.work, "rev-parse", "fleet/v0.1.0^{commit}"), self.head + ) + # The attestation block parses and verifies (the §4 record). + message = git( + self.work, "for-each-ref", "refs/tags/fleet/v0.1.0", + "--format=%(contents)", + ) + parsed = deploy.verify_attestation(message, "fleet", "0.1.0", self.head) + self.assertIsNotNone(parsed) + judged = {wf for wf, _id, _c, _s in parsed["runs"]} + self.assertEqual( + judged, set(deploy.WATCHED_WORKFLOWS) | {"fleet-rust-tests"} + ) + # The ledger round-trips through the status report: the tag + # confirms the record, no disagreement. + entries = deploy.read_releases(self.state) + self.assertEqual(len(entries), 1) + self.assertEqual(entries[0]["tag"], "fleet/v0.1.0") + self.assertEqual(entries[0]["repo_tag"], repo_tag) + report = deploy.format_releases( + entries, deploy.local_tag_attestations(self.work) + ) + text = "\n".join(report) + self.assertIn("fleet/v0.1.0: app fleet version 0.1.0", text) + self.assertIn("attested", text) + self.assertNotIn("DISAGREEMENT", text) + + def test_second_and_third_releases_follow_the_discipline(self): + code, lines = self.release() + self.assertEqual(code, 0, lines) + code, lines = self.release(bump="patch") + self.assertEqual(code, 0, lines) + code, lines = self.release() + self.assertEqual(code, 0, lines) + self.assertEqual( + self.remote_tag_names(), + [ + "fleet/v0.1.0", + "fleet/v0.1.1", + "fleet/v0.2.0", + f"repo/v{self.today()}.1.0", + f"repo/v{self.today()}.1.1", + f"repo/v{self.today()}.2.0", + ], + ) + + def test_dry_run_cuts_nothing(self): + code, lines = self.release(dry_run=True) + self.assertEqual(code, 0, lines) + self.assertIn("would cut fleet/v0.1.0", "\n".join(lines)) + self.assertEqual(self.remote_tag_names(), []) + self.assertEqual(deploy.read_releases(self.state), []) + + +class TestReleaseRefusals(ReleaseFixture): + def test_red_gate_refuses(self): + self.gh.runs[2][0]["conclusion"] = "failure" # workflow "id" + code, lines = self.release() + self.assertEqual(code, 1) + self.assertIn("REFUSED", "\n".join(lines)) + self.assertIn("attestation gate is not green", "\n".join(lines)) + self.assertEqual(self.remote_tag_names(), []) + self.assertEqual(deploy.read_releases(self.state), []) + + def test_missing_gate_signal_refuses(self): + self.gh.runs[1][0]["head_sha"] = "f" * 40 # not in the history + code, lines = self.release() + self.assertEqual(code, 1) + self.assertIn("no completed run on main at or before", "\n".join(lines)) + self.assertEqual(self.remote_tag_names(), []) + + def test_commit_off_main_refuses(self): + git(self.work, "checkout", "-qb", "side") + with open(os.path.join(self.work, "c.txt"), "w") as fh: + fh.write("three\n") + git(self.work, "add", "c.txt") + git(self.work, "commit", "-qm", "three") + side = git(self.work, "rev-parse", "HEAD") + code, lines = self.release(commit_arg=side) + self.assertEqual(code, 1) + self.assertIn("not reachable from origin/main", "\n".join(lines)) + self.assertEqual(self.remote_tag_names(), []) + + def test_version_discipline_refusals(self): + # First tag must be 0.1.0. + code, lines = self.release(app="mcpx", requested_version="0.2.0") + self.assertEqual(code, 1) + self.assertIn("the first tag for an app is 0.1.0", "\n".join(lines)) + # Major bumps are refused outright. + code, lines = self.release(app="mcpx", requested_version="1.0.0") + self.assertEqual(code, 1) + self.assertIn("leaves 0.x", "\n".join(lines)) + code, lines = self.release() + self.assertEqual(code, 0, lines) + # Skipping a version is refused. + code, lines = self.release(requested_version="0.3.0") + self.assertEqual(code, 1) + self.assertIn("is not the next minor", "\n".join(lines)) + # Re-cutting the same version at the same commit is refused. + code, lines = self.release(requested_version="0.1.0") + self.assertEqual(code, 1) + self.assertIn("already released", "\n".join(lines)) + self.assertEqual(self.remote_tag_names(), ["fleet/v0.1.0", f"repo/v{self.today()}.1.0"]) + + def test_unknown_app_refuses(self): + code, lines = self.release(app="nope") + self.assertEqual(code, 1) + self.assertIn("not in the deploy registry", "\n".join(lines)) + + +class TestDeployTimeRefusal(ReleaseFixture): + def setUp(self): + super().setUp() + self.defn = defn(entryPoint="bin/fleet") + self._real_probe = deploy.probe_artifact_version + deploy.probe_artifact_version = lambda defn: "0.1.0" + os.environ["DEPLOY_SOURCE_REV"] = self.head + + def tearDown(self): + deploy.probe_artifact_version = self._real_probe + super().tearDown() + + def deploy_it(self): + return deploy.execute_deploy( + "queue-broker", + self.defn, + [], + base=os.path.join(self.tmp, "profiles"), + state=self.state, + scope="user", + units=os.path.join(self.tmp, "units"), + actor="test-actor", + ) + + def test_unattested_release_claim_is_refused(self): + code, lines = self.deploy_it() + self.assertEqual(code, 1) + self.assertIn("REFUSED", "\n".join(lines)) + self.assertIn("deploy refused (design §6)", "\n".join(lines)) + # Nothing was installed, and the refusal is on the record. + self.assertFalse( + os.path.exists(os.path.join(self.tmp, "profiles", "queue-broker")) + ) + entries = deploy.read_generations("queue-broker", self.state) + self.assertEqual(entries[-1]["action"], "deploy_failed") + self.assertIn("refused", entries[-1]["result"]) + + def test_attested_release_claim_deploys(self): + block = deploy.compose_attestation( + "fleet", + "0.1.0", + self.head, + "fleet-rust-tests", + [ + { + "workflow": "nix ci", + "run_id": 101, + "head_sha": self.parent, + "conclusion": "success", + } + ], + "test-actor", + "2026-11-23T00:00:00Z", + ) + self.gh.serve_tag("fleet/v0.1.0", f"fleet v0.1.0\n\n{block}\n", self.head) + code, lines = self.deploy_it() + self.assertEqual(code, 0, lines) + + def test_prerelease_claim_is_not_a_release_claim(self): + deploy.probe_artifact_version = lambda defn: "0.1.0-dev.3+gabc" + self.assertIsNone(deploy.release_claim_refusal("queue-broker", self.defn)) + deploy.probe_artifact_version = lambda defn: None + self.assertIsNone(deploy.release_claim_refusal("queue-broker", self.defn)) + + +class TestAttestationAndNumbering(unittest.TestCase): + def test_parse_roundtrip_and_tampering(self): + runs = [ + { + "workflow": "mcpx nix build", + "run_id": 42, + "head_sha": "b" * 40, + "conclusion": "success", + } + ] + block = deploy.compose_attestation( + "fleet", "0.1.0", "c" * 40, None, runs, "actor", "2026-11-23T00:00:00Z" + ) + message = f"fleet v0.1.0\n\n{block}\n" + parsed = deploy.verify_attestation(message, "fleet", "0.1.0", "c" * 40) + self.assertIsNotNone(parsed) + self.assertEqual(parsed["runs"][0][0], "mcpx nix build") + self.assertIsNone( + deploy.verify_attestation(message, "fleet", "0.1.0", "d" * 40) + ) + self.assertIsNone(deploy.parse_attestation("fleet v0.1.0\n\nno block\n")) + self.assertIsNone(deploy.parse_attestation("")) + + def test_plan_release_version(self): + self.assertEqual(deploy.plan_release_version([], None, "minor"), (0, 1, 0)) + self.assertEqual( + deploy.plan_release_version([(0, 1, 0)], None, "patch"), (0, 1, 1) + ) + self.assertEqual( + deploy.plan_release_version([(0, 1, 1)], (0, 2, 0), "minor"), (0, 2, 0) + ) + with self.assertRaises(deploy.ReleaseError): + deploy.plan_release_version([(0, 1, 0)], (0, 3, 0), "minor") + with self.assertRaises(deploy.ReleaseError): + deploy.plan_release_version([], (1, 0, 0), "minor") + + def test_next_repo_tag(self): + self.assertEqual( + deploy.next_repo_tag([], "20261123", True), "repo/v20261123.1.0" + ) + self.assertEqual( + deploy.next_repo_tag(["repo/v20261123.1.0"], "20261123", False), + "repo/v20261123.1.1", + ) + self.assertEqual( + deploy.next_repo_tag(["repo/v20261123.1.1"], "20261123", True), + "repo/v20261123.2.0", + ) + self.assertEqual( + deploy.next_repo_tag(["repo/v20261122.2.3"], "20261123", False), + "repo/v20261123.0.1", + ) + + def test_evidence_resolution(self): + self.assertEqual( + deploy.app_evidence_workflow(REGISTRY, "fleet"), "fleet-rust-tests" + ) + self.assertIsNone(deploy.app_evidence_workflow(REGISTRY, "mcpx")) + conflicting = { + "a": defn(entryPoint="bin/x", evidenceWorkflow="one"), + "b": defn(entryPoint="bin/x", evidenceWorkflow="two"), + } + with self.assertRaises(deploy.ReleaseError): + deploy.app_evidence_workflow(conflicting, "x") + + def test_registry_validation_of_evidence_workflow(self): + good = {"svc": defn(evidenceWorkflow="fleet-rust-tests")} + self.assertEqual(deploy.validate(good), []) + bad = {"svc": defn(evidenceWorkflow=7)} + self.assertTrue( + any("evidenceWorkflow" in e for e in deploy.validate(bad)) + ) + + def test_ledger_disagreement_tag_wins(self): + entries = [ + { + "app": "fleet", + "version": "0.1.0", + "commit": "e" * 40, + "tag": "fleet/v0.1.0", + }, + { + "app": "mcpx", + "version": "0.2.0", + "commit": "e" * 40, + "tag": "mcpx/v0.2.0", + }, + ] + block = deploy.compose_attestation( + "fleet", + "0.1.0", + "c" * 40, + None, + [ + { + "workflow": "id", + "run_id": 7, + "head_sha": "b" * 40, + "conclusion": "success", + } + ], + "actor", + "2026-11-23T00:00:00Z", + ) + attestations = {"fleet/v0.1.0": deploy.parse_attestation(block)} + text = "\n".join(deploy.format_releases(entries, attestations)) + # The tag's commit wins over the ledger's. + self.assertIn("DISAGREEMENT", text) + self.assertIn("the tag wins", text) + # A ledger record no tag confirms is not a release. + self.assertIn("mcpx/v0.2.0", text) + self.assertIn("not a release", text) + + +if __name__ == "__main__": + unittest.main(argv=[sys.argv[0]] + sys.argv[2:]) diff --git a/pkgs/fleet/README.md b/pkgs/fleet/README.md index ebc37963c1..9b0f8ec110 100644 --- a/pkgs/fleet/README.md +++ b/pkgs/fleet/README.md @@ -231,6 +231,13 @@ own release. 5. **Deploy truth.** What a target runs is read from the deployed binary's own `Derived version:` line, never from paperwork (that read is the #5760 deployed-state check's input). +6. **Who cuts them.** The workflow of record is the release-workflow + design record (`doc/2026-11-23T13-09-25Z_design_release-workflow-per-app-tags/`): + releases are cut only by `deploy release ` (pkgs/deploy, + #13306), which attests the main-gate for the tagged commit in the + tag's `release-attestation:v1` block, records the release in the + deploy ledger, and refuses a release-claiming deploy with no + attested tag behind it. ## Variants