Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion cmapi/src/cmapi/core/approvals.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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]:
Expand Down Expand Up @@ -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: "
Expand Down
17 changes: 16 additions & 1 deletion cmapi/src/cmapi/core/db/repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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})
Expand Down
25 changes: 25 additions & 0 deletions cmapi/src/cmapi/core/git/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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."""
Expand Down
2 changes: 1 addition & 1 deletion cmapi/src/cmapi/core/git/gitea.py
Original file line number Diff line number Diff line change
Expand Up @@ -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})
Expand Down
10 changes: 8 additions & 2 deletions cmapi/src/cmapi/core/git/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand All @@ -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]
Expand Down
25 changes: 24 additions & 1 deletion cmapi/src/cmapi/core/git/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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: "<status>\0<path>\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):
Expand Down
Loading