From 9815fac418f0517323af37df6b67bc8671b20d14 Mon Sep 17 00:00:00 2001 From: ephico2real2 Date: Tue, 1 Dec 2026 16:25:55 -0600 Subject: [PATCH 1/2] #762: reconcile rebuilds a request from its bot branch, approved again by people After a database restore the reconcile operation's rebuild-requests step takes each bot branch the database lacks, one item at a time (core/rebuild.py). - The head must have the bot's shape: one parent on main, the bot's name and email as author and committer with one date, this request's, this instance's and one plan hash's trailers, the bot's subject, changes inside one namespace folder, the open PR on the same head with the same plan hash in its body, and files that hash to the plan hash again. Anything else is reported and not rebuilt: the item fails and auto-approval stays paused. - A head already in main is skipped as merged, a folder that moved on as superseded, and an adoption and a host that cannot read commits are reported. - The row comes back under its own ID in pending_approval, with the files and base Git holds and no approvals. Git carries no authority (docs/01), so the rules decide it again: at least one approver, no auto-approval, and no self-approval. The run's starter is the requester (via svc-cmapi-workflows). The requester the commit names is refused as approver. Once approved, push_branch adopts the same branch and open_pr takes up the same PR. #796: git_reconcile no longer closes the PR or deletes the branch of a request the database lacks while its head is not in main. It counts them as unrecorded and keeps them for the reconcile operation. Decision record and sources: docs/reviews/2026-12-01-issue-762/README.md. Docs: docs/02, docs/14, docs/16, GLOSSARY, citations relocated. Written by Opus 5.5 (high), the implementer. --- cmapi/src/cmapi/core/approvals.py | 20 +- cmapi/src/cmapi/core/db/repo.py | 17 +- cmapi/src/cmapi/core/git/base.py | 25 +++ cmapi/src/cmapi/core/git/gitea.py | 2 +- cmapi/src/cmapi/core/git/github.py | 10 +- cmapi/src/cmapi/core/git/workspace.py | 25 ++- cmapi/src/cmapi/core/pipeline.py | 62 +++++- cmapi/src/cmapi/core/ports.py | 3 + cmapi/src/cmapi/core/rebuild.py | 185 +++++++++++++++++ cmapi/src/cmapi/jobs/git_reconcile.py | 18 +- cmapi/src/cmapi/ops/__init__.py | 32 ++- cmapi/src/cmapi/ops/templates/reconcile.yaml | 9 +- cmapi/tests/core/test_approvals.py | 25 +++ cmapi/tests/service/conftest.py | 6 +- cmapi/tests/service/gitserver.py | 6 +- cmapi/tests/service/test_git_layer.py | 3 +- cmapi/tests/service/test_operations_26.py | 14 +- .../service/test_reconcile_rebuild_762.py | 186 ++++++++++++++++++ docs/02-technical-design-v2.md | 4 +- docs/14-authorization.md | 27 +-- docs/16-data-model.md | 22 +-- docs/21-usage-from-thanos.md | 8 +- docs/GLOSSARY.md | 1 + docs/citations.lock.json | 80 ++++---- docs/reviews/2026-12-01-issue-762/README.md | 158 +++++++++++++++ docs/reviews/2026-12-01-issue-762/after.txt | 8 + docs/reviews/2026-12-01-issue-762/before.txt | 21 ++ 27 files changed, 877 insertions(+), 100 deletions(-) create mode 100644 cmapi/src/cmapi/core/rebuild.py create mode 100644 cmapi/tests/service/test_reconcile_rebuild_762.py create mode 100644 docs/reviews/2026-12-01-issue-762/README.md create mode 100644 docs/reviews/2026-12-01-issue-762/after.txt create mode 100644 docs/reviews/2026-12-01-issue-762/before.txt diff --git a/cmapi/src/cmapi/core/approvals.py b/cmapi/src/cmapi/core/approvals.py index 5b876163..5471df2c 100644 --- a/cmapi/src/cmapi/core/approvals.py +++ b/cmapi/src/cmapi/core/approvals.py @@ -69,7 +69,7 @@ def approved_at_plan(self) -> bool: # The facts that say a request goes beyond its tier. A threshold that reads one of them is a beyond-tier rule, and the plan # names the approvals that it adds (added_for). BEYOND_FACTS = frozenset({"beyondTier", "beyondTierKeys", "networkExposure"}) -FIXED_GUARDS = ("delete", "beyond-tier", "rules-added-approvers", "capacity", "warnings", "team-allowance") +FIXED_GUARDS = ("delete", "beyond-tier", "rules-added-approvers", "capacity", "warnings", "team-allowance", "rebuilt") ADOPTION = "adoption" # the plugin of an adoption request (story #26) CAPACITY_PLUGINS = frozenset({"namespaces", "quotas"}) # their creates and changes need "fits" on fresh data POLICY_GUARDS = { @@ -233,6 +233,18 @@ def _requirement(self, facts: Mapping[str, Any], paused: bool, team_auto_today: merged[g] = Slot(g, 1, "An adoption needs an approver") reasons.append(f"an adoption, and no rule gives it an approver: +1 {g}") added = True + if facts.get("rebuilt"): + # A request rebuilt from Git after a database restore (#762). Its approvals were lost with the database and Git + # carries no authority (docs/01, "Approval of record"), so people decide it again: at least one approver, never a + # policy, and never the requester or the person who started the reconcile run (no self-approval). + if not any(s.count for s in merged.values()): + g = self.defaults["group"] + merged[g] = Slot(g, 1, "A request rebuilt from Git needs an approver") + reasons.append(f"rebuilt from Git after a restore, and no rule gives it an approver: +1 {g}") + policy, fallback = self._auto(facts, kind, added, paused, team_auto_today) + return Requirement(f"{env}-{kind}", tuple(merged.values()), False, int(rule["timeoutHours"]), + (*reasons, "rebuilt from Git: approved again by people, with no self-approval"), + auto_fallback="rebuilt" if policy or fallback else None, group_path=self.group_path) req = Requirement(rule=f"{env}-{kind}", slots=tuple(merged.values()), self_approval=bool(rule.get("selfApproval")), timeout_hours=int(rule["timeoutHours"]), reasons=tuple(reasons), group_path=self.group_path) @@ -322,6 +334,9 @@ class ApprovalLedger: requester_sub: str # the person the request is for (Requester.sub) operation_starter_sub: str | None = None client_owner_subs: frozenset[str] = frozenset() + # A rebuilt request (#762): the username that its Git commit names as requester. Git carries no sub, and the name is + # unverified, so it only ever refuses: that person cannot decide the change they asked for. + named_requester: str | None = None entries: list[dict[str, Any]] = field(default_factory=list) def _seats(self) -> list[str]: @@ -409,6 +424,9 @@ def _eligible(self, person: Identity, verb: str, permitted: bool | None, entry: if person.sub == self.requester_sub and not self.requirement.self_approval: raise Problem.conflict("self-approval", f"Requesters cannot {verb} their own request here" + ("" if verb == "approve" else "; :cancel withdraws it")) + if self.named_requester is not None and person.username == self.named_requester: + raise Problem.conflict("self-approval", f"This request was rebuilt from Git, whose commit names {person.username} " + f"as its requester: they cannot {verb} it") before, after = self._assign(self.entries), self._assign(self.entries + [entry]) if len(after) <= len(before): raise Problem.forbidden(f"Not in an approving group still needed: " diff --git a/cmapi/src/cmapi/core/db/repo.py b/cmapi/src/cmapi/core/db/repo.py index bcb5b381..1f158259 100644 --- a/cmapi/src/cmapi/core/db/repo.py +++ b/cmapi/src/cmapi/core/db/repo.py @@ -9,6 +9,7 @@ import hashlib import json +import re from dataclasses import asdict from datetime import datetime, timedelta, timezone from typing import Any, Iterable, Mapping @@ -60,6 +61,10 @@ def fingerprint(body: Mapping[str, Any]) -> str: return hashlib.sha256(json.dumps(body, sort_keys=True, default=str).encode()).hexdigest() +# What next_id writes: req-YYYYMMDD-NNNN, the number growing past four digits on a day that needs it. +REQUEST_ID = re.compile(r"req-([0-9]{8})-([0-9]{4,})") + + class RequestRepo: def __init__(self, session: Session): self.s = session @@ -162,6 +167,15 @@ def next_id(self, today: datetime | None = None) -> str: n = int(last.rsplit("-", 1)[1]) + 1 if last else 1 return f"{prefix}{n:04d}" + def claim_id(self, request_id: str) -> str: + """A request ID that Git already names, for a request rebuilt from its bot branch (#762): taken under its day's + advisory lock, as next_id takes one, so a submit at the same moment numbers after it, never onto it.""" + day = REQUEST_ID.fullmatch(request_id) + if day is None: + raise ValueError(f"{request_id!r} is not a request ID") + self.s.execute(text("SELECT pg_advisory_xact_lock(:k)"), {"k": int(day[1])}) + return request_id + # ---- writes def insert(self, row: ChangeRequestRow, first_event: E, by: str, note: str = "") -> ChangeRequestRow: t = transition(None, first_event) @@ -248,7 +262,8 @@ def ledger(self, row: ChangeRequestRow) -> ApprovalLedger | None: # rule that identity may not approve it either. submitter = (row.requester or {}).get("submittedBySub") ledger = ApprovalLedger(req, requester_sub=row.requester_sub, - operation_starter_sub=None if req.self_approval else submitter) + operation_starter_sub=None if req.self_approval else submitter, + named_requester=((row.plan or {}).get("rebuilt") or {}).get("requester")) for a in self.approvals(row.request_id): ledger.entries.append({"sub": a.approver_sub, "username": a.username, "groups": frozenset(a.groups), "comment": a.comment, "relayedBy": a.relayed_by, "at": a.at}) diff --git a/cmapi/src/cmapi/core/git/base.py b/cmapi/src/cmapi/core/git/base.py index 90aeff9b..7733d201 100644 --- a/cmapi/src/cmapi/core/git/base.py +++ b/cmapi/src/cmapi/core/git/base.py @@ -133,6 +133,22 @@ class BranchRequest: approved_at: datetime # both commit dates: the reproducible commit +@dataclass(frozen=True) +class CommitRecord: + """A commit as its own bytes describe it (#762). Every field is what the client that made it wrote: Git does not + authenticate a name ("This name has no effect on authentication", git-commit(1)). The reconcile operation reads it to tell + the bot's commit from anyone else's; it proves the shape of the commit, never who pushed it.""" + sha: str + parents: tuple[str, ...] + author: tuple[str, str] # (name, email) + committer: tuple[str, str] + author_time: int # seconds since the epoch + committer_time: int + subject: str + trailers: Mapping[str, tuple[str, ...]] # each trailer key of the message's trailer block, with its values in order + changed: Mapping[str, str] # path: git diff-tree's status letter (A, M, D, T) against the one parent + + @dataclass(frozen=True) class PushResult: head: str @@ -346,6 +362,15 @@ def branch_time(self, sha: str) -> int: """The commit time of a branch head, for git_reconcile's grace period.""" raise NotImplementedError + def commit_record(self, sha: str) -> CommitRecord: + """The commit's parents, author, committer, subject, trailers and changed paths, for the reconcile operation (#762). + NotImplementedError on a provider that cannot read them: the operation then reports the branch, never rebuilds it.""" + raise NotImplementedError(f"the {self.name} adapter does not read a commit's author, trailers and changed paths") + + def bot_author(self) -> tuple[str, str]: + """The name and email the bot writes as author and committer of its commits.""" + raise NotImplementedError(f"the {self.name} adapter does not write its commits through the Git layer") + # ---- the PR: the host's API def find_pr(self, branch: str) -> PrRef | None: """The open PR from the branch into the default branch.""" diff --git a/cmapi/src/cmapi/core/git/gitea.py b/cmapi/src/cmapi/core/git/gitea.py index 0bfa9e3f..ba01e50d 100644 --- a/cmapi/src/cmapi/core/git/gitea.py +++ b/cmapi/src/cmapi/core/git/gitea.py @@ -250,7 +250,7 @@ def _blob_sha(self, path: str, ref: str) -> str: def _pr_ref(self, p: Mapping[str, Any]) -> PrRef: return PrRef(number=p["number"], url=p.get("html_url") or f"{self.web_url}/{self.repository}/pulls/{p['number']}", - branch=p["head"]["ref"], head_sha=p["head"]["sha"]) + branch=p["head"]["ref"], head_sha=p["head"]["sha"], body=p.get("body")) def find_pr(self, branch: str) -> PrRef | None: r = self._call("find_pr", "GET", f"{self._repo()}/pulls", params={"state": "open", "limit": 50}) diff --git a/cmapi/src/cmapi/core/git/github.py b/cmapi/src/cmapi/core/git/github.py index 32be3f09..16f37cfa 100644 --- a/cmapi/src/cmapi/core/git/github.py +++ b/cmapi/src/cmapi/core/git/github.py @@ -36,7 +36,7 @@ from typing import Any, Iterable, Mapping from urllib.parse import quote -from cmapi.core.git.base import (BranchRequest, CheckState, GitUnavailable, HeadMoved, HostGitProvider, IncompleteList, MergeCheck, +from cmapi.core.git.base import (BranchRequest, CheckState, CommitRecord, GitUnavailable, HeadMoved, HostGitProvider, IncompleteList, MergeCheck, NotMergeable, PlatformRefused, PushResult, manifest_text, refuse_lost_names) from cmapi.core.ports import PrRef, PrStatus @@ -199,6 +199,12 @@ def list_branches(self, prefix: str) -> dict[str, str]: def branch_time(self, sha: str) -> int: return self._git().commit_time(sha) + def commit_record(self, sha: str) -> CommitRecord: + return self._git().commit_record(sha) + + def bot_author(self) -> tuple[str, str]: + return self._git().author + def request_of(self, sha: str) -> str | None: ws = self._git() with ws._lock: @@ -219,7 +225,7 @@ def dispose(self) -> None: # ---- the PR: REST def _pr_ref(self, p: Mapping[str, Any]) -> PrRef: - return PrRef(number=p["number"], url=p["html_url"], branch=p["head"]["ref"], head_sha=p["head"]["sha"]) + return PrRef(number=p["number"], url=p["html_url"], branch=p["head"]["ref"], head_sha=p["head"]["sha"], body=p.get("body")) def find_pr(self, branch: str) -> PrRef | None: owner = self.repository.split("/")[0] diff --git a/cmapi/src/cmapi/core/git/workspace.py b/cmapi/src/cmapi/core/git/workspace.py index d6a5d523..fcd68590 100644 --- a/cmapi/src/cmapi/core/git/workspace.py +++ b/cmapi/src/cmapi/core/git/workspace.py @@ -37,7 +37,8 @@ from pathlib import Path from typing import Iterable, Iterator, Literal, Mapping -from cmapi.core.git.base import BranchRequest, GitUnavailable, MergeCheck, NotUtf8, PushResult, as_plan, git_name, manifest_text +from cmapi.core.git.base import (BranchRequest, CommitRecord, GitUnavailable, MergeCheck, NotUtf8, PushResult, as_plan, git_name, + manifest_text) from cmapi.core.git.oplog import Op, redact, register_secret from cmapi.core.git.transport import Credentials, GitConfigError, Remote, check_path, git_environment, load_credentials, parse_remote from cmapi.core.observability import GIT_WORKDIR_BYTES, GIT_WORKTREES, SWEEPER_RUNS, log @@ -404,6 +405,28 @@ def commit_time(self, sha: str) -> int: self._need(sha) return int(self._out("log", "-1", "--format=%ct", sha, git_dir=True)) + def commit_record(self, sha: str) -> CommitRecord: + """What the commit says of itself (#762): parents, author, committer, their dates, subject, trailers, and each path it + changes against its one parent. %(trailers:only,unfold) reads the message's trailer block as git interpret-trailers + does, one "key: value" per entry; a commit with any other number of parents changes nothing here (no diff is read).""" + fields = "%P", "%an", "%ae", "%at", "%cn", "%ce", "%ct", "%s", "%(trailers:only,unfold,separator=%x1f)" + with self._lock: + self._need(sha) + out = self._m("log", "-1", "--no-show-signature", f"--format={'%x00'.join(fields)}", sha).stdout + parents, an, ae, at, cn, ce, ct, subject, block = out.decode(errors="backslashreplace").rstrip("\n").split("\0") + trailers: dict[str, list[str]] = {} + for entry in filter(None, block.split("\x1f")): + key, _, value = entry.partition(":") + trailers.setdefault(key.strip(), []).append(value.strip()) + changed: dict[str, str] = {} + if len(parents.split()) == 1: + diff = self._m("diff-tree", "-r", "--no-commit-id", "--no-renames", "--name-status", "-z", parents, sha).stdout + # -z: "\0\0" per path. A name that is not UTF-8 shows its bytes as \xNN: never a manifest (#626). + parts = diff.decode(errors="backslashreplace").split("\0") + changed = {path: status for status, path in zip(parts[0::2], parts[1::2]) if path} + return CommitRecord(sha, tuple(parents.split()), (an, ae), (cn, ce), int(at), int(ct), subject, + {k: tuple(v) for k, v in trailers.items()}, changed) + # ---- the request's branch def worktree_path(self, cluster_id: str, request_id: str) -> Path: for part in (cluster_id, request_id): diff --git a/cmapi/src/cmapi/core/pipeline.py b/cmapi/src/cmapi/core/pipeline.py index f4e7e024..78a2838a 100644 --- a/cmapi/src/cmapi/core/pipeline.py +++ b/cmapi/src/cmapi/core/pipeline.py @@ -50,6 +50,7 @@ SYSTEM_PREFIX = "cmapi.net/" ADOPTION_PLUGIN = "adoption" +REBUILD_REASON = "rebuild" # the reason of a request rebuilt from its bot branch after a restore (#762) # The requester of the delete that expire_check opens after an expiry's grace: cmapi itself, never a person's identity. EXPIRY_REQUESTER = Identity(sub=EXPIRY_NAME, username=EXPIRY_NAME, kind="service", client_id="cmapi-worker") @@ -83,6 +84,7 @@ class Plan: rerender: Callable[[str], dict[str, str | None]] | None = None hold: CapacityHold | None = None # the increase that submit holds on the cluster (#62); None: no increase placement_id: str | None = None # the placement whose hold a create claims (#21) + rebuilt: dict[str, Any] | None = None # a request rebuilt from its bot branch (#762): what Git said; stored @property def hash(self) -> str: @@ -106,7 +108,8 @@ def stored(self) -> dict[str, Any]: "capacity": {"status": self.capacity.status, "fresh": self.capacity.fresh, **dict(self.capacity.detail)}, "spec": _spec_json(self.spec), "findings": [f.view() for f in self.findings], "beyondTier": self.beyond_tier, "placementId": self.placement_id, - **({"adoption": self.adoption} if self.adoption else {})} + **({"adoption": self.adoption} if self.adoption else {}), + **({"rebuilt": self.rebuilt} if self.rebuilt else {})} def _spec_json(spec: NamespaceSpec | None) -> dict[str, Any] | None: @@ -852,8 +855,10 @@ def rerender(request_id: str) -> dict[str, str | None]: # ---- record it def submit(self, who: Identity, plan: Plan, repo: RequestRepo, jobs: JobRepo, *, idempotency_key: str | None, - body_fingerprint: str, justification: str | None) -> ChangeRequestRow: - rid = repo.next_id() # takes the day's advisory lock: submits are serial from here to the commit + body_fingerprint: str, justification: str | None, request_id: str | None = None) -> ChangeRequestRow: + """`request_id`: the ID that Git already names, for a request rebuilt from its bot branch (#762); else the next.""" + # Each takes the day's advisory lock: submits are serial from here to the commit + rid = repo.claim_id(request_id) if request_id else repo.next_id() # A delete too: the expired-namespace policy approves one, and the team's daily allowance is a guard that no policy # switches off (docs/01). Any other delete falls back on the guard "delete" first, as when it was planned. decide_again = bool(plan.facts.get("team")) @@ -906,6 +911,57 @@ def submit(self, who: Identity, plan: Plan, repo: RequestRepo, jobs: JobRepo, *, jobs.enqueue("channel_notify", request_id=rid, cluster_id=plan.cluster_id, payload={"kind": "pending"}) return row + def plan_rebuild(self, who: Identity, submitted_by: Identity, cluster_id: str, ns: str, *, action: str, + files: Mapping[str, str | None], prev: Mapping[str, str], base_sha: str, rebuilt: Mapping[str, Any], + session: Any) -> Plan: + """The plan of a request rebuilt from its bot branch after a restore (#762): the files and base that Git holds, judged + as a revert judges a folder restored from Git (jobs/open_pr.py, open_revert): the change from what main holds, `prev`, + to the branch's folder, with the capacity check, the facts the rules read, and the validator's findings. `who` started + the reconcile run and `submitted_by` is svc-cmapi-workflows, as for every request an operation opens: `who` is checked + as on their own request (the permission, the identity rules), and the rules are decided for both (design.md, D3). + + The fact `rebuilt` makes the rules ask people again, at least one, with no auto-approval and no self-approval + (ApprovalRules): the approvals were lost with the database, and Git carries no authority (docs/01).""" + st = self.registry.writable(cluster_id) + env = st.policy.environment + self.check_env_served(env) + self.cfg.roles.require(who, "namespaces:create" if action == "create" else "namespaces:write", env) + self.check_plugin_offered("namespaces", env) + direct = self.requester_for(who, None) + requester = Requester(direct.person, submitted_by, automated=True) + target = {p: t for p, t in files.items() if t is not None} + # The namespace the rules judge is the one the request leaves in Git: for a delete, the one Git holds now. + labels = metadata_of(namespace_doc(prev if action == "delete" else target))["label"] + facts: dict[str, Any] = { + "plugin": "namespaces", "action": action, "environment": env, "namespace": ns, "clusterId": cluster_id, + "team": self.cfg.metadata.team_of(labels), "tier": labels.get("cmapi.net/tier"), + "clusterLabels": dict(st.policy.labels), "automated": True, "requesterClient": submitted_by.client_id, + "reason": REBUILD_REASON, "rebuilt": True, "capacity": "fits", "capacityFresh": True, "warnings": [], + "starterApprovalFacts": {"automated": direct.automated, + "requesterClient": who.client_id if who.kind == "service" else None, "reason": None}} + cap, usage, beyond, hold = CapacityResult("fits", True, None, {"source": "rebuild"}), None, {}, None + findings: list[Finding] = [] + if action == "delete": + # As _plan_delete judges a delete: Git's protection labels (a protected namespace is refused), the namespace's age + # on the cluster and its workloads. + try: + created = created_day(self.registry.cache(cluster_id).namespace(ns)) + except Problem: + created = None + pods, pvcs = self.workload_counts(cluster_id, ns) + facts.update(pods=pods, pvcs=pvcs, namespaceAgeDays=(utc_today() - created).days if created else 0, + protected=self.cfg.approvals.is_protected(labels)) + else: + cap, restored, usage, beyond, hold = self.restore_facts(cluster_id, env, ns, prev, target, session=session) + facts.update(restored) + findings = self.validator.validate(target, cluster_id, env, previous=prev) + facts["warnings"] = [f.message for f in findings] + requirement = self._decide(facts, session=session) + changes = {p: c for p, c in diff_files(prev, files).items() if c != "unchanged"} + return Plan(cluster_id, ns, env, action, "namespaces", None, dict(files), dict(prev), changes, requirement, cap, facts, + requester, findings, base_sha, reason=REBUILD_REASON, etag=folder_etag(prev), usage=usage, + warnings=facts["warnings"], beyond_tier=self.beyond_view(facts, beyond), hold=hold, rebuilt=dict(rebuilt)) + def restore_facts(self, cluster_id: str, env: str, ns: str, current: Mapping[str, str | None], restored: Mapping[str, str | None], *, session: Any = None ) -> tuple[CapacityResult, dict[str, Any], dict[str, Any] | None, dict[str, dict[str, str | None]], diff --git a/cmapi/src/cmapi/core/ports.py b/cmapi/src/cmapi/core/ports.py index 1e99cdf3..091ed913 100644 --- a/cmapi/src/cmapi/core/ports.py +++ b/cmapi/src/cmapi/core/ports.py @@ -49,6 +49,9 @@ class PrRef: url: str branch: str head_sha: str + # The PR's description as the host gave it, when the call read it (a list or a find): the reconcile operation compares the + # plan hash it states with the commit's (#762). Not part of a PR's identity, so two refs to one PR still compare equal. + body: str | None = field(default=None, compare=False) @dataclass(frozen=True) diff --git a/cmapi/src/cmapi/core/rebuild.py b/cmapi/src/cmapi/core/rebuild.py new file mode 100644 index 00000000..53d02146 --- /dev/null +++ b/cmapi/src/cmapi/core/rebuild.py @@ -0,0 +1,185 @@ +"""Rebuilding a request from its bot branch after a database restore (#762; docs/01, "Database recovery"). + +docs/01: after a restore "a reconcile job rebuilds requests already in Git (pr_open and later) from the bot's branches and PR +bodies, which carry the request ID and plan hash". A rebuilt row is a request made from text in Git, and anyone who can push +a branch named cmapi// can write that text. Git's author and committer are what the client wrote +(git-commit(1): "This name has no effect on authentication"), and the bot does not sign its commits, so GitHub's verification +of them reads "unsigned". Nothing in Git proves who pushed the branch. So the rebuild does two things: + +1. It shows that the head has exactly the shape of the bot's commit for this request (`verify`). That means one parent on + main, the bot's name and email as author and committer with one date, and the trailers the bot writes: this request, this + instance and one plan hash. The subject must be the bot's, the changes must sit inside one namespace folder, and the plan + hash computed again from the files must equal the trailer's and the one the PR body states. Anything else is reported and + never rebuilt. +2. It never takes the approval from Git. docs/01, "Approval of record": "cmapi records every approval; Git reviews carry no + authority". The approvals were lost with the database and Git holds no proof of them, so the row lands in + pending_approval with no approval. Today's rules decide it again with at least one approver, no auto-approval and no + self-approval (ApprovalRules, the fact `rebuilt`). Once approved it goes on as any request does: push_branch adopts the + same branch and open_pr the same PR. + +The decision record and its sources: docs/reviews/2026-12-01-issue-762/README.md. +""" +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Any, Mapping + +from sqlalchemy.orm import Session + +from cmapi.core.db.models import ChangeRequestRow +from cmapi.core.db.repo import REQUEST_ID, AuditRepo, JobRepo, RequestRepo, fingerprint +from cmapi.core.git.base import CommitRecord, HostGitProvider, NotUtf8 +from cmapi.core.git.workspace import TRAILER_PLAN_HASH, TRAILER_REQUEST, request_branch +from cmapi.core.identity.claims import Identity +from cmapi.core.ports import PrRef +from cmapi.core.render.manifests import folder, plan_hash + +TRAILER_INSTANCE = "Cmapi-Instance" +TRAILER_REQUESTER = "Cmapi-Requester" +TRAILER_APPROVAL = "Cmapi-Approval" +# The subject the bot writes (jobs/delivery.py, title_of): " ()". +_SUBJECT = re.compile(r"(?Pcreate|update|delete|adopt) (?P[a-z0-9]([-a-z0-9]*[a-z0-9])?) \((?P\S+)\)") +# The line the bot writes in the PR body (jobs/delivery.py, body_of). +_BODY_HASH = re.compile(r"^Plan hash: (\S+)$", re.MULTILINE) + + +class NotRebuilt(Exception): + """A branch the reconcile operation reports and does not rebuild. `outcome` names the case in the report. `failed` is + False for a case that needs nobody (merged already, or moved on in Git): the step is then Skipped, not Failed.""" + + def __init__(self, outcome: str, reason: str, *, failed: bool = True): + super().__init__(reason) + self.outcome, self.reason, self.failed = outcome, reason, failed + + +@dataclass(frozen=True) +class Proven: + """What a bot commit that passed `verify` says, to plan the request again from.""" + namespace: str + action: str + files: dict[str, str | None] # the plan's files: the folder at the head, and None for each path it removes + prev: dict[str, str] # the folder at the parent, which main still holds + base: str # the parent + head: str + plan_hash: str + named_requester: str | None + approval: str | None + + +def _one(record: CommitRecord, key: str) -> str | None: + values = record.trailers.get(key, ()) + return values[0] if len(values) == 1 else None + + +def verify(git: HostGitProvider, record: CommitRecord, *, cluster_id: str, request_id: str, instance: str, + bot: tuple[str, str], pr: PrRef | None) -> Proven: + """The head of cmapi// as the bot's commit for that request, or NotRebuilt with the first check + it fails. The checks read only what the commit and the PR say, and what main holds now.""" + def foreign(why: str) -> NotRebuilt: + return NotRebuilt("not-the-bot", f"{record.sha[:8]} is not the bot's commit for {request_id}: {why}") + + if len(record.parents) != 1: + raise foreign(f"it has {len(record.parents)} parents, and the bot's commit has one") + people = {f"{n} <{e}>" for n, e in (record.author, record.committer) if (n, e) != tuple(bot)} + if people: + raise foreign(f"it was written by {', '.join(sorted(people))}, and the bot writes as {bot[0]} <{bot[1]}>") + if record.author_time != record.committer_time: + raise foreign("its author and committer dates differ, and the bot dates both with the approval") + stated = _one(record, TRAILER_PLAN_HASH) + if _one(record, TRAILER_REQUEST) != request_id or stated is None or _one(record, TRAILER_INSTANCE) != instance: + raise foreign(f"its trailers do not name this request, one plan hash and the instance {instance} as the bot's do") + subject = _SUBJECT.fullmatch(record.subject) + if subject is None or subject["rid"] != request_id: + raise foreign(f"its subject {record.subject[:80]!r} is not the bot's for {request_id}") + if subject["action"] == "adopt": + raise NotRebuilt("adoption", f"{request_id} is an adoption: the live objects it read are not in Git, so it is not " + "rebuilt. Adopt the namespace again") + ns = subject["ns"] + base = folder(cluster_id, ns) + outside = sorted(p for p in record.changed if not p.startswith(base)) + if outside or not record.changed: + raise foreign(f"it changes {outside[:3] or 'nothing'}, outside the folder {base}") + if pr is not None: + if pr.head_sha != record.sha: + raise NotRebuilt("pr-moved", f"PR #{pr.number} is on {pr.head_sha[:8]}, not on the branch's head {record.sha[:8]}") + said = _BODY_HASH.findall(pr.body or "") + if said != [stated]: + raise NotRebuilt("hash-mismatch", f"PR #{pr.number}'s body states the plan hash {said[0][:12] if said else 'none'}, " + f"not {stated[:12]} as the commit's trailer does") + parent = record.parents[0] + try: + at_head, _ = git.read_folder(base, record.sha) + prev, _ = git.read_folder(base, parent) + except NotUtf8 as exc: + raise foreign(f"its folder holds a path a plan cannot carry: {exc}") from exc + removed = {p for p, status in record.changed.items() if status == "D"} + unread = sorted(p for p in record.changed if p not in removed and p not in at_head) + if unread: + raise foreign(f"it writes {unread[:3]}, which are not manifests of the folder") + files: dict[str, str | None] = {**at_head, **dict.fromkeys(removed)} + computed = plan_hash(files) + if computed != stated: + raise NotRebuilt("hash-mismatch", f"the files on the branch hash to {computed[:12]}, not to the plan hash {stated[:12]} " + "that the commit states") + from cmapi.core.pipeline import namespace_doc + + action = "delete" if not at_head else "create" if namespace_doc(prev) is None else "update" + if action != "delete" and namespace_doc(at_head) is None: + raise foreign("the folder at its head holds no Namespace") + if action != subject["action"]: + raise foreign(f"its subject says {subject['action']}, and its files are a {action}") + # Main now: a change merged already needs no request, and one whose folder moved on would end superseded. + now, main = git.read_folder(base) + if git.contains(main, record.sha): + raise NotRebuilt("merged", f"{record.sha[:8]} is in {git.default_branch} already: there is nothing to deliver", + failed=False) + if not git.contains(main, parent): + raise foreign(f"its parent {parent[:8]} is not on {git.default_branch}") + if now != prev: + raise NotRebuilt("superseded", f"the folder on {git.default_branch} at {main[:8]} changed since the commit's parent: the " + "request would end superseded. Ask for the change again", failed=False) + return Proven(ns, action, files, prev, parent, record.sha, stated, _one(record, TRAILER_REQUESTER), + _one(record, TRAILER_APPROVAL)) + + +def rebuild(ctx: Any, s: Session, *, starter: Identity, actor: Identity, cluster_id: str, branch: str, request_id: str, + key: str, operation_id: str) -> ChangeRequestRow: + """The request of a bot branch that the database lacks, back in pending_approval under its own ID, or NotRebuilt.""" + if not REQUEST_ID.fullmatch(request_id) or branch != request_branch(cluster_id, request_id): + raise NotRebuilt("layout", f"{branch} is not cmapi//, the branch the bot writes") + git = ctx.git + head = git.branch_head(branch) + if head is None: + raise NotRebuilt("gone", f"{branch} is gone: there is nothing to rebuild from", failed=False) + try: + record, bot = git.commit_record(head), git.bot_author() + except NotImplementedError as exc: + raise NotRebuilt("unreadable", f"{exc}: {branch} is reported and not rebuilt") from exc + pr = git.find_pr(branch) + proven = verify(git, record, cluster_id=cluster_id, request_id=request_id, instance=ctx.cfg.name, bot=bot, pr=pr) + repo = RequestRepo(s) + holder = repo.open_for(cluster_id, proven.namespace) + if holder is not None: + raise NotRebuilt("namespace-held", f"{holder.request_id} ({holder.status}) holds {proven.namespace} now, so {request_id} " + "cannot take it back. Decide which change stands, then ask for the other again") + evidence = {"branch": branch, "head": proven.head, "base": proven.base, + "pr": {"number": pr.number, "url": pr.url} if pr is not None else None, + "requester": proven.named_requester, "approval": proven.approval, "operationId": operation_id} + plan = ctx.pipeline.plan_rebuild(starter, actor, cluster_id, proven.namespace, action=proven.action, files=proven.files, + prev=proven.prev, base_sha=proven.base, rebuilt=evidence, session=s) + row = ctx.pipeline.submit(actor, plan, repo, JobRepo(s), idempotency_key=key, body_fingerprint=fingerprint({"operation": key}), + justification=f"Rebuilt from {branch} by operation {operation_id} after a database restore", + request_id=request_id) + if row.plan_hash != proven.plan_hash: + # submit hashes the files it stores: the same files, so the same hash. Anything else is a bug, and nothing is kept. + raise RuntimeError(f"{request_id}: stored plan hash {row.plan_hash[:12]} is not Git's {proven.plan_hash[:12]}") + detail = {k: v for k, v in evidence.items() if v is not None} + repo.event(row, "rebuilt", actor.username, f"rebuilt from {branch} at {proven.head[:8]}; its approval is asked for again", + detail) + AuditRepo(s).record(starter, "request.rebuild", request_id, detail) + return row + + +def outcome_of(row: ChangeRequestRow) -> Mapping[str, Any]: + return {"outcome": "rebuilt", "requestId": row.request_id, "status": row.status, "planHash": row.plan_hash} diff --git a/cmapi/src/cmapi/jobs/git_reconcile.py b/cmapi/src/cmapi/jobs/git_reconcile.py index f46c4092..3f889fa2 100644 --- a/cmapi/src/cmapi/jobs/git_reconcile.py +++ b/cmapi/src/cmapi/jobs/git_reconcile.py @@ -3,8 +3,10 @@ reads the request ID from the last segment, and compares with the request's row. A branch younger than the grace period, by its head's commit time, is left alone: a job may be writing it. - PR or branch, no row, or a final state close the PR, delete the branch with a lease orphan - when its head is cmapi's for the request; + PR or branch, no row, its head not in main nothing: kept and counted, for the reconcile unrecorded + operation to rebuild or report (#796) + PR or branch, no row and its head in main, close the PR, delete the branch with a lease orphan + or a final state when its head is cmapi's for the request; any other head is kept and counted foreign_branch an open PR that is not row.pr.number close it, keep the row's duplicate a branch, no PR, approved, no job pending queue open_pr (it adopts, replaces or refuses) stalled @@ -34,6 +36,11 @@ HANDS_OFF = (S.APPLIED.value, S.MERGE_FAILED.value, S.SYNC_FAILED.value, S.AWAITING_PRUNE.value) +def _merged(ctx: AppContext, head: str | None) -> bool: + """Whether the default branch holds head: its change is in Git's history, so its branch and PR hold nothing else.""" + return head is not None and ctx.git.contains(ctx.git.branch_head(ctx.git.default_branch) or "", head) + + def git_reconcile(ctx: AppContext, s: Session, job: JobRow) -> None: jobs = JobRepo(s) stalled = 0 @@ -57,6 +64,13 @@ def git_reconcile(ctx: AppContext, s: Session, job: JobRow) -> None: continue row = rows.get(rid) open_prs = [p for p in prs if p.branch == branch] + if row is None and not _merged(ctx, head or next((p.head_sha for p in open_prs), None)): + # No row and not in main: after a database restore, the only record of an approved change that has not + # merged. docs/01 has the reconcile operation rebuild it from this branch and PR, so nothing here closes + # or deletes them (#796); the operation rebuilds the request or reports the branch. + GIT_ORPHANS.labels("unrecorded", "kept").inc() + actions.append(f"kept {branch}: no request {rid} in the database, for the reconcile operation") + continue if row is None or row.status in FINAL: kind = "orphan" for p in open_prs: diff --git a/cmapi/src/cmapi/ops/__init__.py b/cmapi/src/cmapi/ops/__init__.py index b98341c3..6065fb2e 100644 --- a/cmapi/src/cmapi/ops/__init__.py +++ b/cmapi/src/cmapi/ops/__init__.py @@ -228,7 +228,7 @@ def pause_auto_approval(sc: StepContext) -> StepResult: @step("reconcile", "find-unrecorded") def find_unrecorded(sc: StepContext) -> StepResult: """Each bot branch and open pull request of every cluster (cmapi//...) whose request ID, its last segment as - git_reconcile reads it, the database does not hold.""" + git_reconcile reads it, the database does not hold: the items that rebuild-requests takes one at a time.""" from cmapi.core.git.base import GitUnavailable from cmapi.core.git.workspace import BRANCH_PREFIX @@ -247,18 +247,34 @@ def find_unrecorded(sc: StepContext) -> StepResult: for branch in sorted(names): if ids[branch] not in held: pr = next((p for p in prs if p.branch == branch), None) - found.append({"clusterId": cid, "branch": branch, "requestId": ids[branch], + found.append({"item": branch, "clusterId": cid, "branch": branch, "requestId": ids[branch], "pr": pr.number if pr else None, "url": pr.url if pr else None}) - return StepResult.done(unrecorded=found, count=len(found)) + return StepResult.done(unrecorded=found, items=found, count=len(found)) @step("reconcile", "rebuild-requests") def rebuild_requests(sc: StepContext) -> StepResult: - count = sc.output("find-unrecorded", "count") or 0 - if not count: - return StepResult.done(note="every bot branch and pull request has its request in the database") - raise StepRefused(f"{count} bot branch(es) or pull request(s) have no request in the database (find-unrecorded lists them): " - "rebuilding a request from its pull request is not built yet (#762). Auto-approval stays paused") + """One unrecorded bot branch: its request back in pending_approval under its own ID, its approval asked for again, or the + branch reported and not rebuilt (core/rebuild.py, #762). A branch that is not the bot's commit for the request, whose + files do not hash to its plan hash, or that cannot be read fails the item, so the run fails and auto-approval stays + paused until a person reads the report. A change merged already, or one whose folder moved on, is skipped and listed.""" + from cmapi.core.rebuild import NotRebuilt, outcome_of, rebuild + + item, s = sc.item, sc.session + repo = RequestRepo(s) + mine = repo.by_idempotency(WORKFLOWS_CLIENT, sc.key) # rebuilt by an earlier run of this row + if mine is not None: + return StepResult.done(**outcome_of(mine)) + rid = item["requestId"] + if s.get(ChangeRequestRow, rid) is not None: + return StepResult.skipped(f"the database holds {rid} now", outcome="held", requestId=rid) + try: + row = rebuild(sc.ctx, s, starter=sc.starter, actor=sc.actor, cluster_id=item["clusterId"], branch=item["branch"], + request_id=rid, key=sc.key, operation_id=sc.operation.operation_id) + except NotRebuilt as exc: + report = StepResult.failed if exc.failed else StepResult.skipped + return report(exc.reason, outcome=exc.outcome, requestId=rid, branch=item["branch"]) + return StepResult.done(**outcome_of(row)) # --------------------------------------------------------------------------- cluster-onboard diff --git a/cmapi/src/cmapi/ops/templates/reconcile.yaml b/cmapi/src/cmapi/ops/templates/reconcile.yaml index 2aadd8d3..0b61f342 100644 --- a/cmapi/src/cmapi/ops/templates/reconcile.yaml +++ b/cmapi/src/cmapi/ops/templates/reconcile.yaml @@ -1,10 +1,11 @@ # docs/02, Worker jobs: "reconcile | After a restore, or on demand | Rebuilds open requests from bot PRs; auto-approval starts # paused". docs/01, "Database recovery": after a restore "the auto-approval kill switch starts paused, and a reconcile job # rebuilds requests already in Git (pr_open and later) from the bot's branches and PR bodies". This run pauses auto-approval, -# finds each bot branch and pull request whose request the database does not hold, and stops at the rebuild, which is not -# built yet: the report names each one to rebuild by hand. +# finds each bot branch and pull request whose request the database does not hold, and rebuilds each one (#762): back in +# pending_approval under its own ID, its approval asked for again, when its head is the bot's commit for the request with a +# plan hash that its files give. Any other branch is reported, not rebuilt (core/rebuild.py). name: reconcile -description: After a database restore, pause auto-approval and find the bot pull requests whose requests the database lacks. +description: After a database restore, pause auto-approval and rebuild the requests of the bot branches the database lacks. scope: instance # Pausing auto-approval is an admin's switch (approvals:pause, routers/admin.py): the starter holds it too. permissions: [approvals:pause] @@ -13,4 +14,4 @@ retry: {limit: 3, backoff: 30s, factor: 2} steps: - {name: pause-auto-approval} - {name: find-unrecorded, after: [pause-auto-approval]} - - {name: rebuild-requests, after: [find-unrecorded]} + - {name: rebuild-requests, after: [find-unrecorded], withParam: "{{steps.find-unrecorded.outputs.items}}"} diff --git a/cmapi/tests/core/test_approvals.py b/cmapi/tests/core/test_approvals.py index 55ffb13c..aece9742 100644 --- a/cmapi/tests/core/test_approvals.py +++ b/cmapi/tests/core/test_approvals.py @@ -344,3 +344,28 @@ def refusal(act, who): led = ledger() assert [led.reject(p) for p in people[:3]] == ["approver-prod", "approver-platform", "approver-platform"] assert led.counted_for() == {"sub-amy": "approver-prod"} and len(led.entries) == 1 # no approval moved + + +# ---- a request rebuilt from Git after a restore (#762) +def test_a_rebuilt_request_is_approved_again_by_people_whatever_the_rules_would_waive(rules): + """The approvals were lost with the database and Git carries no authority (docs/01): the policy that auto-approves the same + create from a person does not, a rule that needs nobody still gets one approver, and self-approval is off.""" + auto = rules.decide(facts(environment="rnd", namespace="payments-rnd", tier="small", rebuilt=True, reason="rebuild")) + assert auto.auto is None and auto.auto_fallback == "rebuilt" and not auto.self_approval + assert [(s.group, s.count) for s in auto.slots] == [("approver-platform", 1)] + waived = rules.decide(facts(environment="qa", action="update", namespace="temp-load", rebuilt=True)) + assert waived.auto is None and [(s.group, s.count) for s in waived.slots] == [("approver-platform", 1)] + needed = rules.decide(facts(rebuilt=True)) + assert [(s.group, s.count) for s in needed.slots] == [("approver-prod", 1)] and needed.auto_fallback is None + allowed = rules.decide(facts(environment="rnd", namespace="payments-rnd", tier="large", rebuilt=True)) + assert not allowed.self_approval + + +def test_the_requester_a_rebuilt_commit_names_cannot_decide_it(rules): + req = rules.decide(facts(rebuilt=True)) + led = ApprovalLedger(req, requester_sub="sub-adam", named_requester="ola") + for verb in (led.approve, led.reject): + with pytest.raises(Problem) as e: + verb(person("ola", groups={"/cmapi/app-cmapi-rbac-approver-prod"}, **APPROVER)) + assert e.value.code == "self-approval" and "rebuilt from Git" in e.value.detail + assert led.approve(person("amy", groups={"/cmapi/app-cmapi-rbac-approver-prod"}, **APPROVER)) diff --git a/cmapi/tests/service/conftest.py b/cmapi/tests/service/conftest.py index 1ce62b96..67910d50 100644 --- a/cmapi/tests/service/conftest.py +++ b/cmapi/tests/service/conftest.py @@ -206,7 +206,7 @@ def changed_paths(self, head): def find_pr(self, branch): for n, p in self.prs.items(): if p["branch"] == branch and p["state"] == "open": - return PrRef(n, p["url"], branch, self.heads[branch]) + return PrRef(n, p["url"], branch, self.heads[branch], body=p.get("body")) return None def push_request_branch(self, req): @@ -245,7 +245,7 @@ def open_pr(self, branch, head, title, body): n = len(self.prs) + 1 self.prs[n] = {"branch": branch, "state": "open", "title": title, "body": body, "url": f"https://git.test/pulls/{n}", "merge_sha": None} - return PrRef(n, self.prs[n]["url"], branch, head) + return PrRef(n, self.prs[n]["url"], branch, head, body=body) def comment(self, pr, text): self.prs[pr.number].setdefault("comments", []).append(text) @@ -259,7 +259,7 @@ def delete_branch(self, branch, expected): return True def list_open(self, prefix): - return [PrRef(n, p["url"], p["branch"], self.heads.get(p["branch"], "")) for n, p in self.prs.items() + return [PrRef(n, p["url"], p["branch"], self.heads.get(p["branch"], ""), body=p.get("body")) for n, p in self.prs.items() if p["state"] == "open" and p["branch"].startswith(prefix)] def list_branches(self, prefix): diff --git a/cmapi/tests/service/gitserver.py b/cmapi/tests/service/gitserver.py index 495ef1a7..8a2b05e2 100644 --- a/cmapi/tests/service/gitserver.py +++ b/cmapi/tests/service/gitserver.py @@ -332,7 +332,8 @@ def _pr(self, n: int) -> dict: p = self.prs[n] head = self.head(p["ref"]) or p["sha"] return {"number": n, "html_url": f"https://github.test/{self.repo[7:]}/pull/{n}", "state": p["state"], "merged": p["merged"], - "merge_commit_sha": p.get("merge_sha"), "head": {"ref": p["ref"], "sha": head}, "base": {"ref": "main"}} + "merge_commit_sha": p.get("merge_sha"), "head": {"ref": p["ref"], "sha": head}, "base": {"ref": "main"}, + "body": p.get("body")} def _failing(self, name: str): import httpx @@ -371,7 +372,8 @@ def __call__(self, request): return httpx.Response(422, json={"message": "A pull request already exists"}) n = next(self._numbers) self.opened += 1 - self.prs[n] = {"ref": body["head"], "state": "open", "merged": False, "sha": self.head(body["head"]), "title": body["title"]} + self.prs[n] = {"ref": body["head"], "state": "open", "merged": False, "sha": self.head(body["head"]), "title": body["title"], + "body": body.get("body")} if self.workflow is not None: # on: pull_request (opened) self.run_workflow(n, self.prs[n]["sha"], self.workflow) if self.fail.get("pr_open") == "after": diff --git a/cmapi/tests/service/test_git_layer.py b/cmapi/tests/service/test_git_layer.py index 38a2c105..32a06f62 100644 --- a/cmapi/tests/service/test_git_layer.py +++ b/cmapi/tests/service/test_git_layer.py @@ -863,9 +863,10 @@ def test_7_5_e_the_reconciler_closes_and_deletes_orphans_and_leaves_hands_off_st drive(w.ctx, limit=3) with w.ctx.db.session() as s: s.execute(text("update change_requests set status='merge_failed' where request_id=:r"), {"r": keep}) + # An orphan with no row whose head main already holds: its change is in Git's history, so its branch goes. One whose + # head is not in main is kept for the reconcile operation (#796; test_reconcile_rebuild_762). orphan = person_commit(w.bare, {"README.md": "o\n"}, "o\n\nCmapi-Request-Id: req-20000101-0001\nCmapi-Plan-Hash: x", w.tmp) git("--git-dir", str(w.bare), "update-ref", "refs/heads/cmapi/CRC/req-20000101-0001", orphan, cwd=w.bare, home=w.tmp) - git("--git-dir", str(w.bare), "update-ref", "refs/heads/main", f"{orphan}~1", cwd=w.bare, home=w.tmp) import importlib; rec = importlib.import_module("cmapi.jobs.git_reconcile") rec.GRACE_SECONDS = -1 from cmapi.jobs.git_reconcile import git_reconcile diff --git a/cmapi/tests/service/test_operations_26.py b/cmapi/tests/service/test_operations_26.py index af584d5a..771ffdde 100644 --- a/cmapi/tests/service/test_operations_26.py +++ b/cmapi/tests/service/test_operations_26.py @@ -403,7 +403,9 @@ def test_rebuild_verify_reads_every_folder_against_the_cluster_and_reports_drift assert kube.applied == applied # read-only -def test_reconcile_pauses_auto_approval_and_stops_at_the_rebuild_it_lacks(world): +def test_reconcile_pauses_auto_approval_and_reports_a_branch_it_cannot_prove(world): + """The suite's FakeGit cannot read a commit's author and trailers, as the Gitea stand-in cannot: the branch is reported + and not rebuilt (#762), the run fails, and auto-approval stays paused. The rebuild itself: test_reconcile_rebuild_762.""" client, ctx, git, kube, validator, keys = world orphan = f"{BRANCH_PREFIX}CRC/req-20990101-0001" git.branches[orphan] = dict(git.branches["main"]) @@ -411,11 +413,15 @@ def test_reconcile_pauses_auto_approval_and_stops_at_the_rebuild_it_lacks(world) op_id = start(world, "reconcile", {}, who=("adam", ADMIN)).json()["operationId"] drive(ctx) view = get(world, op_id, who=("adam", ADMIN)) - phases = {r["step"]: r["phase"] for r in view["steps"]} - assert phases == {"pause-auto-approval": "Succeeded", "find-unrecorded": "Succeeded", "rebuild-requests": "Failed"} + phases = {(r["step"], r["item"]): r["phase"] for r in view["steps"]} + assert phases == {("pause-auto-approval", ""): "Succeeded", ("find-unrecorded", ""): "Succeeded", + ("rebuild-requests", orphan): "Failed"} found = rows_of(view, "find-unrecorded")[0]["outputs"]["unrecorded"] assert [f["requestId"] for f in found] == ["req-20990101-0001"] - assert "#762" in rows_of(view, "rebuild-requests")[0]["lastError"] and view["phase"] == "Failed" + rebuilt = rows_of(view, "rebuild-requests")[0]["outputs"] + assert rebuilt["outcome"] == "unreadable" and "not rebuilt" in rebuilt["note"] and view["phase"] == "Failed" + with ctx.db.session() as s: + assert s.get(ChangeRequestRow, "req-20990101-0001") is None with ctx.db.session() as s: assert SwitchRepo(s).value("auto-approval")["paused"] is True # an operator, not an admin, cannot read a run of the whole instance only when the grant is limited; opal's is not diff --git a/cmapi/tests/service/test_reconcile_rebuild_762.py b/cmapi/tests/service/test_reconcile_rebuild_762.py new file mode 100644 index 00000000..ee43fa61 --- /dev/null +++ b/cmapi/tests/service/test_reconcile_rebuild_762.py @@ -0,0 +1,186 @@ +"""#762 (security; story #26, criterion 3): after a database restore, the reconcile operation rebuilds a request from its bot +branch and pull request (docs/01, "Database recovery"), and reports, without rebuilding, a branch that is not the bot's. + +Real Git here (the Git layer over a bare repository) and GitHub's PR paths (gitserver.StubGitHub), as in test_git_layer. A +"restore" is the database as a backup taken before the request: its row, and every row that names it, removed. The decision +record, with its sources, is docs/reviews/2026-12-01-issue-762/README.md. +""" +from __future__ import annotations + +import os +import subprocess +import time + +from sqlalchemy import text + +from cmapi.core.db.repo import JobRepo, SwitchRepo +from gitserver import GIT, git +from test_flow import AMY, auth +from test_git_layer import drive, layer # noqa: F401 (layer is a fixture) + +ADMIN = dict(roles=["cmapi-admin"], groups=["/cmapi/app-cmapi-rbac-admin"]) +OPS = "/api/v1/operations" +PENDING_CI = {"ci/kubeconform": None, "ci/kyverno": None} # the PR's checks never finish: the request stays pr_open + + +def in_pr_open(w) -> dict: + """One create, auto-approved in dev, delivered to an open PR whose host CI has not finished: what the restore loses.""" + w.host.workflow = dict(PENDING_CI) + rid = w.create() + drive(w.ctx, limit=8) + view = w.view(rid) + assert view["status"] == "pr_open", view["status"] + with w.ctx.db.session() as s: + row = s.execute(text("select plan_hash, plan, pr from change_requests where request_id=:r"), {"r": rid}).one() + return {"rid": rid, "planHash": row.plan_hash, "files": row.plan["files"], "pr": row.pr} + + +def restore_without(w, rid: str) -> None: + """The database restored from a backup taken before `rid` was submitted: its row and each row that refers to it are gone.""" + with w.ctx.db.session() as s: + refs = s.execute(text( + "select kcu.table_name, kcu.column_name from information_schema.referential_constraints rc " + "join information_schema.key_column_usage kcu on kcu.constraint_name = rc.constraint_name " + "join information_schema.constraint_column_usage ccu on ccu.constraint_name = rc.unique_constraint_name " + "where ccu.table_name = 'change_requests'")).all() + for table, column in refs: + s.execute(text(f'delete from "{table}" where "{column}" = :r'), {"r": rid}) + s.execute(text("delete from jobs where request_id = :r"), {"r": rid}) + s.execute(text("delete from change_requests where request_id = :r"), {"r": rid}) + + +def reconcile(w) -> dict: + r = w.client.post(OPS, json={"template": "reconcile", "parameters": {}}, headers=auth(w.keys, "adam", **ADMIN)) + assert r.status_code == 202, r.text + op_id = r.json()["operationId"] + drive(w.ctx, limit=40) + view = w.client.get(f"{OPS}/{op_id}", headers=auth(w.keys, "adam", **ADMIN)) + assert view.status_code == 200, view.text + return view.json() + + +def rebuild_rows(view: dict) -> list[dict]: + return [r for r in view["steps"] if r["step"] == "rebuild-requests"] + + +def held(w, rid: str) -> bool: + with w.ctx.db.session() as s: + return s.execute(text("select 1 from change_requests where request_id=:r"), {"r": rid}).first() is not None + + +def rewrite_head(w, branch: str, *, name: str, email: str, files: dict[str, str] | None = None, reset_author: bool) -> str: + """The branch's head made again by someone who can push to the repository: the same message, so the bot's trailers, the + files changed as `files` says, and `name ` as the committer (and as the author with reset_author).""" + work = w.tmp / f"forge-{time.monotonic_ns()}" + git("clone", "--quiet", "--branch", branch, f"file://{w.bare}", str(work), cwd=w.tmp, home=w.tmp) + for path, body in (files or {}).items(): + (work / path).write_text(body) + git("add", "--all", cwd=work, home=w.tmp) + when = git("log", "-1", "--format=%ad", "--date=raw", cwd=work, home=w.tmp) + env = {"PATH": os.environ.get("PATH", ""), "HOME": str(w.tmp), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", + "GIT_COMMITTER_NAME": name, "GIT_COMMITTER_EMAIL": email, "GIT_COMMITTER_DATE": when, + "GIT_AUTHOR_NAME": name, "GIT_AUTHOR_EMAIL": email, "LANG": "C"} + args = ["commit", "--quiet", "--amend", "--no-edit", "--allow-empty"] + (["--reset-author"] if reset_author else []) + subprocess.run([GIT, *args], cwd=work, env=env, check=True, capture_output=True) + git("push", "--quiet", "--force", "origin", f"HEAD:refs/heads/{branch}", cwd=work, home=w.tmp) + return git("rev-parse", "HEAD", cwd=work, home=w.tmp) + + +# --------------------------------------------------------------------------- the issue's proof + + +def test_a_restored_database_gets_its_open_request_back_from_the_bot_pr_and_people_approve_it_again(layer): # noqa: F811 + w = layer + lost = in_pr_open(w) + rid, pr = lost["rid"], lost["pr"] + restore_without(w, rid) + assert not held(w, rid) + + view = reconcile(w) + assert view["phase"] == "Succeeded", view + [row] = rebuild_rows(view) + assert row["phase"] == "Succeeded" and row["outputs"]["outcome"] == "rebuilt", row + rebuilt = w.view(rid) + # The request is back with its ID and plan hash, and the plan's files are the ones Git holds. + assert rebuilt["status"] == "pending_approval" and rebuilt["planHash"] == lost["planHash"] + with w.ctx.db.session() as s: + stored = s.execute(text("select plan, requirement, requester_sub from change_requests where request_id=:r"), + {"r": rid}).one() + assert stored.plan["files"] == lost["files"] + assert stored.plan["rebuilt"]["head"] == pr["head"] and stored.plan["rebuilt"]["pr"]["number"] == pr["number"] + assert stored.plan["rebuilt"]["requester"] == "ola" + # The approval was lost with the database and Git carries no authority: no approval is minted, and dev's auto-approval + # of a create does not apply. Self-approval, which dev allows, does not either. + assert stored.requirement["auto"] is None and stored.requirement["selfApproval"] is False + with w.ctx.db.session() as s: + assert s.execute(text("select count(*) from approvals where request_id=:r"), {"r": rid}).scalar() == 0 + assert SwitchRepo(s).value("auto-approval")["paused"] is True + # The requester the commit names, and the person who started the run, cannot approve it, even holding the approver role + # and group that it needs. + for user, roles in (("ola", ["cmapi-requester", "cmapi-approver"]), ("adam", ["cmapi-admin", "cmapi-approver"])): + r = w.client.post(f"/api/v1/requests/{rid}:approve", json={}, + headers=auth(w.keys, user, roles=roles, groups=AMY["groups"])) + assert r.status_code == 409 and r.json()["code"] == "self-approval", (user, r.text) + # An eligible approver approves it, and the delivery takes up the same branch and the same PR: nothing new is opened. + r = w.client.post(f"/api/v1/requests/{rid}:approve", json={"comment": "rebuilt after the restore"}, + headers=auth(w.keys, "amy", **AMY)) + assert r.status_code == 200 and r.json()["status"] == "approved", r.text + drive(w.ctx, limit=8) + again = w.view(rid) + assert again["status"] == "pr_open", again["status"] + with w.ctx.db.session() as s: + now = s.execute(text("select pr from change_requests where request_id=:r"), {"r": rid}).scalar() + assert now["number"] == pr["number"] and now["head"] == pr["head"] and w.host.opened == 1 + assert w.host.head(pr["branch"]) == pr["head"], "the bot's commit was adopted, not replaced" + + +def test_a_branch_pushed_by_someone_else_is_reported_and_not_rebuilt(layer): # noqa: F811 + w = layer + lost = in_pr_open(w) + rid, branch = lost["rid"], lost["pr"]["branch"] + restore_without(w, rid) + # Someone with push access commits on the bot's branch as themselves, keeping the bot's message and trailers. + rewrite_head(w, branch, name="A Person", email="person@example.test", reset_author=True) + + view = reconcile(w) + [row] = rebuild_rows(view) + assert row["phase"] == "Failed" and row["outputs"]["outcome"] == "not-the-bot", row + assert "A Person " in row["outputs"]["note"], row + assert view["phase"] == "Failed" and not held(w, rid) + assert w.host.prs[lost["pr"]["number"]]["state"] == "open", "reported, not acted on" + + +def test_a_bot_commit_whose_files_do_not_hash_to_its_plan_hash_is_reported_and_not_rebuilt(layer): # noqa: F811 + w = layer + lost = in_pr_open(w) + rid, branch = lost["rid"], lost["pr"]["branch"] + restore_without(w, rid) + bot_name, bot_email = w.ctx.git.workspace.author + path = next(p for p, t in lost["files"].items() if t is not None and p.endswith(".yaml")) + rewrite_head(w, branch, name=bot_name, email=bot_email, reset_author=False, + files={path: lost["files"][path] + "# changed after the plan\n"}) + + view = reconcile(w) + [row] = rebuild_rows(view) + assert row["phase"] == "Failed" and row["outputs"]["outcome"] == "hash-mismatch", row + assert lost["planHash"][:12] in row["outputs"]["note"], row + assert not held(w, rid) + + +def test_git_reconcile_leaves_the_branch_and_pr_of_a_request_the_database_lacks(layer): # noqa: F811 + """#796: the periodic git_reconcile closed and deleted them as orphans, so the evidence the rebuild reads was gone within + one pass after a restore (its grace is the head's commit time, which is the approval's).""" + import importlib + + w = layer + lost = in_pr_open(w) + restore_without(w, lost["rid"]) + rec = importlib.import_module("cmapi.jobs.git_reconcile") + rec_grace, rec.GRACE_SECONDS = rec.GRACE_SECONDS, -1 + try: + with w.ctx.db.session() as s: + rec.git_reconcile(w.ctx, s, JobRepo(s).enqueue("git_reconcile")) + finally: + rec.GRACE_SECONDS = rec_grace + assert w.host.prs[lost["pr"]["number"]]["state"] == "open" + assert w.host.head(lost["pr"]["branch"]) == lost["pr"]["head"] diff --git a/docs/02-technical-design-v2.md b/docs/02-technical-design-v2.md index dbc21378..2e056771 100644 --- a/docs/02-technical-design-v2.md +++ b/docs/02-technical-design-v2.md @@ -2316,7 +2316,7 @@ The limitranges plugin is gone: the LimitRange now comes from the tier catalog, | watch\_sync | merged, or a :retry from sync\_failed | Waits for the full-plan read (`core/plan_read.py`): after Argo CD's own gate in argocd mode, after cmapi's apply in apply mode, alone in gitops mode (#751). Synced; sync\_failed at `syncTimeout` with the differences named; in gitops, awaiting\_prune when only unpruned removals are left. A delete moves to awaiting\_prune | 2 | | prune | awaiting\_prune | A delete: the namespace's absence by a read (apply mode deletes it first, after `POST /admin/prune:confirm`). A gitops change: the full-plan read, until each removed object is gone | 2 | | git\_cleanup | A final state, or merged | Closes a PR left open, deletes the branch with a lease, removes the worktree | 2 | -| git\_reconcile | Every 15 minutes | PRs and branches a crashed worker left | 2 | +| git\_reconcile | Every 15 minutes | PRs and branches a crashed worker left. One whose request the database lacks, and whose head is not in main, is kept for the reconcile operation (#796) | 2 | **Git delivery (#286).** The worker's two layers, the request's states in both modes, and one request in apply mode. The decisions are in `docs/reviews/2026-11-15-issue-286/README.md`. @@ -2396,7 +2396,7 @@ Built in PR #288 (#286 PR-A); not merged, not deployed | reservation\_expiry | Every minute | Ends placement reservations past their TTL | 3 | | policy\_report\_sweep | Every 5 minutes | cmapi\_policy\_results and the Policies tab cache | 5 | | token\_renew | Every minute | Renew bounded baseline imports at the configured point in the issued lifetime | 1 | -| reconcile | After a restore, or on demand | Rebuilds open requests from bot PRs; auto-approval starts paused | 5. Built (#26) as the reconcile operation: it pauses auto-approval and lists the bot branches and PRs whose requests the database lacks; the rebuild is not built (#762) | +| reconcile | After a restore, or on demand | Rebuilds open requests from bot PRs; auto-approval starts paused | 5. Built (#26, #762) as the reconcile operation. It pauses auto-approval and lists the bot branches and PRs whose requests the database lacks. It rebuilds each one whose head is the bot's commit for the request, with files that hash to its plan hash, under its own ID and in pending\_approval: the approval was lost with the database, so people approve it again, with no auto-approval or self-approval. Any other branch is reported, not rebuilt. Approved, the request takes up the same branch and PR (`core/rebuild.py`; docs/reviews/2026-12-01-issue-762) | | kpi\_export | Monthly | KPI rows for the 30-day KPIs | 5 | | outbox\_publish | Continuous, when an EventPublisher is on | Drains the outbox | Backlog | | operations | POST /operations | tiers-rerender, adoption-sweep, cluster-onboard, rebuild-verify, bulk-migrate through OperationsEngine | 5. Built (#26): the job `operation_step` runs one step of the built-in engine; tiers-rerender, rebuild-verify, reconcile and cluster-onboard. adoption-sweep and bulk-migrate are not built | diff --git a/docs/14-authorization.md b/docs/14-authorization.md index 4e339508..7bc8f065 100644 --- a/docs/14-authorization.md +++ b/docs/14-authorization.md @@ -63,7 +63,7 @@ A role is a client role on the client of the instance: `cmapi-nonprod`, `cmapi-s | `audit:export` | | | | | | | yes | | 0 | | `approvals:relay` | | | | | | | | yes | 0 | -`namespaces:protect` is what makes an operator (#366). No route declares it: the routes check it inside, in the environment of the object. It lets a caller set and remove the operator-only labels and annotations of `metadata-keys.yaml` (`cmapi.net/protected` and `do-not-delete`; a requester gets 403), cancel another person's request, and read employee IDs in the directory (`cmapi/src/cmapi/core/authz.py:160-166`, `cmapi/src/cmapi/core/pipeline.py:307`). It is a permission, not a role name: a role of `authz-roles.yaml` that inherits `cmapi-operator` is an operator, and a role that grants it in some environments makes an operator there only. A file that lists `permissions:` for `cmapi-operator` itself must name `namespaces:protect`, or that role is no longer an operator. +`namespaces:protect` is what makes an operator (#366). No route declares it: the routes check it inside, in the environment of the object. It lets a caller set and remove the operator-only labels and annotations of `metadata-keys.yaml` (`cmapi.net/protected` and `do-not-delete`; a requester gets 403), cancel another person's request, and read employee IDs in the directory (`cmapi/src/cmapi/core/authz.py:160-166`, `cmapi/src/cmapi/core/pipeline.py:310`). It is a permission, not a role name: a role of `authz-roles.yaml` that inherits `cmapi-operator` is an operator, and a role that grants it in some environments makes an operator there only. A file that lists `permissions:` for `cmapi-operator` itself must name `namespaces:protect`, or that role is no longer an operator. Each column name has the prefix `cmapi-` in Keycloak. An operator or an admin cannot approve with those roles alone: `requests:approve` is only in `cmapi-approver`. On CRC the group `app-cmapi-rbac-operator` also gives `cmapi-approver`. @@ -175,9 +175,9 @@ A role can have a list of environments. The route checks the permission again wh | Route group | Where the environment comes from | Source | |---|---|---| -| Create, change, delete or extend a namespace, or set or remove its expiry | The cluster's environment | `cmapi/src/cmapi/core/pipeline.py:292`, `:611` | +| Create, change, delete or extend a namespace, or set or remove its expiry | The cluster's environment | `cmapi/src/cmapi/core/pipeline.py:295`, `:614`; a request that the reconcile operation rebuilds after a restore checks the person who started the run in the same way (`:928`, #762) | | Read the namespaces of a cluster | The cluster's environment | `cmapi/src/cmapi/plugins/namespaces/router.py:196`, `:237` | -| List the adoption candidates or the skipped namespaces, or adopt a namespace (#739: `namespaces:write`) | The cluster's environment | `cmapi/src/cmapi/plugins/adoption/router.py:57`, `cmapi/src/cmapi/core/pipeline.py:728` | +| List the adoption candidates or the skipped namespaces, or adopt a namespace (#739: `namespaces:write`) | The cluster's environment | `cmapi/src/cmapi/plugins/adoption/router.py:57`, `cmapi/src/cmapi/core/pipeline.py:731` | | Read one request, its events or its approval status | The request's environment | `cmapi/src/cmapi/routers/requests.py:103`, `:116`, `:130` | | Approve, reject, cancel, retry or revert a request | The request's environment | `requests.py:154`, `:192`, `:216`, `:243`, `:277` | | Confirm a prune | The request's environment | `cmapi/src/cmapi/routers/admin.py:136` | @@ -200,7 +200,7 @@ The tests `test_environment_role_cannot_*` cover each route group (`test_review_ ### Step 5: who can approve or reject -An approval and a rejection have more checks than the permission, the same for both (`approvals.py:395-417`, `ApprovalLedger._eligible`; #779). Before #779 a rejection had only the permission in the environment, so an approver in no approving group of the request could veto it. The request is locked first. The checks are in this order; between the first and the second, a request that is not `pending_approval` gets 409 `not-pending`: +An approval and a rejection have more checks than the permission, the same for both (`approvals.py:410-435`, `ApprovalLedger._eligible`; #779). Before #779 a rejection had only the permission in the environment, so an approver in no approving group of the request could veto it. The request is locked first. The checks are in this order; between the first and the second, a request that is not `pending_approval` gets 409 `not-pending`: | Check | Refusal | |---|---| @@ -208,17 +208,18 @@ An approval and a rejection have more checks than the permission, the same for b | The caller has not approved this request before: a person decides a request once, and an approval is not turned into a rejection | 409 `already-approved` | | The caller did not file the request for another person, unless the rule has `selfApproval: true` | 409 `self-approval`, "The operation starter or client owner cannot approve" (or "reject") | | The caller is not the requester, unless the rule has `selfApproval: true` | 409 `self-approval`, "Requesters cannot approve their own request here"; a rejection's detail adds that `:cancel` withdraws it | +| For a request rebuilt from Git after a restore (#762): the caller is not the person that the Git commit names as requester. The rule of a rebuilt request never has `selfApproval: true`, so the person who started the reconcile run, its requester, is refused by the check above | 409 `self-approval`, "This request was rebuilt from Git, whose commit names ... as its requester" | | The caller is in an approving group that the request still needs: with the caller, one more seat can be filled, and an earlier approver of two groups moves to another seat when that is needed | 403 `not-eligible`, with the groups that are still needed | Who can reject is who can approve. The last check is the same matching for both, so it does not depend on the order of the rule's slots: when an approver of two groups holds the seat of the first, a person of that first group can still approve, and so can still reject (`test_who_may_reject_is_who_may_approve_and_the_group_is_one_still_open`, `tests/core/test_approvals.py`). A rejection that passes ends the request and moves no approval. Its approvals row records a group that is still needed when the caller is in one, and otherwise the group that the caller's approval would have counted for (`counted_for`, with `decision` reject; docs/16). The tests are in `test_reject_decision_779_780.py`. The ledger can also refuse the owners of the service client that filed a request (docs/01, "Approval of record"), and no route gives it any: see "What is not built". -An approval rule names a group by its short name, for example `approver-platform`. The path template makes the full path, and the check compares it with the `groups` claim. A request keeps the path that it was decided under, so a change of the template does not move the approvers of an open request (`cmapi/src/cmapi/core/db/repo.py:36-44`). The tests are `test_self_approval_refused_when_the_environment_forbids_it` and `test_submitter_cannot_approve_what_it_filed_on_behalf_of_someone` (`test_review_c_authz.py:202-212`). +An approval rule names a group by its short name, for example `approver-platform`. The path template makes the full path, and the check compares it with the `groups` claim. A request keeps the path that it was decided under, so a change of the template does not move the approvers of an open request (`cmapi/src/cmapi/core/db/repo.py:37-45`). The tests are `test_self_approval_refused_when_the_environment_forbids_it` and `test_submitter_cannot_approve_what_it_filed_on_behalf_of_someone` (`test_review_c_authz.py:202-212`). ### Step 6: the identity of a requester -A write that makes a request also checks who the requester is (`cmapi/src/cmapi/core/identity/checks.py`, called from `pipeline.py:194-196`). These refusals are 422, because the token is valid and the request cannot be recorded: +A write that makes a request also checks who the requester is (`cmapi/src/cmapi/core/identity/checks.py`, called from `pipeline.py:197-199`). These refusals are 422, because the token is valid and the request cannot be recorded: | Code | When | |---|---| @@ -287,7 +288,7 @@ When a person calls, cmapi records the request under the caller of the token. Th | Value | Where it comes from | Where it is kept | |---|---|---| -| `sub` | The claim `sub` (`claims.py:70`) | The database. Self-approval compares it (`approvals.py:409-411`) | +| `sub` | The claim `sub` (`claims.py:70`) | The database. Self-approval compares it (`approvals.py:424-426`) | | Username | The claim `preferred_username` (`claims.py:78`) | The database, and as a label of the namespace (`claims.py:3-5`) | | `email` | The claim `email` (`claims.py:74`) | The database | | `employee_id` | The claim `employee_id` (`claims.py:78`) | The database | @@ -302,7 +303,7 @@ A person calls as themselves. If a person sends `onBehalfOf`, cmapi refuses with A shared human account, for example `cmapi.requester`, that submits for many people is not in the design. A person cannot use `onBehalfOf` (`checks.py:74-78`), so a shared account would be recorded as the requester. It would have three effects: - Attribution is lost. Each request would carry the `sub` and the username of the shared account, and not those of the person. -- The self-approval check fails. The check compares `sub` values (`approvals.py:409-411`). The requester would carry the `sub` of the shared account. A person who submits through it and then approves with their own account has another `sub`, so the check would not refuse. +- The self-approval check fails. The check compares `sub` values (`approvals.py:424-426`). The requester would carry the `sub` of the shared account. A person who submits through it and then approves with their own account has another `sub`, so the check would not refuse. - The employee ID record is lost. The token of the shared account has one `employee_id`, or none, and a person's write needs one when the instance requires it (`checks.py:79-81`). A tool that must act for people has its own path: see the next section. @@ -317,7 +318,7 @@ The users filter of realm `cmapi` is `(uid=cmapi.*)` (`docs/15`, "The LDAP feder ### Tools that act for people -A tool signs in with the client credentials grant. It is a service client, or an account that holds a role in `identity.automationRoles`. The default role is `cmapi-onboarding`, and `cmapi-automation` holds it (`checks.py:1-15`; `docs/15`, "The clients"). The tool is the caller. Three cases follow (`checks.py:70-95`, called from `pipeline.py:298`): +A tool signs in with the client credentials grant. It is a service client, or an account that holds a role in `identity.automationRoles`. The default role is `cmapi-onboarding`, and `cmapi-automation` holds it (`checks.py:1-15`; `docs/15`, "The clients"). The tool is the caller. Three cases follow (`checks.py:70-95`, called from `pipeline.py:301`): | Case | What cmapi does | Source | |---|---|---| @@ -325,7 +326,7 @@ A tool signs in with the client credentials grant. It is a service client, or an | The tool sends `onBehalfOf`: a username or an employee ID | cmapi looks the value up in the directory. The person must be enabled, or the answer is 422 `unknown-user`. The person is recorded as the requester and the tool as the caller. The request is recorded as automated | `checks.py:89-95` | | A person sends `onBehalfOf` | 422 `on-behalf-of-not-allowed` | `checks.py:74-78`; `problem_docs.py:108` | -Self-approval uses the requester and the submitter. The ledger refuses the requester as approver: `requester_sub` is the `sub` of the named person (`checks.py:49-53`, `pipeline.py:888`, `approvals.py:409-411`). It also refuses the submitter, which is the `sub` of the tool, unless the approval rule has `selfApproval: true` (`cmapi/src/cmapi/core/db/repo.py:249-251`, `approvals.py:407-408`). The record keeps the submitter in `submittedBySub`, and the response leaves it out (`checks.py:59-64`, `views.py:25-27`). +Self-approval uses the requester and the submitter. The ledger refuses the requester as approver: `requester_sub` is the `sub` of the named person (`checks.py:49-53`, `pipeline.py:893`, `approvals.py:424-426`). It also refuses the submitter, which is the `sub` of the tool, unless the approval rule has `selfApproval: true` (`cmapi/src/cmapi/core/db/repo.py:264-266`, `approvals.py:422-423`). The record keeps the submitter in `submittedBySub`, and the response leaves it out (`checks.py:59-64`, `views.py:25-27`). With `onBehalfOf`, cmapi trusts the tool to name the person. The directory proves that the person exists and is enabled. It does not prove that the person signed in. @@ -374,7 +375,7 @@ The code `forbidden` has two more causes. Each is a refusal of the code, not of | A caller cancels a request that is not theirs and does not hold `namespaces:protect` in its environment | "Only the requester or an operator can cancel" | `cmapi/src/cmapi/core/lifecycle.py:125`, `cmapi/src/cmapi/routers/requests.py:221` | | A write sets or removes an operator-only label or annotation (`cmapi.net/protected`, `do-not-delete`) and the caller does not hold `namespaces:protect` in the environment | "Needs namespaces:protect in . Keys: ." (the cluster's environment, #532) | `cmapi/src/cmapi/core/metadata.py:1434` | -The ledger also refuses a relay client without `approvals:relay` with this code ("Relay client lacks approvals:relay", `cmapi/src/cmapi/core/approvals.py:376`), but no route can reach it: the approve route in `routers/requests.py` passes no relay to `ApprovalLedger.approve` (see "What is not built"). +The ledger also refuses a relay client without `approvals:relay` with this code ("Relay client lacks approvals:relay", `cmapi/src/cmapi/core/approvals.py:391`), but no route can reach it: the approve route in `routers/requests.py` passes no relay to `ApprovalLedger.approve` (see "What is not built"). A sample 403, taken from a run of the service suite's app on 2026-11-13. A caller with the role `cmapi-viewer` sent `POST /api/v1/admin/auto-approval:pause`: @@ -398,8 +399,8 @@ A sample 403, taken from a run of the service suite's app on 2026-11-13. A calle |---|---| | Routes for quotas, service accounts, grants, configuration, cluster onboarding, reload, events and audit export | Not built. Their permissions exist in `authz.py`, and no route uses them | | `adoption:write`: the scan of a cluster and the unmanaged-namespaces report (#252's admin operations) | Not built. The adoption of one namespace is self-service: its three routes need `namespaces:write` in the cluster's environment, and the approval rules gate it (#739, the owner's decision of 2026-11-26 on #26). The routes declare and enforce the same permission (`cmapi/src/cmapi/plugins/adoption/router.py`, `ADOPT_PERMISSION`) | -| The approval relay for email, ServiceNow and chat (`approvals:relay`) | The check exists in `approvals.py:373-376`. No route accepts a relayed approval | -| An owner of the service client that filed a request cannot approve or reject it (docs/01, "Approval of record") | The check exists in `approvals.py:407-408` (`client_owner_subs`), and only the pure tests give it owners. `RequestRepo.ledger` passes none (`cmapi/src/cmapi/core/db/repo.py:249-251`), because cmapi has no record of who owns a client. So a person who controls the client's credentials, and is in an approving group that the request needs, can approve or reject what that client filed for another person. The client itself is refused, unless the rule has `selfApproval: true`. Filed as #789 | +| The approval relay for email, ServiceNow and chat (`approvals:relay`) | The check exists in `approvals.py:388-391`. No route accepts a relayed approval | +| An owner of the service client that filed a request cannot approve or reject it (docs/01, "Approval of record") | The check exists in `approvals.py:422-423` (`client_owner_subs`), and only the pure tests give it owners. `RequestRepo.ledger` passes none (`cmapi/src/cmapi/core/db/repo.py:264-266`), because cmapi has no record of who owns a client. So a person who controls the client's credentials, and is in an approving group that the request needs, can approve or reject what that client filed for another person. The client itself is refused, unless the rule has `selfApproval: true`. Filed as #789 | | A scope by team or by namespace name | Not designed. A role with `namespaces:create` can ask for each name that is not reserved (`authz.py:8-10`) | ## Proof diff --git a/docs/16-data-model.md b/docs/16-data-model.md index 95ff27c6..9994407d 100644 --- a/docs/16-data-model.md +++ b/docs/16-data-model.md @@ -8,13 +8,13 @@ The database is PostgreSQL through CloudNativePG, or an existing PostgreSQL serv | Table | One row is | Written by | Read by | |---|---|---|---| -| `change_requests` | One write to a namespace: its plan, its approval rule, its requester, its pull request and its state | The API when a write is submitted (`RequestRepo.insert`, `core/db/repo.py:166`), then the API and the worker on each state change (`RequestRepo.move`, `repo.py:199`) | The request routes, the worker jobs, the KPI report | -| `request_events` | One state change or note of a request, in order | `RequestRepo.event` and `RequestRepo.move` (`repo.py:194-199`) | `GET /api/v1/requests/{request_id}/events` | -| `approvals` | One decision of one person on one request: an approval or, since migration `0014`, a rejection (#780) | `RequestRepo.record_approval` (`repo.py:257`) and `RequestRepo.record_rejection` (`repo.py:268`) | The approval ledger (`repo.py:243`), which reads the approvals only (`repo.py:85`) | -| `jobs` | One unit of work for the worker, with its lease | `JobRepo.enqueue` (`repo.py:280`) | The worker: `JobRepo.claim` (`repo.py:293`) | -| `audit_events` | One recorded action: who, what and on which target | `AuditRepo.record` (`repo.py:352`) | No route reads it yet. `AuditRepo.recent` exists (`repo.py:356`) | -| `jwks_keys` | The last good signing keys of one issuer | `DbKeyStore.save` (`repo.py:393`) | `DbKeyStore.load` (`repo.py:388`), when a pod starts while Keycloak does not answer | -| `admin_switches` | One switch of the instance, for example `auto-approval`, with who set it | `SwitchRepo.set` (`repo.py:374`) | `SwitchRepo.get` (`repo.py:364`), for the admin view. Each approval decision reads the value with `SwitchRepo.value` (`repo.py:368`), in the caller's transaction when it has one | +| `change_requests` | One write to a namespace: its plan, its approval rule, its requester, its pull request and its state | The API when a write is submitted (`RequestRepo.insert`, `core/db/repo.py:180`), then the API and the worker on each state change (`RequestRepo.move`, `repo.py:213`) | The request routes, the worker jobs, the KPI report | +| `request_events` | One state change or note of a request, in order | `RequestRepo.event` and `RequestRepo.move` (`repo.py:208-213`) | `GET /api/v1/requests/{request_id}/events` | +| `approvals` | One decision of one person on one request: an approval or, since migration `0014`, a rejection (#780) | `RequestRepo.record_approval` (`repo.py:272`) and `RequestRepo.record_rejection` (`repo.py:283`) | The approval ledger (`repo.py:257`), which reads the approvals only (`repo.py:90`) | +| `jobs` | One unit of work for the worker, with its lease | `JobRepo.enqueue` (`repo.py:295`) | The worker: `JobRepo.claim` (`repo.py:308`) | +| `audit_events` | One recorded action: who, what and on which target | `AuditRepo.record` (`repo.py:367`) | No route reads it yet. `AuditRepo.recent` exists (`repo.py:371`) | +| `jwks_keys` | The last good signing keys of one issuer | `DbKeyStore.save` (`repo.py:408`) | `DbKeyStore.load` (`repo.py:403`), when a pod starts while Keycloak does not answer | +| `admin_switches` | One switch of the instance, for example `auto-approval`, with who set it | `SwitchRepo.set` (`repo.py:389`) | `SwitchRepo.get` (`repo.py:379`), for the admin view. Each approval decision reads the value with `SwitchRepo.value` (`repo.py:383`), in the caller's transaction when it has one | | `approval_notifications` | One notice that a channel recorded for a request | The worker job `channel_notify` (`jobs/channel_notify.py:30`) | The same job, to send a notice only once | | `expiration_notices` | One expiry notice for a namespace | No code writes it yet. The job `expire_check` is not built | No code reads it yet | | `policy_rejections` | One refusal of cmapi before Git on one UTC day, or Kyverno's warnings on a plan that became a request (#302) | `RejectionRepo.record` (`core/rejections.py`), from the namespace routes, `_submit` and the job `pr_checks`; pruned by the job `rejections_prune` | `GET /api/v1/policies/rejections` | @@ -65,8 +65,8 @@ These indexes and constraints carry correctness. The code relies on each of them | One decision for each person on a request: a person who approved cannot then reject (409 `already-approved`, #779) | The unique index `uq_approvals_person` on `(request_id, approver_sub)` | Migration `0002` | | A decision is an approval or a rejection, and each row from before the column is an approval | The check `ck_approvals_decision` on `decision IN ('approve', 'reject')`, and the column's default `'approve'`. Only an approval fills a slot (`RequestRepo.approvals`). The downgrade refuses while a rejection is stored | Migration `0014` | | An approval says which approving group it counted for | `approvals.counted_for`. Each new approval writes the column again for each approval of the request, because the ledger can move an earlier approval to another slot. It is null for an approval from before the column | Migration `0004` | -| One pending job for each kind, request and payload kind. A job with no request counts the request as empty. A second `enqueue` with the same three values does nothing (`JobRepo.enqueue`, `repo.py:280`) | The partial unique index `uq_jobs_pending` on `(kind, coalesce(request_id, ''), coalesce(payload->>'kind', ''))`, for rows with no `done_at` | Migration `0001`, line 108 | -| A worker that lost its lease cannot commit | `jobs.lease_generation` increases at each claim, and the commit checks it | Migration `0003`, `JobRepo.assert_lease` (`repo.py:306`) | +| One pending job for each kind, request and payload kind. A job with no request counts the request as empty. A second `enqueue` with the same three values does nothing (`JobRepo.enqueue`, `repo.py:295`) | The partial unique index `uq_jobs_pending` on `(kind, coalesce(request_id, ''), coalesce(payload->>'kind', ''))`, for rows with no `done_at` | Migration `0001`, line 108 | +| A worker that lost its lease cannot commit | `jobs.lease_generation` increases at each claim, and the commit checks it | Migration `0003`, `JobRepo.assert_lease` (`repo.py:321`) | | A requester is a person or a service | The check `ck_cr_requester_kind` | Migration `0001`, line 54 | | A hold is released with its reason, or not at all | The check `ck_resv_released`: `released_at` and `released_why` are both set or both null. `released_why` is the state the request moved to (`synced`, `rejected`, `cancelled`, `timeout`, `failed`, `superseded`, `sync_failed`) or `expired`. No code writes `observed` (docs/02's list): each reader stops counting a hold from its own watch, and the row stays active until the lifecycle releases it | Migration `0011` | | Two requests cannot both take a cluster's last headroom | Not an index: the advisory lock of the cluster (`ReservationRepo.lock_cluster`, `repo.py`), taken in the transaction that checks a hold and writes it. The partial index `idx_resv_active` keeps the sum of a cluster's active holds cheap | Migration `0011`, #62 | @@ -148,7 +148,7 @@ The table `_T` in `cmapi/src/cmapi/core/lifecycle.py` holds each allowed move. N | Column | Keys | Source | |---|---|---| -| `plan` | `files` (the rendered files of the folder, path to text, null for a file that the plan removes), `prev` (the folder as Git held it), `changes` (path to `added`, `changed` or `removed`), `facts` (what the approval rules read, for example `beyondTier`, `beyondTierKeys`, `networkExposure`, `tierChange`, `quotaIncreasePct`, `keyClasses`), `capacity`, `spec` (the namespace spec that the renderer used), `findings` (each finding of the validator, with its severity and source) and `beyondTier` (the keys of a custom tier that differ from the tier, and the approvals that they add; null when none) | `Plan.stored` | +| `plan` | `files` (the rendered files of the folder, path to text, null for a file that the plan removes), `prev` (the folder as Git held it), `changes` (path to `added`, `changed` or `removed`), `facts` (what the approval rules read, for example `beyondTier`, `beyondTierKeys`, `networkExposure`, `tierChange`, `quotaIncreasePct`, `keyClasses`), `capacity`, `spec` (the namespace spec that the renderer used), `findings` (each finding of the validator, with its severity and source) and `beyondTier` (the keys of a custom tier that differ from the tier, and the approvals that they add; null when none). A request rebuilt from its bot branch after a restore (#762) also has `rebuilt`: the branch, its head and base, the PR's number and URL, the operation, and the requester and approval that the commit names, kept as unverified claims | `Plan.stored` | | `requirement` | `rule` (for example `rnd-create`), `slots` (each `group`, `count` and `reason`), `selfApproval`, `timeoutHours`, `reasons`, `auto` (`auto:`, `none-required`, or null), `autoFallback` (the guard that stopped a matching auto-approval policy) and `groupPath` (the `identity.groupPath` of the instance when the rule was decided) | `requirement_to_json` | | `requester` | `requester` (the person: `sub`, `username`, `email`, `givenName`, `middleName`, `familyName`, `employeeId`, `kind`, and `clientId` when the person is an `Identity`), `automated`, and, when a service sent the request for a person: `submittedBy`, `submittedBySub` and `submittedByClient` | `Requester.record` | | `pr` | `number`, `url`, `branch`, `head` | `open_pr` | @@ -294,7 +294,7 @@ The owner's rule, 2026-11-13: "we can use postgress for cache as well if needed | Shared state | Where it is | Expiry | |---|---|---| | The copy of the signing keys | `jwks_keys`, one row for each issuer, replaced at each good fetch | None. A newer fetch replaces the row | -| The idempotency records | `change_requests.idempotency_key`, `idempotency_fingerprint` and `idempotency_sub` | 24 hours from the creation of the request, by the database's `now()`. The caller's lookup clears the caller's older key (`RequestRepo.by_idempotency`, `core/db/repo.py:129`, #142, #603). Another caller's expired key stays on its row, and never replays, until its own caller sends it again | +| The idempotency records | `change_requests.idempotency_key`, `idempotency_fingerprint` and `idempotency_sub` | 24 hours from the creation of the request, by the database's `now()`. The caller's lookup clears the caller's older key (`RequestRepo.by_idempotency`, `core/db/repo.py:134`, #142, #603). Another caller's expired key stays on its row, and never replays, until its own caller sends it again | | The lock of a namespace | The index `uq_cr_open_namespace` | The request leaves the open states | | The work queue | `jobs`, claimed with a lease | `locked_until` | diff --git a/docs/21-usage-from-thanos.md b/docs/21-usage-from-thanos.md index b2f43a78..46ad70f9 100644 --- a/docs/21-usage-from-thanos.md +++ b/docs/21-usage-from-thanos.md @@ -115,9 +115,9 @@ from the file. The file also creates the Namespace `cmapi-system` and the Servic | Rule | API group and resources | Verbs | Why cmapi needs it | |---|---|---|---| -| 1 (`examples/baseline/cmapi-reader-rbac.yaml:23-25`) | core: `namespaces`, `nodes`, `resourcequotas`, `limitranges`, `serviceaccounts` | get, list, watch | Namespaces, ResourceQuotas and LimitRanges are the kinds `WatchCache` watches (`cmapi/src/cmapi/core/clients/kube.py:417`), and check 6 lists Namespaces (`cmapi/src/cmapi/core/registry.py:702`). `NodeCache` watches Nodes (`cmapi/src/cmapi/core/clients/nodes.py:33`, `:114`). The adoption plan lists a namespace's ServiceAccounts to count what stays unmanaged: `Pipeline._unadopted_counts` (`cmapi/src/cmapi/core/pipeline.py:691-701`), over `UNADOPTED_KINDS` (`cmapi/src/cmapi/core/adoption.py:43`) | -| 2 (`examples/baseline/cmapi-reader-rbac.yaml:26-28`) | core: `pods`, `persistentvolumeclaims` | list | The delete thresholds count a namespace's pods and PVCs: `Pipeline.workload_counts` (`cmapi/src/cmapi/core/pipeline.py:261-267`) | -| 3 (`examples/baseline/cmapi-reader-rbac.yaml:29-31`) | `rbac.authorization.k8s.io`: `roles`, `rolebindings`, `clusterroles`, `clusterrolebindings` | get, list, watch | The adoption plan lists a namespace's RoleBindings in the same count: `Pipeline._unadopted_counts` (`cmapi/src/cmapi/core/pipeline.py:691-701`). No code reads the other three today | +| 1 (`examples/baseline/cmapi-reader-rbac.yaml:23-25`) | core: `namespaces`, `nodes`, `resourcequotas`, `limitranges`, `serviceaccounts` | get, list, watch | Namespaces, ResourceQuotas and LimitRanges are the kinds `WatchCache` watches (`cmapi/src/cmapi/core/clients/kube.py:417`), and check 6 lists Namespaces (`cmapi/src/cmapi/core/registry.py:702`). `NodeCache` watches Nodes (`cmapi/src/cmapi/core/clients/nodes.py:33`, `:114`). The adoption plan lists a namespace's ServiceAccounts to count what stays unmanaged: `Pipeline._unadopted_counts` (`cmapi/src/cmapi/core/pipeline.py:694-704`), over `UNADOPTED_KINDS` (`cmapi/src/cmapi/core/adoption.py:43`) | +| 2 (`examples/baseline/cmapi-reader-rbac.yaml:26-28`) | core: `pods`, `persistentvolumeclaims` | list | The delete thresholds count a namespace's pods and PVCs: `Pipeline.workload_counts` (`cmapi/src/cmapi/core/pipeline.py:264-270`) | +| 3 (`examples/baseline/cmapi-reader-rbac.yaml:29-31`) | `rbac.authorization.k8s.io`: `roles`, `rolebindings`, `clusterroles`, `clusterrolebindings` | get, list, watch | The adoption plan lists a namespace's RoleBindings in the same count: `Pipeline._unadopted_counts` (`cmapi/src/cmapi/core/pipeline.py:694-704`). No code reads the other three today | | 4 (`examples/baseline/cmapi-reader-rbac.yaml:32-34`) | `security.openshift.io`: `securitycontextconstraints` | get, list, watch | No code reads it today | | 5 (`examples/baseline/cmapi-reader-rbac.yaml:35-37`) | `user.openshift.io`: `users`, `groups`, `identities` | get, list, watch | The identity check reads `users/~`, which every authenticated user may read (`cmapi/src/cmapi/core/clients/kube.py:262-264`); no code lists the others today | | 6 (`examples/baseline/cmapi-reader-rbac.yaml:38-40`) | `quota.openshift.io`: `clusterresourcequotas` | get, list, watch | No code reads it today | @@ -215,7 +215,7 @@ they are kept. While any finding stands, `ThanosQuerier.query` refuses before it - **The daily usage sweep** reads the same source, every namespace of a cluster at one instant, in batches of eight, with a 120-second timeout per query (`cmapi/src/cmapi/capacity/usage.py:256-264`, `cmapi/src/cmapi/capacity/sweep.py:87`). - **A namespace create never queries Thanos.** Only a quota change on an existing namespace reads usage - (`cmapi/src/cmapi/core/pipeline.py:467-474`). A test creates a namespace on PostgreSQL with `usage.source: thanos` and both + (`cmapi/src/cmapi/core/pipeline.py:470-477`). A test creates a namespace on PostgreSQL with `usage.source: thanos` and both grants missing: it is auto-approved, reaches `synced`, and makes no monitoring call; the quota change after it plans with usage `unavailable` (`cmapi/tests/service/test_reader_thanos_grants_724.py:428-470`). diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md index 5337cf8b..4072b4e2 100644 --- a/docs/GLOSSARY.md +++ b/docs/GLOSSARY.md @@ -132,6 +132,7 @@ Status: read from `main` at `afd1206` on 2026-11-23. Each row was read from the | Built-in engine | The operations engine that runs in the cmapi worker: one `operation_step` job per step that is due, under one scheduler (`advance`). integrations.yaml `operations.engine: builtin`, the default. Argo Workflows and Tekton are the optional engines, not built: naming one answers 503 `operations-engine-unavailable`. | [core/operations.py](../cmapi/src/cmapi/core/operations.py), [18-configuration.md](18-configuration.md) | | Step phases | `Pending`, `Running` (queued or running now), `Waiting` (for a request, an import or a retry's backoff), and the final `Succeeded`, `Skipped`, `Failed`, `Error`, `Stopped`. A run is `Pending`, `Running`, `Succeeded`, `Failed`, `Error` or `Stopped`. | [core/operations.py](../cmapi/src/cmapi/core/operations.py) | | Fan-out step | A step with `withParam`: one `operation_steps` row per item that an earlier step listed (for example one per outdated namespace), capped by `parallelism` and `perCluster`. | [design.md](reviews/2026-12-01-issue-26-operations/design.md), D10 | +| Rebuilt request | A request that the reconcile operation made again from its bot branch after a database restore (#762), under its own ID and in pending\_approval. Its head must be the bot's commit for the request, and its files must hash to its plan hash. People approve it again, with no auto-approval or self-approval, because Git carries no authority. | [core/rebuild.py](../cmapi/src/cmapi/core/rebuild.py), [record](reviews/2026-12-01-issue-762/README.md) | | `svc-cmapi-workflows` | The client that an operation's steps act as. On the built-in engine it holds the roles of the person who started the run, and each request it opens has that person as its requester (delegation, design.md D3). | [core/operations.py](../cmapi/src/cmapi/core/operations.py) (`StepContext.actor`) | | `maxConcurrentSteps` | integrations.yaml `operations.builtin.maxConcurrentSteps`, default 4: the steps of every run that may be `Running` at once, so operations never fill the queue ahead of the request jobs. | [18-configuration.md](18-configuration.md) | | `policy_rejections` | The table of cmapi's refusals before Git, and Kyverno's warnings on a plan that went on (migration 0006, #302). Pruned by the daily job `rejections_prune`. | [16-data-model.md](16-data-model.md), [18-configuration.md](18-configuration.md) | diff --git a/docs/citations.lock.json b/docs/citations.lock.json index ba62edf0..6c7b03ed 100644 --- a/docs/citations.lock.json +++ b/docs/citations.lock.json @@ -1,14 +1,14 @@ { - "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|373-376": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|388-391": [ " if relay is not None:", " ok = relay_permitted if relay_permitted is not None else \"approvals:relay\" in builtin_permissions(relay)", " if not ok:", " raise Problem.forbidden(\"Relay client lacks approvals:relay\")" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|376-376": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|391-391": [ " raise Problem.forbidden(\"Relay client lacks approvals:relay\")" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|395-417": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|410-435": [ " def _eligible(self, person: Identity, verb: str, permitted: bool | None, entry: dict[str, Any]) -> int:", " \"\"\"The checks of a decision, approve or reject, in docs/14's order; returns the seat the person would fill.", "", @@ -26,6 +26,9 @@ " if person.sub == self.requester_sub and not self.requirement.self_approval:", " raise Problem.conflict(\"self-approval\", f\"Requesters cannot {verb} their own request here\"", " + (\"\" if verb == \"approve\" else \"; :cancel withdraws it\"))", + " if self.named_requester is not None and person.username == self.named_requester:", + " raise Problem.conflict(\"self-approval\", f\"This request was rebuilt from Git, whose commit names {person.username} \"", + " f\"as its requester: they cannot {verb} it\")", " before, after = self._assign(self.entries), self._assign(self.entries + [entry])", " if len(after) <= len(before):", " raise Problem.forbidden(f\"Not in an approving group still needed: \"", @@ -33,11 +36,11 @@ " # The person is tried last and the matching grew, so the augmenting path that grew it starts at them: they hold a seat.", " return next(si for si, pi in after.items() if pi == len(self.entries))" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|407-408": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|422-423": [ " if person.sub in self.client_owner_subs or person.sub == self.operation_starter_sub:", " raise Problem.conflict(\"self-approval\", f\"The operation starter or client owner cannot {verb}\")" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|409-411": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|424-426": [ " if person.sub == self.requester_sub and not self.requirement.self_approval:", " raise Problem.conflict(\"self-approval\", f\"Requesters cannot {verb} their own request here\"", " + (\"\" if verb == \"approve\" else \"; :cancel withdraws it\"))" @@ -318,12 +321,12 @@ "any namespace name (outside the reserved ones) in the environments that role covers; approval rules decide what needs approval,", "and approving groups (Keycloak groups) decide who may approve." ], - "docs/14-authorization.md|cmapi/src/cmapi/core/db/repo.py|249-251": [ - " submitter = (row.requester or {}).get(\"submittedBySub\")", + "docs/14-authorization.md|cmapi/src/cmapi/core/db/repo.py|264-266": [ " ledger = ApprovalLedger(req, requester_sub=row.requester_sub,", - " operation_starter_sub=None if req.self_approval else submitter)" + " operation_starter_sub=None if req.self_approval else submitter,", + " named_requester=((row.plan or {}).get(\"rebuilt\") or {}).get(\"requester\"))" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/db/repo.py|36-44": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/db/repo.py|37-45": [ " return {\"rule\": r.rule, \"slots\": [asdict(s) for s in r.slots], \"selfApproval\": r.self_approval,", " \"timeoutHours\": r.timeout_hours, \"reasons\": list(r.reasons), \"auto\": r.auto,", " \"autoFallback\": r.auto_fallback, \"groupPath\": r.group_path}", @@ -495,29 +498,32 @@ "docs/14-authorization.md|cmapi/src/cmapi/core/metadata.py|1434-1434": [ " raise Problem.forbidden(f\"{_operator_only_reason((sources or {}).get('environment'))} Keys: {keys}.\")" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|194-196": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|197-199": [ " return resolve_requester(who, on_behalf_of, self.directory, self.identity.get(\"requireEmployeeId\", True),", " self.identity.get(\"requireOnBehalfOf\", False),", " self.identity.get(\"automationRoles\", [\"cmapi-onboarding\"]))" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|292-292": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|295-295": [ " self.cfg.roles.require(who, \"namespaces:create\" if action == \"create\" else \"namespaces:write\", env)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|298-298": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|301-301": [ " direct = self.requester_for(who, body.get(\"onBehalfOf\"))" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|307-307": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|310-310": [ " operator = self.cfg.roles.is_operator(who, env)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|611-611": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|614-614": [ " self.cfg.roles.require(who, \"namespaces:write\", env)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|728-728": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|731-731": [ " self.cfg.roles.require(who, ADOPT_PERMISSION, env)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|888-888": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|893-893": [ " requirement=requirement_to_json(req), requester=plan.requester.record(), requester_sub=plan.requester.sub," ], + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|928-928": [ + " self.cfg.roles.require(who, \"namespaces:create\" if action == \"create\" else \"namespaces:write\", env)" + ], "docs/14-authorization.md|cmapi/src/cmapi/core/problem_docs.py|108-108": [ " \"on-behalf-of-not-allowed\": \"Remove `onBehalfOf`. A person calls as themselves.\"," ], @@ -1044,13 +1050,13 @@ "docs/16-data-model.md|cmapi/src/cmapi/core/db/models.py|20-20": [ "OPEN_STATES = (\"pending_approval\", \"approved\", \"pr_open\", \"applied\", \"merge_failed\", \"merged\", \"awaiting_prune\", \"sync_failed\")" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|129-129": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|134-134": [ " def by_idempotency(self, caller_sub: str, key: str) -> ChangeRequestRow | None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|166-166": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|180-180": [ " def insert(self, row: ChangeRequestRow, first_event: E, by: str, note: str = \"\") -> ChangeRequestRow:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|194-199": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|208-213": [ " def event(self, row: ChangeRequestRow, event: str, by: str, note: str = \"\", detail: Mapping[str, Any] | None = None) -> None:", " self.s.add(RequestEventRow(request_id=row.request_id, event=event, status=row.status, by=by, note=note,", " detail=dict(detail) if detail else None))", @@ -1058,49 +1064,49 @@ "", " def move(self, row: ChangeRequestRow, event: E, by: str, note: str = \"\", **kw: Any) -> S:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|199-199": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|213-213": [ " def move(self, row: ChangeRequestRow, event: E, by: str, note: str = \"\", **kw: Any) -> S:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|243-243": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|257-257": [ " def ledger(self, row: ChangeRequestRow) -> ApprovalLedger | None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|257-257": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|272-272": [ " def record_approval(self, row: ChangeRequestRow, who: Identity, comment: str, relayed_by: str | None," ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|268-268": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|283-283": [ " def record_rejection(self, row: ChangeRequestRow, who: Identity, comment: str, decided_for: str) -> None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|280-280": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|295-295": [ " def enqueue(self, kind: str, *, request_id: str | None = None, cluster_id: str = \"\", delay: float = 0," ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|293-293": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|308-308": [ " def claim(self, worker_id: str, lease_seconds: int = 300) -> JobRow | None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|306-306": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|321-321": [ " def assert_lease(self, job_id: int, worker_id: str, generation: int) -> None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|352-352": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|367-367": [ " def record(self, actor: Identity, action: str, target: str, detail: Mapping[str, Any] | None = None) -> None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|356-356": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|371-371": [ " def recent(self, limit: int = 200) -> list[AuditEventRow]:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|364-364": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|379-379": [ " def get(self, name: str) -> dict[str, Any] | None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|368-368": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|383-383": [ " def value(self, name: str) -> dict[str, Any] | None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|374-374": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|389-389": [ " def set(self, name: str, value: Mapping[str, Any], by: str) -> None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|388-388": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|403-403": [ " def load(self, issuer: str) -> list[dict[str, Any]] | None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|393-393": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|408-408": [ " def save(self, issuer: str, keys: list[dict[str, Any]]) -> None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|85-85": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|90-90": [ " def approvals(self, request_id: str) -> list[ApprovalRow]:" ], "docs/16-data-model.md|cmapi/src/cmapi/core/identity/claims.py|55-60": [ @@ -1552,7 +1558,7 @@ "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/clients/policyreports.py|38-38": [ "POLICY_KINDS = (\"ValidatingPolicy\",)" ], - "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|261-267": [ + "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|264-270": [ " def workload_counts(self, cluster_id: str, ns: str) -> tuple[int, int]:", " \"\"\"Pods and PVCs in a namespace, for the delete thresholds. A live read: unknown is 503, never 0.\"\"\"", " client = self.registry.cache(cluster_id).client", @@ -1561,7 +1567,7 @@ " return (len(client.list(\"Pod\", namespace=ns)[\"items\"]),", " len(client.list(\"PersistentVolumeClaim\", namespace=ns)[\"items\"]))" ], - "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|467-474": [ + "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|470-477": [ " # A quota change on an existing namespace reads its live 14-day usage (docs/01, \"Quota changes on existing namespaces\");", " # nothing else does: \"Never queried while creating a namespace or setting its first quota\" (docs/01, Thanos on onboarding).", " usage_view, usage_facts = None, {}", @@ -1571,7 +1577,7 @@ " if old_hard.keys() != hard.keys() or any(qty(old_hard[k]) != qty(hard[k]) for k in hard):", " usage_view, usage_facts = plan_usage(self.usage.namespace(cluster_id, ns), old_hard, hard)" ], - "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|691-701": [ + "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|694-704": [ " def _unadopted_counts(self, cluster_id: str, ns: str) -> dict[str, int | None]:", " \"\"\"D2: how many ServiceAccounts and RoleBindings the namespace has, which the adoption leaves unmanaged. A kind that", " cannot be read is null (not known), never 0.\"\"\"", diff --git a/docs/reviews/2026-12-01-issue-762/README.md b/docs/reviews/2026-12-01-issue-762/README.md new file mode 100644 index 00000000..827b7fa8 --- /dev/null +++ b/docs/reviews/2026-12-01-issue-762/README.md @@ -0,0 +1,158 @@ +# #762: reconcile rebuilds a request from the bot's pull request + +Story #26, criterion 3. The design is docs/01, "Database recovery": after a restore "the auto-approval kill switch starts +paused, and a reconcile job rebuilds requests already in Git (pr\_open and later) from the bot's branches and PR bodies, which +carry the request ID and plan hash". This record holds the decisions that sentence leaves open, each with the source it rests +on. Every source was fetched on 2026-12-01. + +The implementer (Opus 5.5, high) wrote it on 2026-12-01. + +## The threat + +A rebuilt row is a request made from text in Git. Anyone who can push a branch named `cmapi//` can write +that text, and the commit's identity proves nothing about who wrote it: + +- git-commit(1), "COMMIT INFORMATION": "Author and committer information is taken from the following environment variables, + if set: GIT\_AUTHOR\_NAME, GIT\_AUTHOR\_EMAIL, GIT\_AUTHOR\_DATE, GIT\_COMMITTER\_NAME, GIT\_COMMITTER\_EMAIL, GIT\_COMMITTER\_DATE". + On the names: "This name has no effect on authentication". +- Trailers are lines that anyone writes in a message. git-interpret-trailers(1): "A trailer in its simplest form is a key-value + pair with a colon as a separator", and "The trailer block is by definition at the end of the commit message". + +- The plan hash is sha256 over the files (`plan_hash`, `core/render/manifests.py`), with no secret in it. Anyone can compute it + for files they wrote. +- The bot does not sign its commits. `GitWorkspace` commits with `git commit -F -` and no signing configuration. GitHub's REST + commit object carries a `verification` object, "the result of verifying the commit's signature", and for an unsigned commit + its reason is `unsigned`, "The object does not include a signature". + + +What the GitOps tools do: Flux proves where content in Git came from by its signature, not by its author field. +`.spec.verify` is "an optional field to enable the verification of Git commit signatures", against a Secret "containing the +public keys of trusted Git authors" (). Argo CD's page for the +same feature now says "GPG Signature verification is deprecated" and points to "Source Integrity Verification" +(). Without a signature, Git can show that a commit +has the bot's shape. It cannot show that the bot made it. + +## D1. A rebuilt request is approved again by people. Its approval is never taken from Git + +docs/01, "Approval of record": "cmapi records every approval; Git reviews carry no authority". The approvals rows and the +ledger were lost with the database. Git holds only the bot's own claim (`Cmapi-Approval: approved in cmapi`), and per the +threat above anyone with push access can write that. The approval evidence is not in Git, so the rebuild fails closed. It +mints no approvals row. The rebuilt row lands in **pending\_approval**, and the approval rules decide it again from today's +rules (`ApprovalRules._requirement`, the fact `rebuilt`): + +- at least one approver of `defaults.group` when no rule gives it one, as an adoption gets one; +- no auto-approval policy covers it, even where one would cover the same change from a person (dev's create); +- no self-approval, even where the environment allows it. The person who started the reconcile run is the request's + requester and is refused, and so is the person the commit names as requester (`ApprovalLedger.named_requester`). + +Approved, it goes on as any request does. `push_branch` adopts the same branch, because its adoption test (one commit on +main, this request's and plan's trailers, the folder at head equal to the plan's files) is what the rebuild proved. +`open_pr` takes up the same PR. Nothing new is opened, and the change is the one the PR shows. + +docs/01 lists the states a rebuild covers as "pr\_open and later". The pr\_open part is covered by this decision: the row +goes back to pending\_approval and the same PR carries it to pr\_open after the fresh approval. The design is not wrong: +its sentence does not say which state the rebuilt row lands in, and this decision chooses the one that "Approval of record" +allows. The rest of "and later" is D4. + +Rejected: rebuild into **pr\_open**, keeping the approval. That trusts a forgeable trailer as the approval of record. It +would let anyone who can push a branch get a change merged without a cmapi approval. + +Rejected for now: seal or sign the bot's commits, either with an HMAC trailer under a key that a restore keeps, or with SSH or +OpenPGP signing that `git verify-commit` and GitHub's `verification` can check. A sealed commit could keep its approval. Both +need new key material, rotation and a deployment change. And a commit made before the seal existed could still not be +proven. The fresh approval is safe without either. If the owner wants rebuilt requests to skip it, signing is the follow-up. + +Rejected for now: read who pushed the branch from GitHub's repository activity API (`GET /repos/{owner}/{repo}/activity`). It +"associates these changes with commits and users", with an `actor` for each `push` +(). It only works on GitHub, +and the page states no retention. Under D1 it would still not let a rebuilt request keep its approval. + +## D2. What proves the branch is the bot's, as far as Git can + +`core/rebuild.py`, `verify`, in this order. The first check that fails is the reason in the report: + +1. The branch is `cmapi//`, and `` has next\_id's form. +2. The head has one parent. +3. Author and committer are both the bot's name and email (`GitWorkspace.author`: `cmapi-git-bot` and + `instance.git.commitEmail`), with one date. The bot sets both to the approval's. +4. The trailers name this request (`Cmapi-Request-Id`), one plan hash (`Cmapi-Plan-Hash`) and this instance + (`Cmapi-Instance`). +5. The subject is the bot's: ` ()`. An `adopt` is reported (D5). +6. Every changed path is inside that namespace's folder. +7. If the PR is open, its head is the branch's head, and its body states the same plan hash (`Plan hash: ...`). +8. The plan hash is computed again from the branch: the `.yaml` files of the folder at the head, plus `None` for each path the + commit removes. It equals the trailer's. This is the same set `ManifestRenderer.render` and `delete` produce, and the same + one `_adoptable` compares. +9. The action that the files give (create, update or delete) is the one the subject says. +10. The head is not in main yet (D4), its parent is on main, and the folder on main is the parent's folder (D4). + +A branch that fails 1 to 9 is reported and not rebuilt. Its step item is **Failed**, so the run fails and auto-approval stays +paused until a person reads the report. Nothing is closed or deleted. These checks catch a person's own commit, an edit made +after the plan, and another instance's branch. They cannot catch a perfect forgery (see the threat above), and D1 is why that +is safe. + +## D3. What the row holds for what Git does not carry + +| Field | Rebuilt as | Why | +|---|---|---| +| `request_id`, `plan_hash`, `base_sha` | the branch's ID, the trailer's hash (checked equal to the files'), the commit's parent | what Git carries | +| `plan.files`, `plan.prev` | the folder at the head with `None` for each removed path; the folder at the parent | the plan the commit wrote; `spec` is null, so delivery uses the files as they are (`jobs/delivery.py`, `rendered`) | +| `status` | `pending_approval` | D1 | +| `requirement` | decided now by `approval-rules.yaml` over facts computed as a revert's (`Pipeline.plan_rebuild`, `restore_facts`) | the rules are the gate; the old requirement was lost | +| `requester`, `requester_sub` | the person who started the reconcile run, sent by `svc-cmapi-workflows` | Git holds no sub. Every request an operation opens records its starter and the client (docs/02, rule 4; the operations design D3) | +| the commit's `Cmapi-Requester`, `Cmapi-Approval` | kept in `plan.rebuilt` as unverified claims; the named requester is refused as approver | the record keeps what Git said; the claim can only refuse | +| approvals rows | none | D1: no approval is minted | +| `plan.rebuilt` | branch, head, base, PR number and URL, the two claims, the operation ID | the evidence of the rebuild; also a `rebuilt` event and a `request.rebuild` audit event | + +## D4. Merged, moved on, held + +- The head is in main already: **Skipped**, outcome `merged`. The change is in Git's history and Argo CD syncs it. Nothing is + delivered, so no request is rebuilt. +- The folder on main is not the commit's parent's folder: **Skipped**, outcome `superseded`. A rebuilt request would end + superseded at `push_branch` anyway. The report says to ask for the change again. +- Another open request holds the namespace now: **Failed**, outcome `namespace-held`. A person decides which change stands. + +## D5. Not rebuilt: adoptions, and hosts that cannot read a commit + +- An adoption's plan holds the snapshot of the live objects it read (the adoption design's D6a and D16), and Git does not. + It is reported (`adoption`), and the namespace is adopted again. +- The Gitea stand-in and the test suite's FakeGit do not read a commit's author and trailers (`HostGitProvider.commit_record`). + They report the branch as `unreadable`. Only the Git layer (GitHub) rebuilds. + +## D6. git\_reconcile keeps what the rebuild reads (#796) + +`git_reconcile` closed the PR and deleted the branch of every request whose row the database lacks. Its grace period is the +head's commit time, which is the approval time, so after a restore the evidence went at the first pass. A branch or PR with +no row whose head is not in main is now kept and counted (`cmapi_git_orphans_total{kind="unrecorded",action="kept"}`), and the +reconcile operation rebuilds or reports it. One whose head main already holds is still cleaned up as an orphan. + +## Found and filed + +- #796 (sev:high, fixed here): D6. +- #797 (sev:medium, not in this change): after a restore, `next_id` can reissue the ID of a lost request whose branch is still + in Git. A rebuilt request takes its own ID back, which moves `next_id` past it (`RequestRepo.claim_id`). A reported branch + keeps its ID free to be issued again. + +## Proof + +`cmapi/tests/service/test_reconcile_rebuild_762.py`, on real Git (a bare repository through the Git layer) and GitHub's PR +paths (`StubGitHub`), PostgreSQL 16 locally. No cluster was used. Output before and after the change is in +`before.txt` and `after.txt` beside this file. + +- A request in pr\_open, its row removed as a restore removes it, then reconcile. It is back in pending\_approval with its ID, + its plan hash and its files. It has no approvals, `auto` is null and `selfApproval` is false. The commit's named requester + and the run's starter are refused with 409 `self-approval`, even holding the approver role and group. An eligible approver + approves it. It reaches pr\_open on the same PR, with the same head, and no second PR is opened. +- The same branch re-committed by a person, with the bot's message and trailers kept: Failed, outcome `not-the-bot`, naming + the person. No row is written, and the PR stays open. +- The same branch re-committed with the bot's identity and one file changed: Failed, outcome `hash-mismatch`. No row is + written. +- `git_reconcile` after the restore leaves the PR open and the branch at its head (#796). +- `cmapi/tests/core/test_approvals.py`: a rebuilt request gets no auto-approval, at least one approver where the rules waive + all, and no self-approval; the requester its commit names can neither approve nor reject it. + +Before the change all six fail: `rebuild-requests` refuses with "not built yet (#762)", `git_reconcile` closes the PR, the +policy auto-approves the rebuilt create, and the ledger has no named requester. + +Not tested: a delete or an update rebuilt end to end (the create path is tested; the delete path computes the facts `_plan_delete` computes +facts), a rebuild on CRC, and a perfectly forged bot commit, which D1 makes safe by design. diff --git a/docs/reviews/2026-12-01-issue-762/after.txt b/docs/reviews/2026-12-01-issue-762/after.txt new file mode 100644 index 00000000..2188dfa4 --- /dev/null +++ b/docs/reviews/2026-12-01-issue-762/after.txt @@ -0,0 +1,8 @@ +tests/service/test_reconcile_rebuild_762.py::test_a_restored_database_gets_its_open_request_back_from_the_bot_pr_and_people_approve_it_again PASSED [ 25%] +tests/service/test_reconcile_rebuild_762.py::test_a_branch_pushed_by_someone_else_is_reported_and_not_rebuilt PASSED [ 50%] +tests/service/test_reconcile_rebuild_762.py::test_a_bot_commit_whose_files_do_not_hash_to_its_plan_hash_is_reported_and_not_rebuilt PASSED [ 75%] +tests/service/test_reconcile_rebuild_762.py::test_git_reconcile_leaves_the_branch_and_pr_of_a_request_the_database_lacks PASSED [100%] +============================== 4 passed in 28.63s ============================== +tests/core/test_approvals.py::test_a_rebuilt_request_is_approved_again_by_people_whatever_the_rules_would_waive PASSED [ 50%] +tests/core/test_approvals.py::test_the_requester_a_rebuilt_commit_names_cannot_decide_it PASSED [100%] +======================= 2 passed, 40 deselected in 0.15s ======================= diff --git a/docs/reviews/2026-12-01-issue-762/before.txt b/docs/reviews/2026-12-01-issue-762/before.txt new file mode 100644 index 00000000..924a9dde --- /dev/null +++ b/docs/reviews/2026-12-01-issue-762/before.txt @@ -0,0 +1,21 @@ +E AssertionError: {'operationId': 'op-20261201-0910f09a', 'template': 'reconcile', 'engine': 'builtin', 'runName': 'op-20261201-0910f09a', ...} +E assert 'Failed' == 'Succeeded' +E +E - Succeeded +E + Failed +E TypeError: 'NoneType' object is not subscriptable +E TypeError: 'NoneType' object is not subscriptable +E AssertionError: assert 'closed' == 'open' +E +E - open +E + closed +FAILED tests/service/test_reconcile_rebuild_762.py::test_a_restored_database_gets_its_open_request_back_from_the_bot_pr_and_people_approve_it_again +FAILED tests/service/test_reconcile_rebuild_762.py::test_a_branch_pushed_by_someone_else_is_reported_and_not_rebuilt +FAILED tests/service/test_reconcile_rebuild_762.py::test_a_bot_commit_whose_files_do_not_hash_to_its_plan_hash_is_reported_and_not_rebuilt +FAILED tests/service/test_reconcile_rebuild_762.py::test_git_reconcile_leaves_the_branch_and_pr_of_a_request_the_database_lacks +4 failed in 40.64s + +Core (tests/core/test_approvals.py -k rebuilt), with core/approvals.py as on main: +E AssertionError: assert ('auto:baseline-rnd-namespace' is None) +E TypeError: ApprovalLedger.__init__() got an unexpected keyword argument 'named_requester' +2 failed, 40 deselected From be8c93688e974669f65601b20b4919d3c684a5fc Mon Sep 17 00:00:00 2001 From: ephico2real2 Date: Tue, 1 Dec 2026 16:52:41 -0600 Subject: [PATCH 2/2] #762: test_usage_review_707's stand-in Plan has the new rebuilt field CI's service job: Plan.stored reads plan.rebuilt, and the test's SimpleNamespace stands in for a Plan field by field, as it already gives adoption=None. Written by Opus 5.5 (high), the implementer. --- cmapi/tests/service/test_usage_review_707.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmapi/tests/service/test_usage_review_707.py b/cmapi/tests/service/test_usage_review_707.py index 35574aad..d845d5d0 100644 --- a/cmapi/tests/service/test_usage_review_707.py +++ b/cmapi/tests/service/test_usage_review_707.py @@ -309,7 +309,7 @@ def test_the_stored_plan_holds_the_facts_and_no_usage_figures(): plan = SimpleNamespace(files={}, prev={}, changes={}, facts={"usage": "ok", "requestToPeakRatio": 3.7}, capacity=SimpleNamespace(status="fits", fresh=True, detail={}), spec=None, findings=[], beyond_tier=None, usage={"cpu": {"now": 123}}, adoption=None, - placement_id=None) + placement_id=None, rebuilt=None) stored = Plan.stored(plan) assert "usage" not in stored and stored["facts"] == {"usage": "ok", "requestToPeakRatio": 3.7}