From 0fbd1605fc344890d10bee9b991edb72b757c763 Mon Sep 17 00:00:00 2001 From: Arthur Araujo da Silva Date: Tue, 1 Dec 2026 15:54:47 -0500 Subject: [PATCH 1/3] fix(git): skip commit statuses for state-only PR reads pr_status always paged the commit statuses when host CI was on, even for merge and apply, which only read the PR's state. Add a ci flag (default true) to the Git protocol and both providers; merge and apply pass ci=False, and the GitHub status test asserts the fetch makes no status request. --- cmapi/src/cmapi/core/git/base.py | 774 ++++++------ cmapi/src/cmapi/core/git/gitea.py | 631 +++++----- cmapi/src/cmapi/core/git/github.py | 736 +++++------ cmapi/src/cmapi/core/ports.py | 462 +++---- cmapi/src/cmapi/jobs/apply.py | 340 ++--- cmapi/src/cmapi/jobs/merge.py | 334 ++--- cmapi/tests/service/conftest.py | 1098 ++++++++--------- cmapi/tests/service/test_github_actions_ci.py | 671 +++++----- 8 files changed, 2528 insertions(+), 2518 deletions(-) diff --git a/cmapi/src/cmapi/core/git/base.py b/cmapi/src/cmapi/core/git/base.py index 90aeff9b..5cc81ee5 100644 --- a/cmapi/src/cmapi/core/git/base.py +++ b/cmapi/src/cmapi/core/git/base.py @@ -1,387 +1,387 @@ -"""What the platform adapters share (#286): one httpx client, one structured event per host call, and the error contract. - -The platform layer is thin: open a PR from the request branch, read its state, merge it pinned to a sha, comment, close. A -provider with a Git layer (GitHub) writes branches and reads trees through it; one without (the Gitea stand-in) through REST. - -A Git host failure is GitUnavailable; the worker turns it into a retry with backoff. HeadMoved and NotMergeable say why a -merge did not happen; PlatformRefused is a refusal that a retry cannot fix. Each call logs its op, outcome, HTTP status and, -on a refusal, the host's message (core/git/oplog.py), and counts in cmapi_git_platform_requests_total{platform,op,code}. - -The host's message is text the host chose: a host or a proxy in front of it may echo the request, the Authorization header -included. So every text taken from an answer passes through host_text, which removes each form of the bot's credential and -only then cuts (docs/02 "Client rules", #424); every error, request event, log line and API answer built from it is clean. -""" -from __future__ import annotations - -import base64 -import ssl -from dataclasses import dataclass -from datetime import datetime -from typing import Any, Callable, Iterable, Literal, Mapping - -import httpx - -from cmapi.core.clients.redact import order_forms, redact, redact_cut, sent_forms -from cmapi.core.ports import PrRef, PrStatus - -CheckState = Literal["pending", "success", "failure"] - - -class GitUnavailable(RuntimeError): - pass - - -class IncompleteList(GitUnavailable): - """The host gave a list that it can have cut, so nothing may read it as complete. A caller that does not handle it - treats the host as unavailable, which is the safe reading.""" - - -class PlatformRefused(GitUnavailable): - """401, 403, 404, 422 and the like: the host said no, and saying it again will not change that.""" - - def __init__(self, message: str, status: int | None = None, host_message: str = ""): - super().__init__(message) - self.status, self.host_message = status, host_message - - -class HeadMoved(PlatformRefused): - """The PR's head is not the pinned sha: nothing was merged.""" - - -class NotMergeable(GitUnavailable): - """The host will not merge now. transient: it is still computing, or a required check is pending.""" - - def __init__(self, message: str, transient: bool = False): - super().__init__(message) - self.transient = transient - - -# U+FFFD, what a REST host answers for a byte that is not UTF-8 in a name: measured on api.github.com (git/trees and Contents, -# 2026-11-24), and what Gitea's JSON encoder writes (json-iterator, writeStringSlowPathWithHTMLEscaped). It cannot be told from -# a name that holds U+FFFD itself, so no provider carries either (#626). -REPLACEMENT = "\ufffd" - - -class NotUtf8(Exception): - """Paths under a folder whose name, or a manifest whose text (part), is not UTF-8, so cmapi cannot carry them (#626). - - Git keeps a name as bytes, and a plan, the API's JSON and the database hold text. Each path is as shown() shows it. Not - GitUnavailable: Git answered, and a retry reads the same folder.""" - - def __init__(self, paths: Iterable[str], part: Literal["name", "text"]): - self.paths, self.part = sorted(paths), part - # U+FFFD is valid UTF-8: a REST host's stand-in for a lost byte, or typed on purpose. Either way no plan can carry it. - self.rule = "is not UTF-8 or holds U+FFFD" if any(REPLACEMENT in p for p in self.paths) else "is not UTF-8" - super().__init__(f"the {part} of {', '.join(self.paths[:3])}{' and more' if len(self.paths) > 3 else ''} {self.rule}") - - -def shown(raw: bytes) -> str: - """A path of NotUtf8, to show: each backslash doubled, as Git's own quoting always escapes one (core.quotePath), and each - byte that is not UTF-8 as \\xNN (codecs, 'backslashreplace'). So each shown path stands for one name only (#626).""" - return raw.replace(b"\\", b"\\\\").decode(errors="backslashreplace") - - -def git_name(raw: bytes) -> tuple[str, bool]: - """A name as `git ls-tree -z` gives it ("the filename is output verbatim", git-ls-tree(1)), as text, and whether cmapi can - carry it: valid UTF-8 with no U+FFFD. A name it cannot carry comes back as shown() shows it.""" - try: - name = raw.decode() - except UnicodeDecodeError: - return shown(raw), False - return (name, True) if REPLACEMENT not in name else (shown(raw), False) - - -def refuse_lost_names(paths: Iterable[str]) -> None: - """NotUtf8 for each name a REST host gave with U+FFFD: the byte it stands for is lost, so no plan can name the path.""" - lost = [shown(p.encode()) for p in paths if REPLACEMENT in p] - if lost: - raise NotUtf8(lost, "name") - - -def manifest_text(texts: Mapping[str, bytes]) -> dict[str, str]: - """Each manifest's bytes as text, strict UTF-8 as YAML is read here; NotUtf8 names every one that is not.""" - files, bad = {}, [] - for path, data in texts.items(): - try: - files[path] = data.decode() - except UnicodeDecodeError: - bad.append(shown(path.encode())) - if bad: - raise NotUtf8(bad, "text") - return files - - -def as_plan(read: Callable[[], bool]) -> bool: - """A folder read compared with the plan's, by read. A folder that holds a name or text that is not UTF-8 is never the - plan's, since the plan refuses one (#626), so the comparison is False rather than an error.""" - try: - return read() - except NotUtf8: - return False - - -@dataclass(frozen=True) -class BranchRequest: - """What a provider needs to write a request's branch.""" - cluster_id: str - request_id: str - folder: str - plan_hash: str - message: str - files: Mapping[str, str | None] # the plan's files: text, or None for a path the plan removes - prev: Mapping[str, str] # the folder before the plan (plan.prev) - approved_at: datetime # both commit dates: the reproducible commit - - -@dataclass(frozen=True) -class PushResult: - head: str - base: str - result: Literal["created", "adopted", "replaced"] - - -@dataclass(frozen=True) -class MergeCheck: - """git merge-tree --write-tree
, and the folder's two comparisons (Fable 2.3).""" - main_sha: str - head_sha: str - conflicts: tuple[str, ...] = () - base_matches: bool = True # the folder on main is the plan's prev - result_matches: bool = True # the folder in the merged tree is the plan's files - tree: str | None = None - - @property - def ok(self) -> bool: - return not self.conflicts and self.base_matches and self.result_matches - - def reason(self, branch: str = "main") -> str: - if self.conflicts: - return f"conflicts with {branch} at {self.main_sha[:8]} in {', '.join(self.conflicts)}" - if not self.base_matches: - return f"the folder on {branch} at {self.main_sha[:8]} is no longer the plan's base" - if not self.result_matches: - return f"the merge of {self.head_sha[:8]} into {branch} at {self.main_sha[:8]} would not leave the folder as planned" - return "clean" - - -def is_commit_id(ref: str, lengths: tuple[int, ...] = (40,)) -> bool: - """Whether an explicit ref has the spelling of a full lowercase object ID of one of these lengths (SHA-1 has 40).""" - return len(ref) in lengths and all(c in "0123456789abcdef" for c in ref) - - -def credential_values(token: str | None, basic_auth: tuple[str, str] | None) -> tuple[str, ...]: - """Each value of the bot's credential that a host could echo: the token, and with Basic auth the password and the header's - value as httpx sends it, base64 of user:password in UTF-8 (RFC 7617).""" - values = [token or ""] - if basic_auth: - user, password = basic_auth - values += [password, base64.b64encode(f"{user}:{password}".encode("utf-8")).decode("ascii")] - return tuple(v for v in values if v) - - -class HostGitProvider: - """The contract. Subclasses fill in the host's endpoints.""" - - name = "host" - BOT_NAME = "cmapi-git-bot" - BOT_EMAIL = "cmapi-git-bot@noreply.invalid" - # Whether the host's own CI reports ci/kubeconform and ci/kyverno (GitHub: the config repository's Actions jobs, #60). The - # worker then waits for them there and never posts them. The Gitea stand-in has no runner, so it keeps False. - external_ci = False - # Whether the worker posts its checks as commit statuses. The Gitea stand-in protects main with all three - # (tools/git_bootstrap.py); GitHub posts cmapi/check alone, with host CI or git.postStatus on (the arbitration of #286, row 11). - post_statuses = True - # Whether the worker may post ci/kubeconform and ci/kyverno from its own validators when the host runs no CI. Only on the - # Gitea stand-in, whose protection can name a context but not who sets it. On GitHub never: a ci/* the bot's token posted is - # the worker vouching for itself (#60). - posts_ci = True - - def __init__(self, api_url: str, repository: str, token: str, *, default_branch: str = "main", - verify: ssl.SSLContext | str | bool = True, web_url: str | None = None, timeout: float = 20.0, - basic_auth: tuple[str, str] | None = None): - self.api_url, self.repository, self.default_branch = api_url.rstrip("/"), repository, default_branch - self.web_url = (web_url or self.api_url).rstrip("/") - self._client = httpx.Client(base_url=self.api_url, verify=verify, timeout=timeout, - headers=self._headers(token) if token else {"Accept": "application/json"}, - auth=basic_auth) - from cmapi.core.git.oplog import register_secret - - credentials = credential_values(token, basic_auth) - for value in credentials: - register_secret(value) - self._forms = order_forms({form for value in credentials for form in sent_forms(value)}) - - def _headers(self, token: str) -> dict[str, str]: - return {"Authorization": f"token {token}", "Accept": "application/json"} - - def redact(self, text: str) -> str: - """`text` without the bot's credential in any form (core/clients/redact.py): the whole text, before any cut.""" - return redact(text, self._forms) - - def host_text(self, r: httpx.Response, limit: int = 300) -> str: - """The host's answer as error text: redacted, then cut to `limit` characters (#424).""" - return redact_cut(r.text, self._forms, limit) - - def commit_lines(self, commits: Iterable[Mapping[str, Any]]) -> list[str]: - """` ` of each commit of the host's list. The subject is text the host returns, and GET - /api/v1/admin/git-log serves it to every reports:read caller, so it is redacted; the sha is left as it is (#424).""" - return [f"{c['sha'][:8]} {self.redact(c['commit']['message'].splitlines()[0])}" for c in commits] - - def _call(self, operation: str, method: str, path: str, *, ok: tuple[int, ...] = (200, 201, 204), - log_fields: Mapping[str, Any] | None = None, **kw: Any) -> httpx.Response: - from cmapi.core.git.oplog import Op - from cmapi.core.observability import PLATFORM_REQUESTS - - with Op(operation, method=method, path=path, platform=self.name, **(log_fields or {})) as op: - try: - r = self._client.request(method, path, **kw) - except httpx.HTTPError as exc: - PLATFORM_REQUESTS.labels(self.name, operation, "error").inc() - op.outcome = "retry" - # An HTTP library's error can show the header it refused ("illegal header value b'...'"). Not chained: the - # worker logs traceback.format_exc(), which prints the cause's own, unredacted text (#444). - raise GitUnavailable(self.redact(f"{operation}: {type(exc).__name__}: {exc}")) from None - PLATFORM_REQUESTS.labels(self.name, operation, f"{r.status_code // 100}xx").inc() - op.set(http_status=r.status_code, host_request_id=r.headers.get("x-github-request-id") or r.headers.get("x-request-id")) - if r.status_code >= 500 or r.status_code == 429: - op.set(message=self.host_text(r)) - op.outcome = "retry" - raise GitUnavailable(f"{operation}: the Git host answered {r.status_code}: {self.host_text(r, 200)}") - if r.status_code not in ok: - op.outcome = "refused" - op.set(message=self.host_text(r)) - return r - - # ---- the Git side: a Git layer, or the host's REST API - # How long a full object ID is on this host: 40 hex characters (SHA-1). A host with SHA-256 repositories adds 64. - object_id_lengths: tuple[int, ...] = (40,) - - def _folder_head(self, ref: str | None) -> str: - """An omitted ref selects the configured branch. An explicit object ID pins the read.""" - if ref and is_commit_id(ref, self.object_id_lengths): - return ref - branch = ref or self.default_branch - head = self.branch_head(branch) - if head is None: - raise GitUnavailable(f"branch {branch} does not exist") - return head - - def read_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: - """Files under path at ref (default branch head), keyed by repository path, and the commit sha.""" - raise NotImplementedError - - def tree_files(self, ref: str, folder: str) -> dict[str, str]: - files, _ = self.read_folder(folder, ref) - return files - - def list_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: - """Every entry under path at ref, at any depth, that is not a folder, and the commit sha: {repository path: Git object - type}, "blob" for a file, an executable or a symlink and "commit" for a submodule. read_folder reads cmapi's manifests - (the .yaml files directly in the folder); this lists what a delete removes, whatever made it (#616). IncompleteList - when the host cannot give each entry.""" - raise NotImplementedError - - def branch_head(self, branch: str) -> str | None: - raise NotImplementedError - - def contains(self, revision: str, sha: str) -> bool: - """Whether sha is revision or one of its ancestors.""" - raise NotImplementedError - - def changed_paths(self, head: str) -> set[str]: - """Every path any commit on head touches since it left the default branch. IncompleteList when the host cannot - give each one.""" - raise NotImplementedError - - def log(self, n: int = 20) -> list[str]: - raise NotImplementedError - - def push_request_branch(self, req: BranchRequest) -> PushResult: - """The request's branch, one commit of the plan on the default branch's head.""" - raise NotImplementedError - - def recreate_branch(self, req: BranchRequest, base: str, expected: str) -> str: - """The branch again from its recorded base, the same sha (the reproducible commit).""" - raise NotImplementedError - - def merge_check(self, head: str, folder: str, prev: Mapping[str, str], files: Mapping[str, str | None], *, - whole_folder: bool = False) -> MergeCheck: - """Before an apply and a merge. With no Git layer (the Gitea stand-in): the folder on the default branch compared with the - plan's base; the host's own merge refuses a conflict. A provider with the Git layer runs git merge-tree. - - whole_folder, a delete (#616): the folder must leave Git whole, so main's full listing is the plan's removals, each a - file, and the head's folder is empty. A path main gained after the push is refused here, before the merge, not found - after it (_merged).""" - from cmapi.core.git.oplog import Op - - with Op("merge_check", head_sha=head) as op: - try: - on_main, main = self.read_folder(folder) - base_ok = on_main == dict(prev) - except NotUtf8: # a name the plan cannot hold: main is not its base (#626) - main, base_ok = self._folder_head(None), False - result_ok = True - if whole_folder: - base_ok = base_ok and as_plan(lambda: self.list_folder(folder, main)[0] == dict.fromkeys(files, "blob")) - result_ok = as_plan(lambda: not self.list_folder(folder, head)[0]) - check = MergeCheck(main, head, (), base_ok, result_ok) - op.set(main_sha=main, base_matches=check.base_matches, result_matches=check.result_matches) - if not check.ok: - op.outcome = "refused" - return check - - def delete_branch(self, branch: str, expected: str) -> bool: - """Delete the host's branch only when it is at expected. Missing is success.""" - raise NotImplementedError - - def list_branches(self, prefix: str) -> dict[str, str]: - """{branch: sha} of the host's branches under prefix, for git_reconcile.""" - raise NotImplementedError - - def request_of(self, sha: str) -> str | None: - """The Cmapi-Request-Id trailer of a commit: whose branch head this is. None: not cmapi's, or not known.""" - return None - - def branch_time(self, sha: str) -> int: - """The commit time of a branch head, for git_reconcile's grace period.""" - raise NotImplementedError - - # ---- the PR: the host's API - def find_pr(self, branch: str) -> PrRef | None: - """The open PR from the branch into the default branch.""" - raise NotImplementedError - - def open_pr(self, branch: str, head: str, title: str, body: str) -> PrRef: - """Open it, or return the one that exists for the branch. Its head must be head.""" - raise NotImplementedError - - def pr_status(self, pr: PrRef) -> PrStatus: - raise NotImplementedError - - def merge(self, pr: PrRef, expected_head: str) -> str: - """Merge only if the PR head is expected_head: the merge sha. HeadMoved, NotMergeable, PlatformRefused, GitUnavailable.""" - raise NotImplementedError - - def comment(self, pr: PrRef, text: str) -> None: - raise NotImplementedError - - def close(self, pr: PrRef, comment: str) -> None: - raise NotImplementedError - - def list_open(self, prefix: str) -> list[PrRef]: - """Every open PR whose source branch starts with prefix, all pages, or it raises.""" - raise NotImplementedError - - def set_check(self, sha: str, context: str, state: CheckState, description: str, target_url: str | None = None) -> None: - raise NotImplementedError - - # ---- this pod's working storage - def cleanup(self, cluster_id: str, request_id: str) -> None: - """The request's worktree on this pod. A provider with no Git layer keeps none.""" - - def sweep(self, open_requests: Iterable[tuple[str, str]]): - """The sweeper's pass, in the worker loop between jobs. A provider with no Git layer has nothing to sweep.""" - return None - - def dispose(self) -> None: - """Release what the provider holds at shutdown. Not close(), which closes a PR.""" +"""What the platform adapters share (#286): one httpx client, one structured event per host call, and the error contract. + +The platform layer is thin: open a PR from the request branch, read its state, merge it pinned to a sha, comment, close. A +provider with a Git layer (GitHub) writes branches and reads trees through it; one without (the Gitea stand-in) through REST. + +A Git host failure is GitUnavailable; the worker turns it into a retry with backoff. HeadMoved and NotMergeable say why a +merge did not happen; PlatformRefused is a refusal that a retry cannot fix. Each call logs its op, outcome, HTTP status and, +on a refusal, the host's message (core/git/oplog.py), and counts in cmapi_git_platform_requests_total{platform,op,code}. + +The host's message is text the host chose: a host or a proxy in front of it may echo the request, the Authorization header +included. So every text taken from an answer passes through host_text, which removes each form of the bot's credential and +only then cuts (docs/02 "Client rules", #424); every error, request event, log line and API answer built from it is clean. +""" +from __future__ import annotations + +import base64 +import ssl +from dataclasses import dataclass +from datetime import datetime +from typing import Any, Callable, Iterable, Literal, Mapping + +import httpx + +from cmapi.core.clients.redact import order_forms, redact, redact_cut, sent_forms +from cmapi.core.ports import PrRef, PrStatus + +CheckState = Literal["pending", "success", "failure"] + + +class GitUnavailable(RuntimeError): + pass + + +class IncompleteList(GitUnavailable): + """The host gave a list that it can have cut, so nothing may read it as complete. A caller that does not handle it + treats the host as unavailable, which is the safe reading.""" + + +class PlatformRefused(GitUnavailable): + """401, 403, 404, 422 and the like: the host said no, and saying it again will not change that.""" + + def __init__(self, message: str, status: int | None = None, host_message: str = ""): + super().__init__(message) + self.status, self.host_message = status, host_message + + +class HeadMoved(PlatformRefused): + """The PR's head is not the pinned sha: nothing was merged.""" + + +class NotMergeable(GitUnavailable): + """The host will not merge now. transient: it is still computing, or a required check is pending.""" + + def __init__(self, message: str, transient: bool = False): + super().__init__(message) + self.transient = transient + + +# U+FFFD, what a REST host answers for a byte that is not UTF-8 in a name: measured on api.github.com (git/trees and Contents, +# 2026-11-24), and what Gitea's JSON encoder writes (json-iterator, writeStringSlowPathWithHTMLEscaped). It cannot be told from +# a name that holds U+FFFD itself, so no provider carries either (#626). +REPLACEMENT = "\ufffd" + + +class NotUtf8(Exception): + """Paths under a folder whose name, or a manifest whose text (part), is not UTF-8, so cmapi cannot carry them (#626). + + Git keeps a name as bytes, and a plan, the API's JSON and the database hold text. Each path is as shown() shows it. Not + GitUnavailable: Git answered, and a retry reads the same folder.""" + + def __init__(self, paths: Iterable[str], part: Literal["name", "text"]): + self.paths, self.part = sorted(paths), part + # U+FFFD is valid UTF-8: a REST host's stand-in for a lost byte, or typed on purpose. Either way no plan can carry it. + self.rule = "is not UTF-8 or holds U+FFFD" if any(REPLACEMENT in p for p in self.paths) else "is not UTF-8" + super().__init__(f"the {part} of {', '.join(self.paths[:3])}{' and more' if len(self.paths) > 3 else ''} {self.rule}") + + +def shown(raw: bytes) -> str: + """A path of NotUtf8, to show: each backslash doubled, as Git's own quoting always escapes one (core.quotePath), and each + byte that is not UTF-8 as \\xNN (codecs, 'backslashreplace'). So each shown path stands for one name only (#626).""" + return raw.replace(b"\\", b"\\\\").decode(errors="backslashreplace") + + +def git_name(raw: bytes) -> tuple[str, bool]: + """A name as `git ls-tree -z` gives it ("the filename is output verbatim", git-ls-tree(1)), as text, and whether cmapi can + carry it: valid UTF-8 with no U+FFFD. A name it cannot carry comes back as shown() shows it.""" + try: + name = raw.decode() + except UnicodeDecodeError: + return shown(raw), False + return (name, True) if REPLACEMENT not in name else (shown(raw), False) + + +def refuse_lost_names(paths: Iterable[str]) -> None: + """NotUtf8 for each name a REST host gave with U+FFFD: the byte it stands for is lost, so no plan can name the path.""" + lost = [shown(p.encode()) for p in paths if REPLACEMENT in p] + if lost: + raise NotUtf8(lost, "name") + + +def manifest_text(texts: Mapping[str, bytes]) -> dict[str, str]: + """Each manifest's bytes as text, strict UTF-8 as YAML is read here; NotUtf8 names every one that is not.""" + files, bad = {}, [] + for path, data in texts.items(): + try: + files[path] = data.decode() + except UnicodeDecodeError: + bad.append(shown(path.encode())) + if bad: + raise NotUtf8(bad, "text") + return files + + +def as_plan(read: Callable[[], bool]) -> bool: + """A folder read compared with the plan's, by read. A folder that holds a name or text that is not UTF-8 is never the + plan's, since the plan refuses one (#626), so the comparison is False rather than an error.""" + try: + return read() + except NotUtf8: + return False + + +@dataclass(frozen=True) +class BranchRequest: + """What a provider needs to write a request's branch.""" + cluster_id: str + request_id: str + folder: str + plan_hash: str + message: str + files: Mapping[str, str | None] # the plan's files: text, or None for a path the plan removes + prev: Mapping[str, str] # the folder before the plan (plan.prev) + approved_at: datetime # both commit dates: the reproducible commit + + +@dataclass(frozen=True) +class PushResult: + head: str + base: str + result: Literal["created", "adopted", "replaced"] + + +@dataclass(frozen=True) +class MergeCheck: + """git merge-tree --write-tree
, and the folder's two comparisons (Fable 2.3).""" + main_sha: str + head_sha: str + conflicts: tuple[str, ...] = () + base_matches: bool = True # the folder on main is the plan's prev + result_matches: bool = True # the folder in the merged tree is the plan's files + tree: str | None = None + + @property + def ok(self) -> bool: + return not self.conflicts and self.base_matches and self.result_matches + + def reason(self, branch: str = "main") -> str: + if self.conflicts: + return f"conflicts with {branch} at {self.main_sha[:8]} in {', '.join(self.conflicts)}" + if not self.base_matches: + return f"the folder on {branch} at {self.main_sha[:8]} is no longer the plan's base" + if not self.result_matches: + return f"the merge of {self.head_sha[:8]} into {branch} at {self.main_sha[:8]} would not leave the folder as planned" + return "clean" + + +def is_commit_id(ref: str, lengths: tuple[int, ...] = (40,)) -> bool: + """Whether an explicit ref has the spelling of a full lowercase object ID of one of these lengths (SHA-1 has 40).""" + return len(ref) in lengths and all(c in "0123456789abcdef" for c in ref) + + +def credential_values(token: str | None, basic_auth: tuple[str, str] | None) -> tuple[str, ...]: + """Each value of the bot's credential that a host could echo: the token, and with Basic auth the password and the header's + value as httpx sends it, base64 of user:password in UTF-8 (RFC 7617).""" + values = [token or ""] + if basic_auth: + user, password = basic_auth + values += [password, base64.b64encode(f"{user}:{password}".encode("utf-8")).decode("ascii")] + return tuple(v for v in values if v) + + +class HostGitProvider: + """The contract. Subclasses fill in the host's endpoints.""" + + name = "host" + BOT_NAME = "cmapi-git-bot" + BOT_EMAIL = "cmapi-git-bot@noreply.invalid" + # Whether the host's own CI reports ci/kubeconform and ci/kyverno (GitHub: the config repository's Actions jobs, #60). The + # worker then waits for them there and never posts them. The Gitea stand-in has no runner, so it keeps False. + external_ci = False + # Whether the worker posts its checks as commit statuses. The Gitea stand-in protects main with all three + # (tools/git_bootstrap.py); GitHub posts cmapi/check alone, with host CI or git.postStatus on (the arbitration of #286, row 11). + post_statuses = True + # Whether the worker may post ci/kubeconform and ci/kyverno from its own validators when the host runs no CI. Only on the + # Gitea stand-in, whose protection can name a context but not who sets it. On GitHub never: a ci/* the bot's token posted is + # the worker vouching for itself (#60). + posts_ci = True + + def __init__(self, api_url: str, repository: str, token: str, *, default_branch: str = "main", + verify: ssl.SSLContext | str | bool = True, web_url: str | None = None, timeout: float = 20.0, + basic_auth: tuple[str, str] | None = None): + self.api_url, self.repository, self.default_branch = api_url.rstrip("/"), repository, default_branch + self.web_url = (web_url or self.api_url).rstrip("/") + self._client = httpx.Client(base_url=self.api_url, verify=verify, timeout=timeout, + headers=self._headers(token) if token else {"Accept": "application/json"}, + auth=basic_auth) + from cmapi.core.git.oplog import register_secret + + credentials = credential_values(token, basic_auth) + for value in credentials: + register_secret(value) + self._forms = order_forms({form for value in credentials for form in sent_forms(value)}) + + def _headers(self, token: str) -> dict[str, str]: + return {"Authorization": f"token {token}", "Accept": "application/json"} + + def redact(self, text: str) -> str: + """`text` without the bot's credential in any form (core/clients/redact.py): the whole text, before any cut.""" + return redact(text, self._forms) + + def host_text(self, r: httpx.Response, limit: int = 300) -> str: + """The host's answer as error text: redacted, then cut to `limit` characters (#424).""" + return redact_cut(r.text, self._forms, limit) + + def commit_lines(self, commits: Iterable[Mapping[str, Any]]) -> list[str]: + """` ` of each commit of the host's list. The subject is text the host returns, and GET + /api/v1/admin/git-log serves it to every reports:read caller, so it is redacted; the sha is left as it is (#424).""" + return [f"{c['sha'][:8]} {self.redact(c['commit']['message'].splitlines()[0])}" for c in commits] + + def _call(self, operation: str, method: str, path: str, *, ok: tuple[int, ...] = (200, 201, 204), + log_fields: Mapping[str, Any] | None = None, **kw: Any) -> httpx.Response: + from cmapi.core.git.oplog import Op + from cmapi.core.observability import PLATFORM_REQUESTS + + with Op(operation, method=method, path=path, platform=self.name, **(log_fields or {})) as op: + try: + r = self._client.request(method, path, **kw) + except httpx.HTTPError as exc: + PLATFORM_REQUESTS.labels(self.name, operation, "error").inc() + op.outcome = "retry" + # An HTTP library's error can show the header it refused ("illegal header value b'...'"). Not chained: the + # worker logs traceback.format_exc(), which prints the cause's own, unredacted text (#444). + raise GitUnavailable(self.redact(f"{operation}: {type(exc).__name__}: {exc}")) from None + PLATFORM_REQUESTS.labels(self.name, operation, f"{r.status_code // 100}xx").inc() + op.set(http_status=r.status_code, host_request_id=r.headers.get("x-github-request-id") or r.headers.get("x-request-id")) + if r.status_code >= 500 or r.status_code == 429: + op.set(message=self.host_text(r)) + op.outcome = "retry" + raise GitUnavailable(f"{operation}: the Git host answered {r.status_code}: {self.host_text(r, 200)}") + if r.status_code not in ok: + op.outcome = "refused" + op.set(message=self.host_text(r)) + return r + + # ---- the Git side: a Git layer, or the host's REST API + # How long a full object ID is on this host: 40 hex characters (SHA-1). A host with SHA-256 repositories adds 64. + object_id_lengths: tuple[int, ...] = (40,) + + def _folder_head(self, ref: str | None) -> str: + """An omitted ref selects the configured branch. An explicit object ID pins the read.""" + if ref and is_commit_id(ref, self.object_id_lengths): + return ref + branch = ref or self.default_branch + head = self.branch_head(branch) + if head is None: + raise GitUnavailable(f"branch {branch} does not exist") + return head + + def read_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: + """Files under path at ref (default branch head), keyed by repository path, and the commit sha.""" + raise NotImplementedError + + def tree_files(self, ref: str, folder: str) -> dict[str, str]: + files, _ = self.read_folder(folder, ref) + return files + + def list_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: + """Every entry under path at ref, at any depth, that is not a folder, and the commit sha: {repository path: Git object + type}, "blob" for a file, an executable or a symlink and "commit" for a submodule. read_folder reads cmapi's manifests + (the .yaml files directly in the folder); this lists what a delete removes, whatever made it (#616). IncompleteList + when the host cannot give each entry.""" + raise NotImplementedError + + def branch_head(self, branch: str) -> str | None: + raise NotImplementedError + + def contains(self, revision: str, sha: str) -> bool: + """Whether sha is revision or one of its ancestors.""" + raise NotImplementedError + + def changed_paths(self, head: str) -> set[str]: + """Every path any commit on head touches since it left the default branch. IncompleteList when the host cannot + give each one.""" + raise NotImplementedError + + def log(self, n: int = 20) -> list[str]: + raise NotImplementedError + + def push_request_branch(self, req: BranchRequest) -> PushResult: + """The request's branch, one commit of the plan on the default branch's head.""" + raise NotImplementedError + + def recreate_branch(self, req: BranchRequest, base: str, expected: str) -> str: + """The branch again from its recorded base, the same sha (the reproducible commit).""" + raise NotImplementedError + + def merge_check(self, head: str, folder: str, prev: Mapping[str, str], files: Mapping[str, str | None], *, + whole_folder: bool = False) -> MergeCheck: + """Before an apply and a merge. With no Git layer (the Gitea stand-in): the folder on the default branch compared with the + plan's base; the host's own merge refuses a conflict. A provider with the Git layer runs git merge-tree. + + whole_folder, a delete (#616): the folder must leave Git whole, so main's full listing is the plan's removals, each a + file, and the head's folder is empty. A path main gained after the push is refused here, before the merge, not found + after it (_merged).""" + from cmapi.core.git.oplog import Op + + with Op("merge_check", head_sha=head) as op: + try: + on_main, main = self.read_folder(folder) + base_ok = on_main == dict(prev) + except NotUtf8: # a name the plan cannot hold: main is not its base (#626) + main, base_ok = self._folder_head(None), False + result_ok = True + if whole_folder: + base_ok = base_ok and as_plan(lambda: self.list_folder(folder, main)[0] == dict.fromkeys(files, "blob")) + result_ok = as_plan(lambda: not self.list_folder(folder, head)[0]) + check = MergeCheck(main, head, (), base_ok, result_ok) + op.set(main_sha=main, base_matches=check.base_matches, result_matches=check.result_matches) + if not check.ok: + op.outcome = "refused" + return check + + def delete_branch(self, branch: str, expected: str) -> bool: + """Delete the host's branch only when it is at expected. Missing is success.""" + raise NotImplementedError + + def list_branches(self, prefix: str) -> dict[str, str]: + """{branch: sha} of the host's branches under prefix, for git_reconcile.""" + raise NotImplementedError + + def request_of(self, sha: str) -> str | None: + """The Cmapi-Request-Id trailer of a commit: whose branch head this is. None: not cmapi's, or not known.""" + return None + + def branch_time(self, sha: str) -> int: + """The commit time of a branch head, for git_reconcile's grace period.""" + raise NotImplementedError + + # ---- the PR: the host's API + def find_pr(self, branch: str) -> PrRef | None: + """The open PR from the branch into the default branch.""" + raise NotImplementedError + + def open_pr(self, branch: str, head: str, title: str, body: str) -> PrRef: + """Open it, or return the one that exists for the branch. Its head must be head.""" + raise NotImplementedError + + def pr_status(self, pr: PrRef, *, ci: bool = True) -> PrStatus: + raise NotImplementedError + + def merge(self, pr: PrRef, expected_head: str) -> str: + """Merge only if the PR head is expected_head: the merge sha. HeadMoved, NotMergeable, PlatformRefused, GitUnavailable.""" + raise NotImplementedError + + def comment(self, pr: PrRef, text: str) -> None: + raise NotImplementedError + + def close(self, pr: PrRef, comment: str) -> None: + raise NotImplementedError + + def list_open(self, prefix: str) -> list[PrRef]: + """Every open PR whose source branch starts with prefix, all pages, or it raises.""" + raise NotImplementedError + + def set_check(self, sha: str, context: str, state: CheckState, description: str, target_url: str | None = None) -> None: + raise NotImplementedError + + # ---- this pod's working storage + def cleanup(self, cluster_id: str, request_id: str) -> None: + """The request's worktree on this pod. A provider with no Git layer keeps none.""" + + def sweep(self, open_requests: Iterable[tuple[str, str]]): + """The sweeper's pass, in the worker loop between jobs. A provider with no Git layer has nothing to sweep.""" + return None + + def dispose(self) -> None: + """Release what the provider holds at shutdown. Not close(), which closes a PR.""" diff --git a/cmapi/src/cmapi/core/git/gitea.py b/cmapi/src/cmapi/core/git/gitea.py index 0bfa9e3f..3af20e2a 100644 --- a/cmapi/src/cmapi/core/git/gitea.py +++ b/cmapi/src/cmapi/core/git/gitea.py @@ -1,315 +1,316 @@ -"""GitProvider for Gitea (API v1). Endpoints as documented for Gitea 1.25: - - GET /repos/{o}/{r}/branches/{b} head sha - GET /repos/{o}/{r}/git/commits/{sha} a commit: its message (the trailers) and its parents - GET /repos/{o}/{r}/contents/{path}?ref= folder listing, file content (base64) - POST /repos/{o}/{r}/branches {new_branch_name, old_ref_name} - POST /repos/{o}/{r}/contents one commit with several files {files: [...]} - POST /repos/{o}/{r}/pulls {head, base, title, body} - GET /repos/{o}/{r}/pulls/{n} state, merged, head.sha, merge_commit_sha - GET /repos/{o}/{r}/pulls?state=open&head= open PR from a branch - POST /repos/{o}/{r}/statuses/{sha} commit status {state, context, description} - GET /repos/{o}/{r}/commits/{sha}/status combined status - POST /repos/{o}/{r}/pulls/{n}/merge {Do: merge, head_commit_id, delete_branch_after_merge} - PATCH /repos/{o}/{r}/pulls/{n} {state: closed} -""" -from __future__ import annotations - -import base64 -from itertools import count -from pathlib import PurePosixPath -from typing import Any, Iterator, Mapping -from urllib.parse import quote - -from cmapi.core.git.base import (BranchRequest, CheckState, GitUnavailable, HostGitProvider, PushResult, manifest_text, - refuse_lost_names) -from cmapi.core.git.workspace import TRAILER_PLAN_HASH, TRAILER_REQUEST, BranchMoved, BranchRefused, request_branch -from cmapi.core.ports import PrRef, PrStatus - - -class GiteaProvider(HostGitProvider): - name = "gitea" - object_id_lengths = (40, 64) # a Gitea repository is SHA-1 or SHA-256, as the Git layer's _OID reads both - - def _repo(self) -> str: - return f"/repos/{self.repository}" - - def branch_head(self, branch: str) -> str | None: - # A name is data in the path: "#", "?" and "%" are escaped (RFC 3986, sections 2.4 and 3.3). Gitea routes branches, - # compare and contents with a "/*" wildcard, so a "/" in a branch name or a file path stays a "/" (#638). - r = self._call("branch_head", "GET", f"{self._repo()}/branches/{quote(branch)}", ok=(200, 404)) - return r.json()["commit"]["id"] if r.status_code == 200 else None - - def _tree_entries(self, oid: str) -> Iterator[dict[str, Any]]: - for page in count(1): - r = self._call("read_folder", "GET", f"{self._repo()}/git/trees/{oid}", params={"page": page}) - if r.status_code != 200: - raise GitUnavailable(f"read tree {oid}: HTTP {r.status_code}") - body = r.json() - entries = body["tree"] or [] - if body["truncated"] and (not entries or body["page"] != page): - raise GitUnavailable(f"incomplete page {page} of tree {oid}") - yield from entries - if not body["truncated"]: - return - - def read_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: - head = self._folder_head(ref) - # Gitea Contents resolves a branch or tag before a commit. Trees and blobs accept object IDs. - directory = PurePosixPath(path.strip("/")) - tree = head - for i, part in enumerate(directory.parts): - entry = next((e for e in self._tree_entries(tree) if e["path"] == part), None) - if entry is None: - return {}, head - if entry["type"] != "tree": - if i + 1 < len(directory.parts): - return {}, head - entries = [entry] # Contents also supports a direct file path. - directory = directory.parent - break - tree = entry["sha"] - else: - entries = self._tree_entries(tree) - manifests = {str(directory / e["path"]): e["sha"] for e in entries - if e["type"] == "blob" and e["mode"] in ("100644", "100755") and e["path"].endswith(".yaml")} - # Gitea's JSON writes a byte that is not UTF-8 as U+FFFD (json-iterator): no plan can name the file (#626). - refuse_lost_names(manifests) - texts: dict[str, bytes] = {} - for path, sha in manifests.items(): - r = self._call("read_file", "GET", f"{self._repo()}/git/blobs/{sha}") - if r.status_code != 200: - raise GitUnavailable(f"read blob {sha}: HTTP {r.status_code}") - texts[path] = base64.b64decode(r.json()["content"]) - return manifest_text(texts), head - - def list_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: - """Every blob and submodule under path, at any depth (#616): each subtree read with _tree_entries, page by page, so no - recursive listing that the host may cut is read as complete.""" - entries, head = self._walk(path, ref) - refuse_lost_names(entries) # a delete removes each path, so it must name each one (#626) - return {p: kind for p, (kind, _) in entries.items()}, head - - def _walk(self, path: str, ref: str | None) -> tuple[dict[str, tuple[str, str]], str]: - """list_folder with each entry's object ID: {path: (type, ID)}. The ID is what a delete sends as its sha, the tree - entry's own, which Gitea compares it with, so no URL has to carry a name that holds "#" or "?" (#616).""" - head = self._folder_head(ref) - tree = head - directory = PurePosixPath(path.strip("/")) - for part in directory.parts: - entry = next((e for e in self._tree_entries(tree) if e["path"] == part), None) - if entry is None or entry["type"] != "tree": - return {}, head - tree = entry["sha"] - listed: dict[str, tuple[str, str]] = {} - pending = [(directory, tree)] - while pending: - where, oid = pending.pop() - for e in self._tree_entries(oid): - if e["type"] == "tree": - pending.append((where / e["path"], e["sha"])) - else: - listed[str(where / e["path"])] = (e["type"], e["sha"]) - return listed, head - - def push_request_branch(self, req: BranchRequest) -> PushResult: - """Through Gitea's REST API, not the Git layer: the chart's stand-in, whose Gitea the cluster serves over plain http, which - the Git layer refuses. A branch that exists is handled as the Git layer handles it (the arbitration of #286, row 3; - #450): adopted when its head is this request's commit of this plan with the plan's files; deleted and written again - when it is this request's own stale attempt; refused, and left as it is, when it is anyone else's. An open PR proves - nothing about the head. REST has no lease, so the delete of a stale attempt reads the head first (delete_branch).""" - branch = request_branch(req.cluster_id, req.request_id) - base = self.branch_head(self.default_branch) - if base is None: - raise GitUnavailable(f"branch {self.default_branch} does not exist") - existing = self.branch_head(branch) - if existing is not None: - trailers, parents = self._commit(existing) - planned = {p: t for p, t in req.files.items() if t is not None} - if trailers.get(TRAILER_REQUEST) != [req.request_id]: - raise BranchRefused(f"branch {branch} exists at {existing[:8]} and its head is not cmapi's commit for " - f"{req.request_id}: it is not adopted or overwritten") - if trailers.get(TRAILER_PLAN_HASH) == [req.plan_hash] and len(parents) == 1 and \ - self.read_folder(req.folder, existing)[0] == planned: - return PushResult(existing, parents[0], "adopted") - if not self.delete_branch(branch, existing): - raise BranchMoved(f"branch {branch} moved from {existing[:8]} before its stale attempt was replaced") - # The folder at main's commit, which the new branch starts from, read before the branch exists: a read that fails (a name - # that is not UTF-8, #626, or the host) leaves no branch at main's commit, which a retry would refuse as not cmapi's. - current, _ = self.read_folder(req.folder, base) - # A removal is any path of the folder, not only a manifest (#616). Only a plan that removes one walks the subfolders. - listed = self._walk(req.folder, base)[0] if any(text is None for text in req.files.values()) else {} - r = self._call("create_branch", "POST", f"{self._repo()}/branches", - json={"new_branch_name": branch, "old_ref_name": base}, ok=(201,)) - if r.status_code != 201: - raise GitUnavailable(f"create branch {branch}: {r.status_code} {self.host_text(r, 200)}") - ops = [] - for path, text in req.files.items(): - if text is None: - if path in listed: - ops.append({"operation": "delete", "path": path, "sha": listed[path][1]}) - elif path in current: - if current[path] != text: - ops.append({"operation": "update", "path": path, "sha": self._blob_sha(path, branch), "content": _b64(text)}) - else: - ops.append({"operation": "create", "path": path, "content": _b64(text)}) - if ops: - r = self._call("commit", "POST", f"{self._repo()}/contents", - json={"branch": branch, "message": req.message, "files": ops, - "author": {"name": self.BOT_NAME, "email": self.BOT_EMAIL}, - "committer": {"name": self.BOT_NAME, "email": self.BOT_EMAIL}}, ok=(200, 201)) - if r.status_code not in (200, 201): - raise GitUnavailable(f"commit on {branch}: {r.status_code} {self.host_text(r)}") - head = self.branch_head(branch) - return PushResult(head or base, base, "created" if existing is None else "replaced") - - def _commit(self, sha: str) -> tuple[dict[str, list[str]], list[str]]: - """A commit's cmapi trailers ({key: [values]}, from its message's last paragraph) and its parents' shas.""" - r = self._call("commit_read", "GET", f"{self._repo()}/git/commits/{sha}", ok=(200,)) - if r.status_code != 200: - raise GitUnavailable(f"read commit {sha[:8]}: {r.status_code} {self.host_text(r, 200)}") - body = r.json() - paragraphs = [p for p in ((body.get("commit") or {}).get("message") or "").strip().split("\n\n") if p.strip()] - trailers: dict[str, list[str]] = {} - for line in (paragraphs[-1].splitlines() if paragraphs else []): - key, sep, value = line.partition(":") - if sep and key.strip() in (TRAILER_REQUEST, TRAILER_PLAN_HASH): - trailers.setdefault(key.strip(), []).append(value.strip()) - return trailers, [p["sha"] for p in body.get("parents") or []] - - - def recreate_branch(self, req: BranchRequest, base: str, expected: str) -> str: - raise GitUnavailable("the Gitea stand-in is not on the Git layer: a closed PR's branch is not re-created") - - def open_pr(self, branch: str, head: str, title: str, body: str) -> PrRef: - existing = self.find_pr(branch) - if existing is None: - r = self._call("open_pr", "POST", f"{self._repo()}/pulls", - json={"head": branch, "base": self.default_branch, "title": title, "body": body}, ok=(201,)) - if r.status_code != 201: - raise GitUnavailable(f"open PR from {branch}: {r.status_code} {self.host_text(r)}") - existing = self._pr_ref(r.json()) - return existing - - def comment(self, pr: PrRef, text: str) -> None: - self._call("comment", "POST", f"{self._repo()}/issues/{pr.number}/comments", json={"body": text}, ok=(201,)) - - def delete_branch(self, branch: str, expected: str) -> bool: - """Gitea's REST delete is not conditional: the head is read first, and a race in between is the stand-in's to accept.""" - head = self.branch_head(branch) - if head is None: - return True - if head != expected: - return False - r = self._call("delete_branch", "DELETE", f"{self._repo()}/branches/{quote(branch)}", ok=(204, 404)) - return r.status_code in (204, 404) - - def _list_pages(self, operation: str, resource: str, **filters: str) -> Iterator[dict[str, Any]]: - path = f"{self._repo()}/{resource}" - for page in count(1): - response = self._call(operation, "GET", path, params={**filters, "limit": 50, "page": page}) - if response.status_code != 200: - raise GitUnavailable(f"{operation}: GET {path} page {page}: HTTP {response.status_code}") - yield from response.json() - if "next" not in response.links: - return - - def list_open(self, prefix: str) -> list[PrRef]: - return [self._pr_ref(p) for p in self._list_pages("find_pr", "pulls", state="open") - if p["head"]["ref"].startswith(prefix)] - - def list_branches(self, prefix: str) -> dict[str, str]: - return {b["name"]: b["commit"]["id"] for b in self._list_pages("branches", "branches") - if b["name"].startswith(prefix)} - - def branch_time(self, sha: str) -> int: - from datetime import datetime - - r = self._call("commit_read", "GET", f"{self._repo()}/git/commits/{sha}") - return int(datetime.fromisoformat(r.json()["created"].replace("Z", "+00:00")).timestamp()) - - def contains(self, revision: str, sha: str) -> bool: - if revision == sha: - return True - r = self._call("compare", "GET", f"{self._repo()}/compare/{quote(revision)}...{sha}") - if r.status_code == 404: # not this repository's: a multi-source Application's other source, or a force-pushed commit - return False - if r.status_code != 200: - raise GitUnavailable(f"compare {revision[:8]}...{sha[:8]}: {r.status_code} {self.host_text(r, 200)}") - return r.json().get("total_commits", 1) == 0 - - def changed_paths(self, head: str) -> set[str]: - r = self._call("compare", "GET", f"{self._repo()}/compare/{quote(self.default_branch)}...{head}") - if r.status_code != 200: - raise GitUnavailable(f"compare {head[:8]}: {r.status_code} {self.host_text(r, 200)}") - return {f["filename"] for c in r.json().get("commits") or [] for f in c.get("files") or []} - - def _blob_sha(self, path: str, ref: str) -> str: - r = self._call("read_file", "GET", f"{self._repo()}/contents/{quote(path)}", params={"ref": ref}) - return r.json()["sha"] - - 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"]) - - def find_pr(self, branch: str) -> PrRef | None: - r = self._call("find_pr", "GET", f"{self._repo()}/pulls", params={"state": "open", "limit": 50}) - for p in r.json(): - if p["head"]["ref"] == branch: - return self._pr_ref(p) - return None - - def pr_status(self, pr: PrRef) -> PrStatus: - r = self._call("pr_status", "GET", f"{self._repo()}/pulls/{pr.number}") - if r.status_code != 200: - raise GitUnavailable(f"PR {pr.number}: {r.status_code}") - p = r.json() - head = p["head"]["sha"] - checks: dict[str, CheckState] = {} - s = self._call("pr_checks", "GET", f"{self._repo()}/commits/{head}/status", ok=(200, 404)) - if s.status_code == 200: - for st in s.json().get("statuses") or []: - checks[st["context"]] = {"success": "success", "pending": "pending"}.get(st["status"], "failure") - state = "merged" if p.get("merged") else ("open" if p["state"] == "open" else "closed") - return PrStatus(state=state, checks=checks, merge_sha=p.get("merge_commit_sha") if p.get("merged") else None, head_sha=head) - - def set_check(self, sha: str, context: str, state: CheckState, description: str, target_url: str | None = None) -> None: - body = {"context": context, "state": state, "description": description[:255]} - if target_url: - body["target_url"] = target_url - r = self._call("set_check", "POST", f"{self._repo()}/statuses/{sha}", json=body, ok=(201,)) - if r.status_code != 201: - raise GitUnavailable(f"status {context} on {sha[:8]}: {r.status_code} {self.host_text(r, 200)}") - - def merge(self, pr: PrRef, expected_head: str) -> str: - r = self._call("merge", "POST", f"{self._repo()}/pulls/{pr.number}/merge", - json={"Do": "merge", "head_commit_id": expected_head, "delete_branch_after_merge": False, - "MergeTitleField": f"Merge {pr.branch}"}, ok=(200,)) - if r.status_code != 200: - raise GitUnavailable(f"merge PR {pr.number}: {r.status_code} {self.host_text(r)}") - p = self._call("pr_status", "GET", f"{self._repo()}/pulls/{pr.number}").json() - return p.get("merge_commit_sha") or self.branch_head(self.default_branch) or "" - - def close(self, pr: PrRef, comment: str) -> None: - self._call("comment", "POST", f"{self._repo()}/issues/{pr.number}/comments", json={"body": comment}, ok=(201,)) - self._call("close", "PATCH", f"{self._repo()}/pulls/{pr.number}", json={"state": "closed"}, ok=(201, 200)) - - def log(self, n: int = 20) -> list[str]: - r = self._call("log", "GET", f"{self._repo()}/commits", params={"sha": self.default_branch, "limit": n}) - return self.commit_lines(r.json()) - - -def _b64(text: str) -> str: - return base64.b64encode(text.encode()).decode() - - -def _common_folder(files: Mapping[str, Any]) -> str: - paths = list(files) - if not paths: - return "" - parts = paths[0].split("/")[:-1] - for p in paths[1:]: - q = p.split("/")[:-1] - while parts and parts != q[:len(parts)]: - parts = parts[:-1] - return "/".join(parts) +"""GitProvider for Gitea (API v1). Endpoints as documented for Gitea 1.25: + + GET /repos/{o}/{r}/branches/{b} head sha + GET /repos/{o}/{r}/git/commits/{sha} a commit: its message (the trailers) and its parents + GET /repos/{o}/{r}/contents/{path}?ref= folder listing, file content (base64) + POST /repos/{o}/{r}/branches {new_branch_name, old_ref_name} + POST /repos/{o}/{r}/contents one commit with several files {files: [...]} + POST /repos/{o}/{r}/pulls {head, base, title, body} + GET /repos/{o}/{r}/pulls/{n} state, merged, head.sha, merge_commit_sha + GET /repos/{o}/{r}/pulls?state=open&head= open PR from a branch + POST /repos/{o}/{r}/statuses/{sha} commit status {state, context, description} + GET /repos/{o}/{r}/commits/{sha}/status combined status + POST /repos/{o}/{r}/pulls/{n}/merge {Do: merge, head_commit_id, delete_branch_after_merge} + PATCH /repos/{o}/{r}/pulls/{n} {state: closed} +""" +from __future__ import annotations + +import base64 +from itertools import count +from pathlib import PurePosixPath +from typing import Any, Iterator, Mapping +from urllib.parse import quote + +from cmapi.core.git.base import (BranchRequest, CheckState, GitUnavailable, HostGitProvider, PushResult, manifest_text, + refuse_lost_names) +from cmapi.core.git.workspace import TRAILER_PLAN_HASH, TRAILER_REQUEST, BranchMoved, BranchRefused, request_branch +from cmapi.core.ports import PrRef, PrStatus + + +class GiteaProvider(HostGitProvider): + name = "gitea" + object_id_lengths = (40, 64) # a Gitea repository is SHA-1 or SHA-256, as the Git layer's _OID reads both + + def _repo(self) -> str: + return f"/repos/{self.repository}" + + def branch_head(self, branch: str) -> str | None: + # A name is data in the path: "#", "?" and "%" are escaped (RFC 3986, sections 2.4 and 3.3). Gitea routes branches, + # compare and contents with a "/*" wildcard, so a "/" in a branch name or a file path stays a "/" (#638). + r = self._call("branch_head", "GET", f"{self._repo()}/branches/{quote(branch)}", ok=(200, 404)) + return r.json()["commit"]["id"] if r.status_code == 200 else None + + def _tree_entries(self, oid: str) -> Iterator[dict[str, Any]]: + for page in count(1): + r = self._call("read_folder", "GET", f"{self._repo()}/git/trees/{oid}", params={"page": page}) + if r.status_code != 200: + raise GitUnavailable(f"read tree {oid}: HTTP {r.status_code}") + body = r.json() + entries = body["tree"] or [] + if body["truncated"] and (not entries or body["page"] != page): + raise GitUnavailable(f"incomplete page {page} of tree {oid}") + yield from entries + if not body["truncated"]: + return + + def read_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: + head = self._folder_head(ref) + # Gitea Contents resolves a branch or tag before a commit. Trees and blobs accept object IDs. + directory = PurePosixPath(path.strip("/")) + tree = head + for i, part in enumerate(directory.parts): + entry = next((e for e in self._tree_entries(tree) if e["path"] == part), None) + if entry is None: + return {}, head + if entry["type"] != "tree": + if i + 1 < len(directory.parts): + return {}, head + entries = [entry] # Contents also supports a direct file path. + directory = directory.parent + break + tree = entry["sha"] + else: + entries = self._tree_entries(tree) + manifests = {str(directory / e["path"]): e["sha"] for e in entries + if e["type"] == "blob" and e["mode"] in ("100644", "100755") and e["path"].endswith(".yaml")} + # Gitea's JSON writes a byte that is not UTF-8 as U+FFFD (json-iterator): no plan can name the file (#626). + refuse_lost_names(manifests) + texts: dict[str, bytes] = {} + for path, sha in manifests.items(): + r = self._call("read_file", "GET", f"{self._repo()}/git/blobs/{sha}") + if r.status_code != 200: + raise GitUnavailable(f"read blob {sha}: HTTP {r.status_code}") + texts[path] = base64.b64decode(r.json()["content"]) + return manifest_text(texts), head + + def list_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: + """Every blob and submodule under path, at any depth (#616): each subtree read with _tree_entries, page by page, so no + recursive listing that the host may cut is read as complete.""" + entries, head = self._walk(path, ref) + refuse_lost_names(entries) # a delete removes each path, so it must name each one (#626) + return {p: kind for p, (kind, _) in entries.items()}, head + + def _walk(self, path: str, ref: str | None) -> tuple[dict[str, tuple[str, str]], str]: + """list_folder with each entry's object ID: {path: (type, ID)}. The ID is what a delete sends as its sha, the tree + entry's own, which Gitea compares it with, so no URL has to carry a name that holds "#" or "?" (#616).""" + head = self._folder_head(ref) + tree = head + directory = PurePosixPath(path.strip("/")) + for part in directory.parts: + entry = next((e for e in self._tree_entries(tree) if e["path"] == part), None) + if entry is None or entry["type"] != "tree": + return {}, head + tree = entry["sha"] + listed: dict[str, tuple[str, str]] = {} + pending = [(directory, tree)] + while pending: + where, oid = pending.pop() + for e in self._tree_entries(oid): + if e["type"] == "tree": + pending.append((where / e["path"], e["sha"])) + else: + listed[str(where / e["path"])] = (e["type"], e["sha"]) + return listed, head + + def push_request_branch(self, req: BranchRequest) -> PushResult: + """Through Gitea's REST API, not the Git layer: the chart's stand-in, whose Gitea the cluster serves over plain http, which + the Git layer refuses. A branch that exists is handled as the Git layer handles it (the arbitration of #286, row 3; + #450): adopted when its head is this request's commit of this plan with the plan's files; deleted and written again + when it is this request's own stale attempt; refused, and left as it is, when it is anyone else's. An open PR proves + nothing about the head. REST has no lease, so the delete of a stale attempt reads the head first (delete_branch).""" + branch = request_branch(req.cluster_id, req.request_id) + base = self.branch_head(self.default_branch) + if base is None: + raise GitUnavailable(f"branch {self.default_branch} does not exist") + existing = self.branch_head(branch) + if existing is not None: + trailers, parents = self._commit(existing) + planned = {p: t for p, t in req.files.items() if t is not None} + if trailers.get(TRAILER_REQUEST) != [req.request_id]: + raise BranchRefused(f"branch {branch} exists at {existing[:8]} and its head is not cmapi's commit for " + f"{req.request_id}: it is not adopted or overwritten") + if trailers.get(TRAILER_PLAN_HASH) == [req.plan_hash] and len(parents) == 1 and \ + self.read_folder(req.folder, existing)[0] == planned: + return PushResult(existing, parents[0], "adopted") + if not self.delete_branch(branch, existing): + raise BranchMoved(f"branch {branch} moved from {existing[:8]} before its stale attempt was replaced") + # The folder at main's commit, which the new branch starts from, read before the branch exists: a read that fails (a name + # that is not UTF-8, #626, or the host) leaves no branch at main's commit, which a retry would refuse as not cmapi's. + current, _ = self.read_folder(req.folder, base) + # A removal is any path of the folder, not only a manifest (#616). Only a plan that removes one walks the subfolders. + listed = self._walk(req.folder, base)[0] if any(text is None for text in req.files.values()) else {} + r = self._call("create_branch", "POST", f"{self._repo()}/branches", + json={"new_branch_name": branch, "old_ref_name": base}, ok=(201,)) + if r.status_code != 201: + raise GitUnavailable(f"create branch {branch}: {r.status_code} {self.host_text(r, 200)}") + ops = [] + for path, text in req.files.items(): + if text is None: + if path in listed: + ops.append({"operation": "delete", "path": path, "sha": listed[path][1]}) + elif path in current: + if current[path] != text: + ops.append({"operation": "update", "path": path, "sha": self._blob_sha(path, branch), "content": _b64(text)}) + else: + ops.append({"operation": "create", "path": path, "content": _b64(text)}) + if ops: + r = self._call("commit", "POST", f"{self._repo()}/contents", + json={"branch": branch, "message": req.message, "files": ops, + "author": {"name": self.BOT_NAME, "email": self.BOT_EMAIL}, + "committer": {"name": self.BOT_NAME, "email": self.BOT_EMAIL}}, ok=(200, 201)) + if r.status_code not in (200, 201): + raise GitUnavailable(f"commit on {branch}: {r.status_code} {self.host_text(r)}") + head = self.branch_head(branch) + return PushResult(head or base, base, "created" if existing is None else "replaced") + + def _commit(self, sha: str) -> tuple[dict[str, list[str]], list[str]]: + """A commit's cmapi trailers ({key: [values]}, from its message's last paragraph) and its parents' shas.""" + r = self._call("commit_read", "GET", f"{self._repo()}/git/commits/{sha}", ok=(200,)) + if r.status_code != 200: + raise GitUnavailable(f"read commit {sha[:8]}: {r.status_code} {self.host_text(r, 200)}") + body = r.json() + paragraphs = [p for p in ((body.get("commit") or {}).get("message") or "").strip().split("\n\n") if p.strip()] + trailers: dict[str, list[str]] = {} + for line in (paragraphs[-1].splitlines() if paragraphs else []): + key, sep, value = line.partition(":") + if sep and key.strip() in (TRAILER_REQUEST, TRAILER_PLAN_HASH): + trailers.setdefault(key.strip(), []).append(value.strip()) + return trailers, [p["sha"] for p in body.get("parents") or []] + + + def recreate_branch(self, req: BranchRequest, base: str, expected: str) -> str: + raise GitUnavailable("the Gitea stand-in is not on the Git layer: a closed PR's branch is not re-created") + + def open_pr(self, branch: str, head: str, title: str, body: str) -> PrRef: + existing = self.find_pr(branch) + if existing is None: + r = self._call("open_pr", "POST", f"{self._repo()}/pulls", + json={"head": branch, "base": self.default_branch, "title": title, "body": body}, ok=(201,)) + if r.status_code != 201: + raise GitUnavailable(f"open PR from {branch}: {r.status_code} {self.host_text(r)}") + existing = self._pr_ref(r.json()) + return existing + + def comment(self, pr: PrRef, text: str) -> None: + self._call("comment", "POST", f"{self._repo()}/issues/{pr.number}/comments", json={"body": text}, ok=(201,)) + + def delete_branch(self, branch: str, expected: str) -> bool: + """Gitea's REST delete is not conditional: the head is read first, and a race in between is the stand-in's to accept.""" + head = self.branch_head(branch) + if head is None: + return True + if head != expected: + return False + r = self._call("delete_branch", "DELETE", f"{self._repo()}/branches/{quote(branch)}", ok=(204, 404)) + return r.status_code in (204, 404) + + def _list_pages(self, operation: str, resource: str, **filters: str) -> Iterator[dict[str, Any]]: + path = f"{self._repo()}/{resource}" + for page in count(1): + response = self._call(operation, "GET", path, params={**filters, "limit": 50, "page": page}) + if response.status_code != 200: + raise GitUnavailable(f"{operation}: GET {path} page {page}: HTTP {response.status_code}") + yield from response.json() + if "next" not in response.links: + return + + def list_open(self, prefix: str) -> list[PrRef]: + return [self._pr_ref(p) for p in self._list_pages("find_pr", "pulls", state="open") + if p["head"]["ref"].startswith(prefix)] + + def list_branches(self, prefix: str) -> dict[str, str]: + return {b["name"]: b["commit"]["id"] for b in self._list_pages("branches", "branches") + if b["name"].startswith(prefix)} + + def branch_time(self, sha: str) -> int: + from datetime import datetime + + r = self._call("commit_read", "GET", f"{self._repo()}/git/commits/{sha}") + return int(datetime.fromisoformat(r.json()["created"].replace("Z", "+00:00")).timestamp()) + + def contains(self, revision: str, sha: str) -> bool: + if revision == sha: + return True + r = self._call("compare", "GET", f"{self._repo()}/compare/{quote(revision)}...{sha}") + if r.status_code == 404: # not this repository's: a multi-source Application's other source, or a force-pushed commit + return False + if r.status_code != 200: + raise GitUnavailable(f"compare {revision[:8]}...{sha[:8]}: {r.status_code} {self.host_text(r, 200)}") + return r.json().get("total_commits", 1) == 0 + + def changed_paths(self, head: str) -> set[str]: + r = self._call("compare", "GET", f"{self._repo()}/compare/{quote(self.default_branch)}...{head}") + if r.status_code != 200: + raise GitUnavailable(f"compare {head[:8]}: {r.status_code} {self.host_text(r, 200)}") + return {f["filename"] for c in r.json().get("commits") or [] for f in c.get("files") or []} + + def _blob_sha(self, path: str, ref: str) -> str: + r = self._call("read_file", "GET", f"{self._repo()}/contents/{quote(path)}", params={"ref": ref}) + return r.json()["sha"] + + 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"]) + + def find_pr(self, branch: str) -> PrRef | None: + r = self._call("find_pr", "GET", f"{self._repo()}/pulls", params={"state": "open", "limit": 50}) + for p in r.json(): + if p["head"]["ref"] == branch: + return self._pr_ref(p) + return None + + def pr_status(self, pr: PrRef, *, ci: bool = True) -> PrStatus: + r = self._call("pr_status", "GET", f"{self._repo()}/pulls/{pr.number}") + if r.status_code != 200: + raise GitUnavailable(f"PR {pr.number}: {r.status_code}") + p = r.json() + head = p["head"]["sha"] + checks: dict[str, CheckState] = {} + if ci: + s = self._call("pr_checks", "GET", f"{self._repo()}/commits/{head}/status", ok=(200, 404)) + if s.status_code == 200: + for st in s.json().get("statuses") or []: + checks[st["context"]] = {"success": "success", "pending": "pending"}.get(st["status"], "failure") + state = "merged" if p.get("merged") else ("open" if p["state"] == "open" else "closed") + return PrStatus(state=state, checks=checks, merge_sha=p.get("merge_commit_sha") if p.get("merged") else None, head_sha=head) + + def set_check(self, sha: str, context: str, state: CheckState, description: str, target_url: str | None = None) -> None: + body = {"context": context, "state": state, "description": description[:255]} + if target_url: + body["target_url"] = target_url + r = self._call("set_check", "POST", f"{self._repo()}/statuses/{sha}", json=body, ok=(201,)) + if r.status_code != 201: + raise GitUnavailable(f"status {context} on {sha[:8]}: {r.status_code} {self.host_text(r, 200)}") + + def merge(self, pr: PrRef, expected_head: str) -> str: + r = self._call("merge", "POST", f"{self._repo()}/pulls/{pr.number}/merge", + json={"Do": "merge", "head_commit_id": expected_head, "delete_branch_after_merge": False, + "MergeTitleField": f"Merge {pr.branch}"}, ok=(200,)) + if r.status_code != 200: + raise GitUnavailable(f"merge PR {pr.number}: {r.status_code} {self.host_text(r)}") + p = self._call("pr_status", "GET", f"{self._repo()}/pulls/{pr.number}").json() + return p.get("merge_commit_sha") or self.branch_head(self.default_branch) or "" + + def close(self, pr: PrRef, comment: str) -> None: + self._call("comment", "POST", f"{self._repo()}/issues/{pr.number}/comments", json={"body": comment}, ok=(201,)) + self._call("close", "PATCH", f"{self._repo()}/pulls/{pr.number}", json={"state": "closed"}, ok=(201, 200)) + + def log(self, n: int = 20) -> list[str]: + r = self._call("log", "GET", f"{self._repo()}/commits", params={"sha": self.default_branch, "limit": n}) + return self.commit_lines(r.json()) + + +def _b64(text: str) -> str: + return base64.b64encode(text.encode()).decode() + + +def _common_folder(files: Mapping[str, Any]) -> str: + paths = list(files) + if not paths: + return "" + parts = paths[0].split("/")[:-1] + for p in paths[1:]: + q = p.split("/")[:-1] + while parts and parts != q[:len(parts)]: + parts = parts[:-1] + return "/".join(parts) diff --git a/cmapi/src/cmapi/core/git/github.py b/cmapi/src/cmapi/core/git/github.py index 32be3f09..e5400340 100644 --- a/cmapi/src/cmapi/core/git/github.py +++ b/cmapi/src/cmapi/core/git/github.py @@ -1,368 +1,368 @@ -"""GitHub: the Git layer for every branch, commit and read in the worker (core/git/workspace.py), and REST for the PR (#286). - -The worker writes the request branch with git, pushes it with a lease, and deletes it with a lease. GitHub's REST API opens the -PR, reads its state, merges it pinned to a sha, comments and closes. - -Host CI is on by default (instance.git.hostChecks, #60): the config repository's GitHub Actions run kubeconform and Kyverno, and -pr_status reads their outcome as the workflow jobs ci/kubeconform and ci/kyverno of the PR head, through the Actions API: the -runs of one workflow file (instance.git.ciWorkflow, ci.yml unless set) for the pull_request event, never a job of that name -in another workflow or in a push run. Not the commit statuses: an Actions job reports a check run, never a commit status -(measured on cmapi-cluster-configs, 2026-12-01), and a status can be posted by any token that holds Commit statuses write, the -bot's included. Not the Checks API either: a fine-grained token has no Checks permission (BUG-69, #279), while "Actions" read -covers the runs and jobs endpoints (GitHub, "Permissions required for fine-grained personal access tokens", fetched -2026-12-01). The worker posts one commit status, cmapi/check, and never a ci/* context on GitHub. With hostChecks false it -reads no CI and posts nothing unless instance.git.postStatus is on (the arbitration of #286, row 11). - -The API process has no Git layer: the bot's SSH key is mounted in the worker alone (F2), so plan-time reads of a folder, the -branch head and the log go through the contents, branches and commits endpoints with the bot's token, as before #286 (the -arbitration, row 12: for PR-A). - -The bot account's token: Contents read and write (git fetch and push over HTTPS, and the reads above), Pull requests read and -write, Metadata read; with host CI on (the default), Actions read and Commit statuses read and write; Commit statuses read and -write alone with postStatus. Endpoints as documented by GitHub (2026-11, 2026-12): - - GET /repos/{o}/{r}/pulls?head=&state=open POST /repos/{o}/{r}/pulls GET /repos/{o}/{r}/pulls/{n} - PUT /repos/{o}/{r}/pulls/{n}/merge {sha} PATCH /repos/{o}/{r}/pulls/{n} POST /repos/{o}/{r}/issues/{n}/comments - GET /repos/{o}/{r}/actions/workflows/{file}/runs?head_sha=&event=pull_request - GET /repos/{o}/{r}/actions/runs/{id}/jobs?filter=latest GET /repos/{o}/{r}/actions/runs/{id} - POST /repos/{o}/{r}/statuses/{sha} GET /repos/{o}/{r}/pulls?state=open (list) - The API process, reads only: GET /repos/{o}/{r}/branches/{b}, /contents/{path}?ref= (the folder's tree sha), /commits?sha=, - /git/commits/{sha}, /git/trees/{sha}[?recursive=1] (the folder read_folder reads, and the one a delete lists, #616), - /git/blobs/{sha} (a manifest) -""" -from __future__ import annotations - -import base64 -from typing import Any, Iterable, Mapping -from urllib.parse import quote - -from cmapi.core.git.base import (BranchRequest, CheckState, GitUnavailable, HeadMoved, HostGitProvider, IncompleteList, MergeCheck, - NotMergeable, PlatformRefused, PushResult, manifest_text, refuse_lost_names) -from cmapi.core.ports import PrRef, PrStatus - - -def _worse(a: CheckState | None, b: CheckState) -> CheckState: - """One context reported twice reads as the worse report: a pass from one source never hides the other's failure.""" - return max(a or b, b, key=("success", "pending", "failure").index) - - -def _job_state(job: Mapping[str, Any]) -> CheckState: - """What one workflow job says about a required check (the rule of #87, e6300b8c, on the job that reports the check run). - Unfinished is pending, whatever else the job carries; a null conclusion has not reported an outcome yet, even when status - already says completed. Finished is a pass only on success. GitHub's branch protection also passes skipped and neutral, but - here ci/* is the evidence that the validation ran and passed, and a skipped job validated nothing, so they fail.""" - conclusion = job.get("conclusion") - if job.get("status") != "completed" or conclusion is None: - return "pending" - return "success" if conclusion == "success" else "failure" - - -class GitHubProvider(HostGitProvider): - name = "github" - posts_ci = False # ci/* come from the repository's Actions or from nobody; the worker posts cmapi/check alone (#60) - MAX_PAGES = 100 # 10,000 entries: past this a host is not answering a list, and a partial list must not read as complete - # "This endpoint will return up to 1,000 results for each search when using the following parameters: ... head_sha" (REST - # docs, Workflow runs, fetched 2026-12-01): that many runs on one commit may be a list GitHub cut. - MAX_RUNS_PER_SHA = 1000 - # The file name, under .github/workflows/, of the config repository's workflow whose jobs are the CI: "You can replace - # workflow_id with the workflow file name. For example, you could use main.yaml" (REST docs, List workflow runs for a - # workflow, fetched 2026-12-01). The template's name (examples/cluster-configs/.github/workflows/ci.yml). - CI_WORKFLOW = "ci.yml" - - def __init__(self, api_url: str, repository: str, token: str, *, workspace=None, host_checks: bool = True, - post_status: bool = False, ci_workflow: str | None = None, **kw: Any): - super().__init__(api_url, repository, token, **kw) - self.workspace = workspace - self.ci_workflow = ci_workflow or self.CI_WORKFLOW - self.external_ci = bool(host_checks) - self.post_statuses = bool(host_checks or post_status) - - def _headers(self, token: str) -> dict[str, str]: - return {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json", - "X-GitHub-Api-Version": "2022-11-28"} - - def _repo(self) -> str: - return f"/repos/{self.repository}" - - def _git(self): - if self.workspace is None: - raise GitUnavailable("this process has no Git layer: only the worker writes branches (core/context.py)") - return self.workspace - - # ---- the Git side: the Git layer in the worker; REST reads in the API process - def branch_head(self, branch: str) -> str | None: - if self.workspace is not None: - return self.workspace.branch_head(branch) - # One path parameter: GitHub asks for a "/" in it as %2F, and "#", "?" and "%" are escaped as data (#638). - r = self._call("branch_head", "GET", f"{self._repo()}/branches/{quote(branch, safe='')}", ok=(200, 404)) - return r.json()["commit"]["sha"] if r.status_code == 200 else None - - def read_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: - """The regular .yaml files directly in path at ref, read from the folder's tree as workspace._folder reads them (#625, - #632). Not from the Contents listing: version 2022-11-28 lists a submodule and a symlink to a file as "file", reads - that symlink as its target's text, lists at most 1,000 entries, and gives no content for a file past 1 MB. A tree - types each entry by its mode, and a blob read holds up to 100 MB. Contents still finds the folder in one request: its - object form carries the folder's tree sha (REST docs, Repository contents and Git blobs, fetched 2026-11-23).""" - if self.workspace is not None: - return self.workspace.read_folder(path, ref) - head = self._folder_head(ref) - directory = path.strip("/") - # A path is data in the URL: "#" or "?" would end it (RFC 3986, section 3.3), and "%41" would read as "A". - r = self._call("read_folder", "GET", f"{self._repo()}/contents/{quote(directory)}", params={"ref": head}, - headers={"Accept": "application/vnd.github.object+json"}, ok=(200, 404)) - if r.status_code == 404: - return {}, head - if r.status_code != 200: # 403 is a refusal or a rate limit (REST docs), never a missing folder - raise GitUnavailable(f"read folder {directory} at {head[:8]}: HTTP {r.status_code}") - found = r.json() - if found["type"] != "dir": # a file, symlink or submodule: git ls-tree of "/" lists nothing either - return {}, head - prefix = f"{directory}/" if directory else "" - manifests = {prefix + e["path"]: e["sha"] for e in self._tree(found["sha"]) - if e["type"] == "blob" and e["mode"] in ("100644", "100755") and e["path"].endswith(".yaml")} - refuse_lost_names(manifests) # a byte that is not UTF-8 came as U+FFFD: no plan can name the file (#626) - return manifest_text({p: self._blob_bytes(sha) for p, sha in manifests.items()}), head - - def _blob_bytes(self, sha: str) -> bytes: - """GET git/blobs/{sha}: "The content in the response will always be Base64 encoded", for blobs up to 100 MB (REST docs, - Git blobs, fetched 2026-11-23). manifest_text reads it as strict UTF-8, as the worker reads a manifest.""" - b = self._call("read_file", "GET", f"{self._repo()}/git/blobs/{sha}") - if b.status_code != 200: - raise GitUnavailable(f"read blob {sha[:8]}: HTTP {b.status_code}") - return base64.b64decode(b.json()["content"]) - - def _tree(self, oid: str, *, recursive: bool = False) -> list[dict[str, Any]]: - """GET git/trees/{oid}: the entries of one tree, or of every tree under it. "If truncated is true in the response then - the number of items in the tree array exceeded our maximum limit" (100,000 entries or 7 MB recursive; REST docs, - 2026-11): IncompleteList, never a short list read as complete.""" - r = self._call("list_folder", "GET", f"{self._repo()}/git/trees/{oid}", params={"recursive": "1"} if recursive else None) - if r.status_code != 200: - raise GitUnavailable(f"read tree {oid[:8]}: HTTP {r.status_code}") - body = r.json() - if body.get("truncated"): - raise IncompleteList(f"the tree {oid[:8]} is truncated: past GitHub's limit for a tree") - return body["tree"] - - def list_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: - """The Git Trees API, not Contents: a tree gives each entry's Git type and mode, and Contents stops at 1,000 entries. - From the commit's root tree (GET git/commits/{sha}), the walk to the folder reads one tree per part, then the folder's - tree with recursive=1.""" - if self.workspace is not None: - return self.workspace.list_folder(path, ref) - head = self._folder_head(ref) - c = self._call("list_folder", "GET", f"{self._repo()}/git/commits/{head}") - if c.status_code != 200: - raise GitUnavailable(f"read commit {head[:8]}: HTTP {c.status_code}") - directory = path.strip("/") - tree = c.json()["tree"]["sha"] - for part in filter(None, directory.split("/")): - entry = next((e for e in self._tree(tree) if e["path"] == part), None) - if entry is None or entry["type"] != "tree": - return {}, head - tree = entry["sha"] - prefix = f"{directory}/" if directory else "" - listed = {prefix + e["path"]: e["type"] for e in self._tree(tree, recursive=True) if e["type"] in ("blob", "commit")} - refuse_lost_names(listed) # a delete removes each path, so it must name each one (#626) - return listed, head - - def log(self, n: int = 20) -> list[str]: - if self.workspace is not None: - # The Git layer's token is in oplog's registry, not in this provider's forms (#424). - from cmapi.core.git.oplog import redact as redact_registered - - return [redact_registered(line) for line in self.workspace.log(n)] - r = self._call("log", "GET", f"{self._repo()}/commits", params={"sha": self.default_branch, "per_page": n}) - return self.commit_lines(r.json()) - - def contains(self, revision: str, sha: str) -> bool: - return self._git().contains(revision, sha) - - def changed_paths(self, head: str) -> set[str]: - return self._git().changed_paths(head) - - def push_request_branch(self, req: BranchRequest) -> PushResult: - return self._git().push_branch(req) - - def recreate_branch(self, req: BranchRequest, base: str, expected: str) -> str: - return self._git().recreate(req, base, expected) - - def merge_check(self, head: str, folder: str, prev: Mapping[str, str], files: Mapping[str, str | None], *, - whole_folder: bool = False) -> MergeCheck: - return self._git().merge_check(head, folder, prev, files, whole_folder=whole_folder) - - def delete_branch(self, branch: str, expected: str) -> bool: - return self._git().delete_branch(branch, expected) - - def list_branches(self, prefix: str) -> dict[str, str]: - return self._git().ls_remote(f"{prefix}*") - - def branch_time(self, sha: str) -> int: - return self._git().commit_time(sha) - - def request_of(self, sha: str) -> str | None: - ws = self._git() - with ws._lock: - ws._need(sha) - ids = ws.trailers(sha)["Cmapi-Request-Id"] - return ids[0] if len(ids) == 1 else None - - def cleanup(self, cluster_id: str, request_id: str) -> None: - if self.workspace is not None: - self.workspace.remove(cluster_id, request_id) - - def sweep(self, open_requests: Iterable[tuple[str, str]]): - return self.workspace.sweep(open_requests) if self.workspace is not None else None - - def dispose(self) -> None: - if self.workspace is not None: - self.workspace.dispose() - - # ---- 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"]) - - def find_pr(self, branch: str) -> PrRef | None: - owner = self.repository.split("/")[0] - r = self._call("pr_find", "GET", f"{self._repo()}/pulls", params={"state": "open", "head": f"{owner}:{branch}"}, ok=(200,)) - if r.status_code != 200: - text = self.host_text(r) - raise PlatformRefused(f"find the PR of {branch}: {r.status_code} {text[:200]}", r.status_code, text) - prs = r.json() - if len(prs) > 1: - raise PlatformRefused(f"{len(prs)} open PRs from {branch}: one is expected") - return self._pr_ref(prs[0]) if prs else None - - def open_pr(self, branch: str, head: str, title: str, body: str) -> PrRef: - existing = self.find_pr(branch) - if existing is None: - r = self._call("pr_open", "POST", f"{self._repo()}/pulls", - json={"head": branch, "base": self.default_branch, "title": title, "body": body}, ok=(201,)) - if r.status_code != 201: - existing = self.find_pr(branch) if r.status_code == 422 else None # "A pull request already exists" - if existing is None: - text = self.host_text(r) - raise PlatformRefused(f"open PR from {branch}: {r.status_code} {text}", r.status_code, text) - else: - existing = self._pr_ref(r.json()) - if existing.head_sha != head: - raise HeadMoved(f"PR #{existing.number} is on {existing.head_sha[:8]}, not on the pushed head {head[:8]}") - return existing - - def _pages(self, operation: str, path: str, key: str | None, **params: Any) -> list[Mapping[str, Any]]: - """Every entry of a paginated list, or GitUnavailable: an unread page could hold the answer.""" - return [entry for batch in self._page_batches(operation, path, key, **params) for entry in batch] - - def _page_batches(self, operation: str, path: str, key: str | None, **params: Any) -> Iterable[list[Mapping[str, Any]]]: - """The same list, one page at a time, for a caller that must know how many pages it read. The Link header says only - whether there is a next page. Its URL is not called, because this client sends the token with every request.""" - for page in range(1, self.MAX_PAGES + 1): - r = self._call(operation, "GET", path, params={**params, "per_page": 100, "page": page}, ok=(200,)) - if r.status_code != 200: - raise GitUnavailable(f"{operation}: GET {path} page {page}: {r.status_code} {self.host_text(r, 200)}") - body = r.json() - yield ((body.get(key) or []) if key else body) - if "next" not in r.links: - return - raise GitUnavailable(f"{operation}: GET {path} has more than {self.MAX_PAGES} pages") - - def list_open(self, prefix: str) -> list[PrRef]: - return [self._pr_ref(p) for p in self._pages("pr_list", f"{self._repo()}/pulls", None, state="open") - if p["head"]["ref"].startswith(prefix)] - - def pr_status(self, pr: PrRef) -> PrStatus: - r = self._call("pr_state", "GET", f"{self._repo()}/pulls/{pr.number}", ok=(200,)) - if r.status_code != 200: - text = self.host_text(r) - raise PlatformRefused(f"PR {pr.number}: {r.status_code} {text[:200]}", r.status_code, text) - p = r.json() - head = (p.get("head") or {}).get("sha") - if p["state"] != "open": # nothing reads a finished PR's checks, and a refused read must not hold back recording its end - merged = bool(p.get("merged")) - return PrStatus(state="merged" if merged else "closed", checks={}, merge_sha=p.get("merge_commit_sha") if merged else None, - head_sha=head) - # CI counts only for the head this request approved (pr.head_sha, the head the PR was opened on). A PR the host reports - # on another head, or on none, gives no CI: the worker fails its cmapi check on the head_sha returned here. - checks = self._actions_checks(pr) if self.external_ci and head and head == pr.head_sha else {} - return PrStatus(state="open", checks=checks, head_sha=head) - - def _actions_checks(self, pr: PrRef) -> dict[str, CheckState]: - """The jobs of the CI workflow's pull_request runs on the approved head, by job name: a job named ci/kyverno is the - check run ci/kyverno that branch protection requires (measured: the job and its check run share their name and id). - The workflow is asked for by its file name, so a job of that name in another workflow says nothing, and by its event, - so a push run does not either. A run is this PR's when it is on the PR's commit and branch in this repository: - head_sha, head_branch and head_repository.full_name are required fields of a run (github/rest-api-description, - workflow-run, fetched 2026-12-01), and a fork's PR on the same commit and branch name carries the fork as its - head_repository. Not pull_requests: it holds only "Pull requests that are open with a head_sha or head_branch that - matches the workflow run", "do not necessarily indicate pull requests that triggered the run" (the same schema), and - was empty on every pull_request run of cmapi-cluster-configs measured 2026-12-01, so requiring it could leave every - request waiting. Two jobs of one name read as the worse. filter=latest reads a re-run's newest attempt. Commit - statuses are not read: the worker's own token can post those.""" - head = pr.head_sha - workflow = f"{self._repo()}/actions/workflows/{quote(self.ci_workflow, safe='')}" - runs = self._pages("ci_runs", f"{workflow}/runs", "workflow_runs", head_sha=head, event="pull_request") - if len(runs) >= self.MAX_RUNS_PER_SHA: - raise IncompleteList(f"{len(runs)} workflow runs on {head[:8]}: GitHub lists at most {self.MAX_RUNS_PER_SHA}") - checks: dict[str, CheckState] = {} - for run in runs: - # The filters are GitHub's; a run of another commit or event says nothing about this PR. - if run.get("head_sha") != head or run.get("event") != "pull_request": - continue - # A fork's PR, or another branch at the same commit, is not this PR. GitHub's names do not tell case apart. - source = ((run.get("head_repository") or {}).get("full_name") or "").lower() - if run.get("head_branch") != pr.branch or source != self.repository.lower(): - continue - path = f"{self._repo()}/actions/runs/{run['id']}" - pages = 0 - for jobs in self._page_batches("ci_jobs", f"{path}/jobs", "jobs", filter="latest"): - pages += 1 - for job in jobs: - checks[job["name"]] = _worse(checks.get(job["name"]), _job_state(job)) - if pages > 1: - # Each page asked for the latest attempt on its own, so a re-run that started between two pages mixes two - # attempts. run_attempt is "1 for first attempt and higher if the workflow was re-run" (github/rest-api- - # description, workflow-run, fetched 2026-12-01). One page is one answer and needs no second read. - latest = self._call("ci_runs", "GET", path, ok=(200,)) - if latest.status_code != 200: - raise GitUnavailable(f"ci_runs: GET {path}: {latest.status_code} {self.host_text(latest, 200)}") - if latest.json().get("run_attempt") != run.get("run_attempt"): - return {} # nothing is known this poll: each context reads as pending, and the next poll reads again - return checks - - def set_check(self, sha: str, context: str, state: CheckState, description: str, target_url: str | None = None) -> None: - body: dict[str, Any] = {"context": context, "state": state, "description": description[:140]} - if target_url: - body["target_url"] = target_url - r = self._call("status_write", "POST", f"{self._repo()}/statuses/{sha}", json=body, ok=(201,)) - if r.status_code != 201: - raise GitUnavailable(f"status {context} on {sha[:8]}: {r.status_code} {self.host_text(r, 200)}") - - def merge(self, pr: PrRef, expected_head: str) -> str: - """PUT .../merge with sha: GitHub merges only if the head is that sha. 409 is HeadMoved, 405 NotMergeable. The branch is - not deleted here: git_cleanup deletes it with a lease.""" - r = self._call("merge", "PUT", f"{self._repo()}/pulls/{pr.number}/merge", ok=(200,), log_fields={"pinned_sha": expected_head, - "pr_number": pr.number, "merge_method": "merge"}, - json={"sha": expected_head, "merge_method": "merge", "commit_title": f"Merge {pr.branch}"}) - if r.status_code == 200: - return r.json()["sha"] - message = self.host_text(r) - if r.status_code == 409: - raise HeadMoved(f"merge PR {pr.number}: the head is not {expected_head[:8]}: {message}", 409, message) - if r.status_code == 405: - said = r.text[:300].lower() # the decision reads the host's own words; only the message is redacted - raise NotMergeable(f"merge PR {pr.number}: {message}", transient="pending" in said or "expected" in said) - raise PlatformRefused(f"merge PR {pr.number}: {r.status_code} {message}", r.status_code, message) - - def comment(self, pr: PrRef, text: str) -> None: - """At most once per text: a retry after a lost answer finds the comment the host kept, and posts nothing (#451). A read - before the write, not a host idempotency key: two writers at the same moment could still both post.""" - if any(c.get("body") == text for c in self._pages("pr_comments", f"{self._repo()}/issues/{pr.number}/comments", None)): - return - r = self._call("pr_comment", "POST", f"{self._repo()}/issues/{pr.number}/comments", json={"body": text}, ok=(201,)) - if r.status_code != 201: - raise PlatformRefused(f"comment on PR {pr.number}: {r.status_code}", r.status_code, self.host_text(r)) - - def close(self, pr: PrRef, comment: str) -> None: - self.comment(pr, comment) - r = self._call("pr_close", "PATCH", f"{self._repo()}/pulls/{pr.number}", json={"state": "closed"}, ok=(200,)) - if r.status_code != 200: - raise PlatformRefused(f"close PR {pr.number}: {r.status_code}", r.status_code, self.host_text(r)) +"""GitHub: the Git layer for every branch, commit and read in the worker (core/git/workspace.py), and REST for the PR (#286). + +The worker writes the request branch with git, pushes it with a lease, and deletes it with a lease. GitHub's REST API opens the +PR, reads its state, merges it pinned to a sha, comments and closes. + +Host CI is on by default (instance.git.hostChecks, #60): the config repository's GitHub Actions run kubeconform and Kyverno, and +pr_status reads their outcome as the workflow jobs ci/kubeconform and ci/kyverno of the PR head, through the Actions API: the +runs of one workflow file (instance.git.ciWorkflow, ci.yml unless set) for the pull_request event, never a job of that name +in another workflow or in a push run. Not the commit statuses: an Actions job reports a check run, never a commit status +(measured on cmapi-cluster-configs, 2026-12-01), and a status can be posted by any token that holds Commit statuses write, the +bot's included. Not the Checks API either: a fine-grained token has no Checks permission (BUG-69, #279), while "Actions" read +covers the runs and jobs endpoints (GitHub, "Permissions required for fine-grained personal access tokens", fetched +2026-12-01). The worker posts one commit status, cmapi/check, and never a ci/* context on GitHub. With hostChecks false it +reads no CI and posts nothing unless instance.git.postStatus is on (the arbitration of #286, row 11). + +The API process has no Git layer: the bot's SSH key is mounted in the worker alone (F2), so plan-time reads of a folder, the +branch head and the log go through the contents, branches and commits endpoints with the bot's token, as before #286 (the +arbitration, row 12: for PR-A). + +The bot account's token: Contents read and write (git fetch and push over HTTPS, and the reads above), Pull requests read and +write, Metadata read; with host CI on (the default), Actions read and Commit statuses read and write; Commit statuses read and +write alone with postStatus. Endpoints as documented by GitHub (2026-11, 2026-12): + + GET /repos/{o}/{r}/pulls?head=&state=open POST /repos/{o}/{r}/pulls GET /repos/{o}/{r}/pulls/{n} + PUT /repos/{o}/{r}/pulls/{n}/merge {sha} PATCH /repos/{o}/{r}/pulls/{n} POST /repos/{o}/{r}/issues/{n}/comments + GET /repos/{o}/{r}/actions/workflows/{file}/runs?head_sha=&event=pull_request + GET /repos/{o}/{r}/actions/runs/{id}/jobs?filter=latest GET /repos/{o}/{r}/actions/runs/{id} + POST /repos/{o}/{r}/statuses/{sha} GET /repos/{o}/{r}/pulls?state=open (list) + The API process, reads only: GET /repos/{o}/{r}/branches/{b}, /contents/{path}?ref= (the folder's tree sha), /commits?sha=, + /git/commits/{sha}, /git/trees/{sha}[?recursive=1] (the folder read_folder reads, and the one a delete lists, #616), + /git/blobs/{sha} (a manifest) +""" +from __future__ import annotations + +import base64 +from typing import Any, Iterable, Mapping +from urllib.parse import quote + +from cmapi.core.git.base import (BranchRequest, CheckState, GitUnavailable, HeadMoved, HostGitProvider, IncompleteList, MergeCheck, + NotMergeable, PlatformRefused, PushResult, manifest_text, refuse_lost_names) +from cmapi.core.ports import PrRef, PrStatus + + +def _worse(a: CheckState | None, b: CheckState) -> CheckState: + """One context reported twice reads as the worse report: a pass from one source never hides the other's failure.""" + return max(a or b, b, key=("success", "pending", "failure").index) + + +def _job_state(job: Mapping[str, Any]) -> CheckState: + """What one workflow job says about a required check (the rule of #87, e6300b8c, on the job that reports the check run). + Unfinished is pending, whatever else the job carries; a null conclusion has not reported an outcome yet, even when status + already says completed. Finished is a pass only on success. GitHub's branch protection also passes skipped and neutral, but + here ci/* is the evidence that the validation ran and passed, and a skipped job validated nothing, so they fail.""" + conclusion = job.get("conclusion") + if job.get("status") != "completed" or conclusion is None: + return "pending" + return "success" if conclusion == "success" else "failure" + + +class GitHubProvider(HostGitProvider): + name = "github" + posts_ci = False # ci/* come from the repository's Actions or from nobody; the worker posts cmapi/check alone (#60) + MAX_PAGES = 100 # 10,000 entries: past this a host is not answering a list, and a partial list must not read as complete + # "This endpoint will return up to 1,000 results for each search when using the following parameters: ... head_sha" (REST + # docs, Workflow runs, fetched 2026-12-01): that many runs on one commit may be a list GitHub cut. + MAX_RUNS_PER_SHA = 1000 + # The file name, under .github/workflows/, of the config repository's workflow whose jobs are the CI: "You can replace + # workflow_id with the workflow file name. For example, you could use main.yaml" (REST docs, List workflow runs for a + # workflow, fetched 2026-12-01). The template's name (examples/cluster-configs/.github/workflows/ci.yml). + CI_WORKFLOW = "ci.yml" + + def __init__(self, api_url: str, repository: str, token: str, *, workspace=None, host_checks: bool = True, + post_status: bool = False, ci_workflow: str | None = None, **kw: Any): + super().__init__(api_url, repository, token, **kw) + self.workspace = workspace + self.ci_workflow = ci_workflow or self.CI_WORKFLOW + self.external_ci = bool(host_checks) + self.post_statuses = bool(host_checks or post_status) + + def _headers(self, token: str) -> dict[str, str]: + return {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28"} + + def _repo(self) -> str: + return f"/repos/{self.repository}" + + def _git(self): + if self.workspace is None: + raise GitUnavailable("this process has no Git layer: only the worker writes branches (core/context.py)") + return self.workspace + + # ---- the Git side: the Git layer in the worker; REST reads in the API process + def branch_head(self, branch: str) -> str | None: + if self.workspace is not None: + return self.workspace.branch_head(branch) + # One path parameter: GitHub asks for a "/" in it as %2F, and "#", "?" and "%" are escaped as data (#638). + r = self._call("branch_head", "GET", f"{self._repo()}/branches/{quote(branch, safe='')}", ok=(200, 404)) + return r.json()["commit"]["sha"] if r.status_code == 200 else None + + def read_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: + """The regular .yaml files directly in path at ref, read from the folder's tree as workspace._folder reads them (#625, + #632). Not from the Contents listing: version 2022-11-28 lists a submodule and a symlink to a file as "file", reads + that symlink as its target's text, lists at most 1,000 entries, and gives no content for a file past 1 MB. A tree + types each entry by its mode, and a blob read holds up to 100 MB. Contents still finds the folder in one request: its + object form carries the folder's tree sha (REST docs, Repository contents and Git blobs, fetched 2026-11-23).""" + if self.workspace is not None: + return self.workspace.read_folder(path, ref) + head = self._folder_head(ref) + directory = path.strip("/") + # A path is data in the URL: "#" or "?" would end it (RFC 3986, section 3.3), and "%41" would read as "A". + r = self._call("read_folder", "GET", f"{self._repo()}/contents/{quote(directory)}", params={"ref": head}, + headers={"Accept": "application/vnd.github.object+json"}, ok=(200, 404)) + if r.status_code == 404: + return {}, head + if r.status_code != 200: # 403 is a refusal or a rate limit (REST docs), never a missing folder + raise GitUnavailable(f"read folder {directory} at {head[:8]}: HTTP {r.status_code}") + found = r.json() + if found["type"] != "dir": # a file, symlink or submodule: git ls-tree of "/" lists nothing either + return {}, head + prefix = f"{directory}/" if directory else "" + manifests = {prefix + e["path"]: e["sha"] for e in self._tree(found["sha"]) + if e["type"] == "blob" and e["mode"] in ("100644", "100755") and e["path"].endswith(".yaml")} + refuse_lost_names(manifests) # a byte that is not UTF-8 came as U+FFFD: no plan can name the file (#626) + return manifest_text({p: self._blob_bytes(sha) for p, sha in manifests.items()}), head + + def _blob_bytes(self, sha: str) -> bytes: + """GET git/blobs/{sha}: "The content in the response will always be Base64 encoded", for blobs up to 100 MB (REST docs, + Git blobs, fetched 2026-11-23). manifest_text reads it as strict UTF-8, as the worker reads a manifest.""" + b = self._call("read_file", "GET", f"{self._repo()}/git/blobs/{sha}") + if b.status_code != 200: + raise GitUnavailable(f"read blob {sha[:8]}: HTTP {b.status_code}") + return base64.b64decode(b.json()["content"]) + + def _tree(self, oid: str, *, recursive: bool = False) -> list[dict[str, Any]]: + """GET git/trees/{oid}: the entries of one tree, or of every tree under it. "If truncated is true in the response then + the number of items in the tree array exceeded our maximum limit" (100,000 entries or 7 MB recursive; REST docs, + 2026-11): IncompleteList, never a short list read as complete.""" + r = self._call("list_folder", "GET", f"{self._repo()}/git/trees/{oid}", params={"recursive": "1"} if recursive else None) + if r.status_code != 200: + raise GitUnavailable(f"read tree {oid[:8]}: HTTP {r.status_code}") + body = r.json() + if body.get("truncated"): + raise IncompleteList(f"the tree {oid[:8]} is truncated: past GitHub's limit for a tree") + return body["tree"] + + def list_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: + """The Git Trees API, not Contents: a tree gives each entry's Git type and mode, and Contents stops at 1,000 entries. + From the commit's root tree (GET git/commits/{sha}), the walk to the folder reads one tree per part, then the folder's + tree with recursive=1.""" + if self.workspace is not None: + return self.workspace.list_folder(path, ref) + head = self._folder_head(ref) + c = self._call("list_folder", "GET", f"{self._repo()}/git/commits/{head}") + if c.status_code != 200: + raise GitUnavailable(f"read commit {head[:8]}: HTTP {c.status_code}") + directory = path.strip("/") + tree = c.json()["tree"]["sha"] + for part in filter(None, directory.split("/")): + entry = next((e for e in self._tree(tree) if e["path"] == part), None) + if entry is None or entry["type"] != "tree": + return {}, head + tree = entry["sha"] + prefix = f"{directory}/" if directory else "" + listed = {prefix + e["path"]: e["type"] for e in self._tree(tree, recursive=True) if e["type"] in ("blob", "commit")} + refuse_lost_names(listed) # a delete removes each path, so it must name each one (#626) + return listed, head + + def log(self, n: int = 20) -> list[str]: + if self.workspace is not None: + # The Git layer's token is in oplog's registry, not in this provider's forms (#424). + from cmapi.core.git.oplog import redact as redact_registered + + return [redact_registered(line) for line in self.workspace.log(n)] + r = self._call("log", "GET", f"{self._repo()}/commits", params={"sha": self.default_branch, "per_page": n}) + return self.commit_lines(r.json()) + + def contains(self, revision: str, sha: str) -> bool: + return self._git().contains(revision, sha) + + def changed_paths(self, head: str) -> set[str]: + return self._git().changed_paths(head) + + def push_request_branch(self, req: BranchRequest) -> PushResult: + return self._git().push_branch(req) + + def recreate_branch(self, req: BranchRequest, base: str, expected: str) -> str: + return self._git().recreate(req, base, expected) + + def merge_check(self, head: str, folder: str, prev: Mapping[str, str], files: Mapping[str, str | None], *, + whole_folder: bool = False) -> MergeCheck: + return self._git().merge_check(head, folder, prev, files, whole_folder=whole_folder) + + def delete_branch(self, branch: str, expected: str) -> bool: + return self._git().delete_branch(branch, expected) + + def list_branches(self, prefix: str) -> dict[str, str]: + return self._git().ls_remote(f"{prefix}*") + + def branch_time(self, sha: str) -> int: + return self._git().commit_time(sha) + + def request_of(self, sha: str) -> str | None: + ws = self._git() + with ws._lock: + ws._need(sha) + ids = ws.trailers(sha)["Cmapi-Request-Id"] + return ids[0] if len(ids) == 1 else None + + def cleanup(self, cluster_id: str, request_id: str) -> None: + if self.workspace is not None: + self.workspace.remove(cluster_id, request_id) + + def sweep(self, open_requests: Iterable[tuple[str, str]]): + return self.workspace.sweep(open_requests) if self.workspace is not None else None + + def dispose(self) -> None: + if self.workspace is not None: + self.workspace.dispose() + + # ---- 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"]) + + def find_pr(self, branch: str) -> PrRef | None: + owner = self.repository.split("/")[0] + r = self._call("pr_find", "GET", f"{self._repo()}/pulls", params={"state": "open", "head": f"{owner}:{branch}"}, ok=(200,)) + if r.status_code != 200: + text = self.host_text(r) + raise PlatformRefused(f"find the PR of {branch}: {r.status_code} {text[:200]}", r.status_code, text) + prs = r.json() + if len(prs) > 1: + raise PlatformRefused(f"{len(prs)} open PRs from {branch}: one is expected") + return self._pr_ref(prs[0]) if prs else None + + def open_pr(self, branch: str, head: str, title: str, body: str) -> PrRef: + existing = self.find_pr(branch) + if existing is None: + r = self._call("pr_open", "POST", f"{self._repo()}/pulls", + json={"head": branch, "base": self.default_branch, "title": title, "body": body}, ok=(201,)) + if r.status_code != 201: + existing = self.find_pr(branch) if r.status_code == 422 else None # "A pull request already exists" + if existing is None: + text = self.host_text(r) + raise PlatformRefused(f"open PR from {branch}: {r.status_code} {text}", r.status_code, text) + else: + existing = self._pr_ref(r.json()) + if existing.head_sha != head: + raise HeadMoved(f"PR #{existing.number} is on {existing.head_sha[:8]}, not on the pushed head {head[:8]}") + return existing + + def _pages(self, operation: str, path: str, key: str | None, **params: Any) -> list[Mapping[str, Any]]: + """Every entry of a paginated list, or GitUnavailable: an unread page could hold the answer.""" + return [entry for batch in self._page_batches(operation, path, key, **params) for entry in batch] + + def _page_batches(self, operation: str, path: str, key: str | None, **params: Any) -> Iterable[list[Mapping[str, Any]]]: + """The same list, one page at a time, for a caller that must know how many pages it read. The Link header says only + whether there is a next page. Its URL is not called, because this client sends the token with every request.""" + for page in range(1, self.MAX_PAGES + 1): + r = self._call(operation, "GET", path, params={**params, "per_page": 100, "page": page}, ok=(200,)) + if r.status_code != 200: + raise GitUnavailable(f"{operation}: GET {path} page {page}: {r.status_code} {self.host_text(r, 200)}") + body = r.json() + yield ((body.get(key) or []) if key else body) + if "next" not in r.links: + return + raise GitUnavailable(f"{operation}: GET {path} has more than {self.MAX_PAGES} pages") + + def list_open(self, prefix: str) -> list[PrRef]: + return [self._pr_ref(p) for p in self._pages("pr_list", f"{self._repo()}/pulls", None, state="open") + if p["head"]["ref"].startswith(prefix)] + + def pr_status(self, pr: PrRef, *, ci: bool = True) -> PrStatus: + r = self._call("pr_state", "GET", f"{self._repo()}/pulls/{pr.number}", ok=(200,)) + if r.status_code != 200: + text = self.host_text(r) + raise PlatformRefused(f"PR {pr.number}: {r.status_code} {text[:200]}", r.status_code, text) + p = r.json() + head = (p.get("head") or {}).get("sha") + if p["state"] != "open": # nothing reads a finished PR's checks, and a refused read must not hold back recording its end + merged = bool(p.get("merged")) + return PrStatus(state="merged" if merged else "closed", checks={}, merge_sha=p.get("merge_commit_sha") if merged else None, + head_sha=head) + # CI counts only for the head this request approved (pr.head_sha, the head the PR was opened on). A PR the host reports + # on another head, or on none, gives no CI: the worker fails its cmapi check on the head_sha returned here. + checks = self._actions_checks(pr) if ci and self.external_ci and head and head == pr.head_sha else {} + return PrStatus(state="open", checks=checks, head_sha=head) + + def _actions_checks(self, pr: PrRef) -> dict[str, CheckState]: + """The jobs of the CI workflow's pull_request runs on the approved head, by job name: a job named ci/kyverno is the + check run ci/kyverno that branch protection requires (measured: the job and its check run share their name and id). + The workflow is asked for by its file name, so a job of that name in another workflow says nothing, and by its event, + so a push run does not either. A run is this PR's when it is on the PR's commit and branch in this repository: + head_sha, head_branch and head_repository.full_name are required fields of a run (github/rest-api-description, + workflow-run, fetched 2026-12-01), and a fork's PR on the same commit and branch name carries the fork as its + head_repository. Not pull_requests: it holds only "Pull requests that are open with a head_sha or head_branch that + matches the workflow run", "do not necessarily indicate pull requests that triggered the run" (the same schema), and + was empty on every pull_request run of cmapi-cluster-configs measured 2026-12-01, so requiring it could leave every + request waiting. Two jobs of one name read as the worse. filter=latest reads a re-run's newest attempt. Commit + statuses are not read: the worker's own token can post those.""" + head = pr.head_sha + workflow = f"{self._repo()}/actions/workflows/{quote(self.ci_workflow, safe='')}" + runs = self._pages("ci_runs", f"{workflow}/runs", "workflow_runs", head_sha=head, event="pull_request") + if len(runs) >= self.MAX_RUNS_PER_SHA: + raise IncompleteList(f"{len(runs)} workflow runs on {head[:8]}: GitHub lists at most {self.MAX_RUNS_PER_SHA}") + checks: dict[str, CheckState] = {} + for run in runs: + # The filters are GitHub's; a run of another commit or event says nothing about this PR. + if run.get("head_sha") != head or run.get("event") != "pull_request": + continue + # A fork's PR, or another branch at the same commit, is not this PR. GitHub's names do not tell case apart. + source = ((run.get("head_repository") or {}).get("full_name") or "").lower() + if run.get("head_branch") != pr.branch or source != self.repository.lower(): + continue + path = f"{self._repo()}/actions/runs/{run['id']}" + pages = 0 + for jobs in self._page_batches("ci_jobs", f"{path}/jobs", "jobs", filter="latest"): + pages += 1 + for job in jobs: + checks[job["name"]] = _worse(checks.get(job["name"]), _job_state(job)) + if pages > 1: + # Each page asked for the latest attempt on its own, so a re-run that started between two pages mixes two + # attempts. run_attempt is "1 for first attempt and higher if the workflow was re-run" (github/rest-api- + # description, workflow-run, fetched 2026-12-01). One page is one answer and needs no second read. + latest = self._call("ci_runs", "GET", path, ok=(200,)) + if latest.status_code != 200: + raise GitUnavailable(f"ci_runs: GET {path}: {latest.status_code} {self.host_text(latest, 200)}") + if latest.json().get("run_attempt") != run.get("run_attempt"): + return {} # nothing is known this poll: each context reads as pending, and the next poll reads again + return checks + + def set_check(self, sha: str, context: str, state: CheckState, description: str, target_url: str | None = None) -> None: + body: dict[str, Any] = {"context": context, "state": state, "description": description[:140]} + if target_url: + body["target_url"] = target_url + r = self._call("status_write", "POST", f"{self._repo()}/statuses/{sha}", json=body, ok=(201,)) + if r.status_code != 201: + raise GitUnavailable(f"status {context} on {sha[:8]}: {r.status_code} {self.host_text(r, 200)}") + + def merge(self, pr: PrRef, expected_head: str) -> str: + """PUT .../merge with sha: GitHub merges only if the head is that sha. 409 is HeadMoved, 405 NotMergeable. The branch is + not deleted here: git_cleanup deletes it with a lease.""" + r = self._call("merge", "PUT", f"{self._repo()}/pulls/{pr.number}/merge", ok=(200,), log_fields={"pinned_sha": expected_head, + "pr_number": pr.number, "merge_method": "merge"}, + json={"sha": expected_head, "merge_method": "merge", "commit_title": f"Merge {pr.branch}"}) + if r.status_code == 200: + return r.json()["sha"] + message = self.host_text(r) + if r.status_code == 409: + raise HeadMoved(f"merge PR {pr.number}: the head is not {expected_head[:8]}: {message}", 409, message) + if r.status_code == 405: + said = r.text[:300].lower() # the decision reads the host's own words; only the message is redacted + raise NotMergeable(f"merge PR {pr.number}: {message}", transient="pending" in said or "expected" in said) + raise PlatformRefused(f"merge PR {pr.number}: {r.status_code} {message}", r.status_code, message) + + def comment(self, pr: PrRef, text: str) -> None: + """At most once per text: a retry after a lost answer finds the comment the host kept, and posts nothing (#451). A read + before the write, not a host idempotency key: two writers at the same moment could still both post.""" + if any(c.get("body") == text for c in self._pages("pr_comments", f"{self._repo()}/issues/{pr.number}/comments", None)): + return + r = self._call("pr_comment", "POST", f"{self._repo()}/issues/{pr.number}/comments", json={"body": text}, ok=(201,)) + if r.status_code != 201: + raise PlatformRefused(f"comment on PR {pr.number}: {r.status_code}", r.status_code, self.host_text(r)) + + def close(self, pr: PrRef, comment: str) -> None: + self.comment(pr, comment) + r = self._call("pr_close", "PATCH", f"{self._repo()}/pulls/{pr.number}", json={"state": "closed"}, ok=(200,)) + if r.status_code != 200: + raise PlatformRefused(f"close PR {pr.number}: {r.status_code}", r.status_code, self.host_text(r)) diff --git a/cmapi/src/cmapi/core/ports.py b/cmapi/src/cmapi/core/ports.py index 1e99cdf3..f32d9e49 100644 --- a/cmapi/src/cmapi/core/ports.py +++ b/cmapi/src/cmapi/core/ports.py @@ -1,231 +1,231 @@ -"""Every extension point and outside dependency of cmapi-core, as typed Protocols. - -Core and plugins depend only on these; adapters implement them and register under -cmapi.adapters. (docs/01, Modularity). An adapter is chosen per instance in instance.yaml, -integrations.yaml, capacity.yaml or plugins.yaml. Each Protocol below says which module owns the -default adapter. The pure-logic modules (tiers, metadata, approvals, lifecycle, expiration, -listquery, render, identity checks) need none of these and are tested without them. -""" -from __future__ import annotations - -from dataclasses import dataclass, field -from datetime import datetime, timedelta -from typing import Any, Literal, Mapping, Protocol, runtime_checkable - -from cmapi.core.identity.claims import Identity -from cmapi.core.identity.directory import DirectoryProvider # noqa: F401 (re-exported) - -# --------------------------------------------------------------------------- shared value types - - -@dataclass(frozen=True) -class Finding: - source: Literal["kyverno", "kubeconform", "cmapi"] - rule: str # the policy's name for Kyverno, the check's name for cmapi, `schema` - path: str - message: str - severity: Literal["error", "warning"] = "error" - # Kyverno's own rule name from its report (#302): `validation` for a ValidatingPolicy, the rule of a hand-written - # ClusterPolicy. None for every other source. - kyverno_rule: str | None = None - - def view(self) -> dict[str, Any]: - """The JSON form of a finding in a plan, a 422 and a stored refusal: camelCase, as the rest of the API.""" - return {"source": self.source, "rule": self.rule, "path": self.path, "message": self.message, - "severity": self.severity, "kyvernoRule": self.kyverno_rule} - - -@dataclass(frozen=True) -class CapacityResult: - status: Literal["fits", "warn", "exceeded", "unknown"] - fresh: bool - binding_resource: str | None = None # cpu or memory, whichever binds - detail: Mapping[str, Any] = field(default_factory=dict) - - -@dataclass(frozen=True) -class PrRef: - number: int - url: str - branch: str - head_sha: str - - -@dataclass(frozen=True) -class PrStatus: - state: Literal["open", "merged", "closed"] - checks: Mapping[str, Literal["pending", "success", "failure"]] - merge_sha: str | None = None - head_sha: str | None = None # the PR's head as the host reports it (#286: merge pins it) - - -@dataclass(frozen=True) -class AppStatus: - cluster_id: str - revision: str - sync: Literal["Synced", "OutOfSync", "Unknown"] - health: str - phase: str | None - revisions: frozenset[str] = frozenset() # status.sync.revisions (multi-source) or {status.sync.revision} - resources: tuple[tuple[str, str, str, str], ...] = () # (kind, namespace, name, status) from status.resources - prune_pending: frozenset[str] = frozenset() # namespaces waiting on Prune=confirm - - -@dataclass(frozen=True) -class PolicyResult: - cluster_id: str - policy: str - rule: str - result: Literal["pass", "fail", "warn", "error", "skip"] - resource: str - namespace: str | None - message: str - - -@dataclass(frozen=True) -class CloudEvent: - id: str - type: str # cmapi.request.synced, cmapi.namespace.expiring, ... - subject: str # / - time: datetime - data: Mapping[str, Any] - - -# --------------------------------------------------------------------------- extension points - - -@runtime_checkable -class Authenticator(Protocol): - """core/auth.py (OIDC against the Keycloak realm, offline JWKS).""" - def authenticate(self, bearer: str) -> Identity: ... - - -@runtime_checkable -class Renderer(Protocol): - """core/render/manifests.py (raw manifests); project_meta.py and Kustomize are alternatives.""" - def render(self, spec: Any, previous: Mapping[str, str] | None = None) -> dict[str, str | None]: ... - def delete(self, cluster_id: str, namespace: str, previous: Mapping[str, str]) -> dict[str, None]: ... - - -@runtime_checkable -class GitProvider(Protocol): - """core/git/ (#286): a Git layer for branches, commits and reads (workspace.py) and a thin platform adapter per host for the - PR (github.py; gitea.py is REST alone). The full contract is core/git/base.py HostGitProvider. Every change is a request - branch and a PR; nothing pushes to the default branch.""" - external_ci: bool - post_statuses: bool - posts_ci: bool - def read_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: ... # files, commit sha - def list_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: ... # {path: blob|commit}, sha - def push_request_branch(self, req: Any) -> Any: ... # BranchRequest -> PushResult - def open_pr(self, branch: str, head: str, title: str, body: str) -> PrRef: ... - def pr_status(self, pr: PrRef) -> PrStatus: ... - def merge_check(self, head: str, folder: str, prev: Mapping[str, str], files: Mapping[str, str | None], *, - whole_folder: bool = False) -> Any: ... - def merge(self, pr: PrRef, expected_head: str) -> str: ... # merge sha, pinned to expected_head - def comment(self, pr: PrRef, text: str) -> None: ... - def close(self, pr: PrRef, comment: str) -> None: ... - def delete_branch(self, branch: str, expected: str) -> bool: ... - - -@runtime_checkable -class Validator(Protocol): - """core/validate/: the Kyverno CLI bundle plus kubeconform on the rendered files.""" - def validate(self, files: Mapping[str, str], cluster_id: str, environment: str, - previous: Mapping[str, str | None] | None = None, held: list[Finding] | None = None) -> list[Finding]: ... - - -@runtime_checkable -class CapacityBackend(Protocol): - """remote (cmapi-capacity over HTTP, default) or embedded (the worker runs the jobs). - - The holds of open requests live in the cmapi schema, so `reserve_check`, `reserve`, `confirm` and `release` take the - caller's transaction: "Placement, the capacity check inside every plan [...] stay in the API, because they write requests - or reservations" (docs/01). The hold is core/capacity_backend.py's CapacityHold.""" - def check(self, cluster_id: str, environment: str, cpu_delta: float, memory_delta: float, *, session: Any = None, - exclude: str | None = None, exclude_placement: str | None = None, - namespace: str | None = None) -> CapacityResult: ... - def placement(self, placement_id: str) -> Any: ... - def reserve_check(self, session: Any, cluster_id: str, environment: str, hold: Any, *, - placement_id: str | None = None) -> CapacityResult: ... - def reserve(self, session: Any, request_id: str, cluster_id: str, hold: Any, term: timedelta, *, - placement_id: str | None = None) -> None: ... - def confirm(self, session: Any, request_id: str, cluster_id: str, environment: str) -> CapacityResult | None: ... - def release(self, session: Any, request_id: str, why: str) -> int: ... - - -@runtime_checkable -class MetricsSource(Protocol): - """Each cluster's Thanos Querier (default) or an ACM Observability hub. Used by cmapi-capacity only.""" - def query(self, cluster_id: str, promql: str, at: datetime | None = None) -> list[dict[str, Any]]: ... - - -@runtime_checkable -class SyncSignal(Protocol): - """poll (default) or notify (Argo CD Notifications webhook, then confirmed by a read).""" - def status(self, cluster_id: str) -> AppStatus: ... - - -@runtime_checkable -class OperationsEngine(Protocol): - """builtin (worker steps, default), Argo Workflows or Tekton: docs/02's OperationsEngine, synchronous as the rest of cmapi - (core/operations.py). `available` says whether it can take a run, and why not; `submit` starts the run whose operations row - the caller wrote, in the caller's transaction, and returns the run's name on the engine; `cancel` stops it. The built-in - engine keeps its state in that row and its operation_steps, so it needs no `watch`; an Argo or Tekton adapter adds it.""" - name: str - def available(self) -> tuple[bool, str]: ... - def submit(self, session: Any, operation: Any, template: Any) -> str: ... - def cancel(self, session: Any, operation: Any) -> None: ... - - -@runtime_checkable -class EventPublisher(Protocol): - """none (default), signed webhook, Kafka. Fed from the outbox table, so delivery is at least once.""" - def publish(self, event: CloudEvent) -> None: ... - - -@runtime_checkable -class Notifier(Protocol): - """email (default), Slack, Teams. Expiry notices and approval prompts go to the team DL.""" - def send(self, to: list[str], subject: str, body: str, links: Mapping[str, str] | None = None) -> None: ... - - -@runtime_checkable -class ApprovalChannel(Protocol): - """portal (default), email link, argo-events, servicenow, slack/teams. A channel notifies or - relays; the decision is always POST /requests/{id}:approve with an eligible person's identity.""" - name: str - def notify_pending(self, request: Mapping[str, Any], groups: list[str]) -> None: ... - def notify_decision(self, request: Mapping[str, Any], decision: str) -> None: ... - - -# --------------------------------------------------------------------------- readers - - -@runtime_checkable -class KubeReader(Protocol): - """core/clients/kube.py: watch cache per cluster through the read-only cmapi-reader.""" - def namespaces(self, cluster_id: str) -> list[Mapping[str, Any]]: ... - def get(self, cluster_id: str, kind: str, namespace: str | None, name: str) -> Mapping[str, Any] | None: ... - def quota(self, cluster_id: str, namespace: str) -> Mapping[str, Any] | None: ... - - -@runtime_checkable -class PolicyReportReader(Protocol): - """plugins/policies: PolicyReport and ClusterPolicyReport (wgpolicyk8s.io), CEL policy kinds.""" - def results(self, cluster_id: str) -> list[PolicyResult]: ... - def bundle_tag(self, cluster_id: str) -> str | None: ... - - -@runtime_checkable -class AuditLog(Protocol): - """core/audit.py: audit_events rows; never token values.""" - def record(self, actor: Identity, action: str, target: str, detail: Mapping[str, Any]) -> None: ... - - -@runtime_checkable -class Plugin(Protocol): - """Every plugin: name, a router, models, a planner and its read RBAC (docs/01, Adding an offering).""" - name: str - def routes(self) -> Any: ... - def plan(self, request: Mapping[str, Any], caller: Identity) -> Mapping[str, Any]: ... +"""Every extension point and outside dependency of cmapi-core, as typed Protocols. + +Core and plugins depend only on these; adapters implement them and register under +cmapi.adapters. (docs/01, Modularity). An adapter is chosen per instance in instance.yaml, +integrations.yaml, capacity.yaml or plugins.yaml. Each Protocol below says which module owns the +default adapter. The pure-logic modules (tiers, metadata, approvals, lifecycle, expiration, +listquery, render, identity checks) need none of these and are tested without them. +""" +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime, timedelta +from typing import Any, Literal, Mapping, Protocol, runtime_checkable + +from cmapi.core.identity.claims import Identity +from cmapi.core.identity.directory import DirectoryProvider # noqa: F401 (re-exported) + +# --------------------------------------------------------------------------- shared value types + + +@dataclass(frozen=True) +class Finding: + source: Literal["kyverno", "kubeconform", "cmapi"] + rule: str # the policy's name for Kyverno, the check's name for cmapi, `schema` + path: str + message: str + severity: Literal["error", "warning"] = "error" + # Kyverno's own rule name from its report (#302): `validation` for a ValidatingPolicy, the rule of a hand-written + # ClusterPolicy. None for every other source. + kyverno_rule: str | None = None + + def view(self) -> dict[str, Any]: + """The JSON form of a finding in a plan, a 422 and a stored refusal: camelCase, as the rest of the API.""" + return {"source": self.source, "rule": self.rule, "path": self.path, "message": self.message, + "severity": self.severity, "kyvernoRule": self.kyverno_rule} + + +@dataclass(frozen=True) +class CapacityResult: + status: Literal["fits", "warn", "exceeded", "unknown"] + fresh: bool + binding_resource: str | None = None # cpu or memory, whichever binds + detail: Mapping[str, Any] = field(default_factory=dict) + + +@dataclass(frozen=True) +class PrRef: + number: int + url: str + branch: str + head_sha: str + + +@dataclass(frozen=True) +class PrStatus: + state: Literal["open", "merged", "closed"] + checks: Mapping[str, Literal["pending", "success", "failure"]] + merge_sha: str | None = None + head_sha: str | None = None # the PR's head as the host reports it (#286: merge pins it) + + +@dataclass(frozen=True) +class AppStatus: + cluster_id: str + revision: str + sync: Literal["Synced", "OutOfSync", "Unknown"] + health: str + phase: str | None + revisions: frozenset[str] = frozenset() # status.sync.revisions (multi-source) or {status.sync.revision} + resources: tuple[tuple[str, str, str, str], ...] = () # (kind, namespace, name, status) from status.resources + prune_pending: frozenset[str] = frozenset() # namespaces waiting on Prune=confirm + + +@dataclass(frozen=True) +class PolicyResult: + cluster_id: str + policy: str + rule: str + result: Literal["pass", "fail", "warn", "error", "skip"] + resource: str + namespace: str | None + message: str + + +@dataclass(frozen=True) +class CloudEvent: + id: str + type: str # cmapi.request.synced, cmapi.namespace.expiring, ... + subject: str # / + time: datetime + data: Mapping[str, Any] + + +# --------------------------------------------------------------------------- extension points + + +@runtime_checkable +class Authenticator(Protocol): + """core/auth.py (OIDC against the Keycloak realm, offline JWKS).""" + def authenticate(self, bearer: str) -> Identity: ... + + +@runtime_checkable +class Renderer(Protocol): + """core/render/manifests.py (raw manifests); project_meta.py and Kustomize are alternatives.""" + def render(self, spec: Any, previous: Mapping[str, str] | None = None) -> dict[str, str | None]: ... + def delete(self, cluster_id: str, namespace: str, previous: Mapping[str, str]) -> dict[str, None]: ... + + +@runtime_checkable +class GitProvider(Protocol): + """core/git/ (#286): a Git layer for branches, commits and reads (workspace.py) and a thin platform adapter per host for the + PR (github.py; gitea.py is REST alone). The full contract is core/git/base.py HostGitProvider. Every change is a request + branch and a PR; nothing pushes to the default branch.""" + external_ci: bool + post_statuses: bool + posts_ci: bool + def read_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: ... # files, commit sha + def list_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: ... # {path: blob|commit}, sha + def push_request_branch(self, req: Any) -> Any: ... # BranchRequest -> PushResult + def open_pr(self, branch: str, head: str, title: str, body: str) -> PrRef: ... + def pr_status(self, pr: PrRef, *, ci: bool = True) -> PrStatus: ... + def merge_check(self, head: str, folder: str, prev: Mapping[str, str], files: Mapping[str, str | None], *, + whole_folder: bool = False) -> Any: ... + def merge(self, pr: PrRef, expected_head: str) -> str: ... # merge sha, pinned to expected_head + def comment(self, pr: PrRef, text: str) -> None: ... + def close(self, pr: PrRef, comment: str) -> None: ... + def delete_branch(self, branch: str, expected: str) -> bool: ... + + +@runtime_checkable +class Validator(Protocol): + """core/validate/: the Kyverno CLI bundle plus kubeconform on the rendered files.""" + def validate(self, files: Mapping[str, str], cluster_id: str, environment: str, + previous: Mapping[str, str | None] | None = None, held: list[Finding] | None = None) -> list[Finding]: ... + + +@runtime_checkable +class CapacityBackend(Protocol): + """remote (cmapi-capacity over HTTP, default) or embedded (the worker runs the jobs). + + The holds of open requests live in the cmapi schema, so `reserve_check`, `reserve`, `confirm` and `release` take the + caller's transaction: "Placement, the capacity check inside every plan [...] stay in the API, because they write requests + or reservations" (docs/01). The hold is core/capacity_backend.py's CapacityHold.""" + def check(self, cluster_id: str, environment: str, cpu_delta: float, memory_delta: float, *, session: Any = None, + exclude: str | None = None, exclude_placement: str | None = None, + namespace: str | None = None) -> CapacityResult: ... + def placement(self, placement_id: str) -> Any: ... + def reserve_check(self, session: Any, cluster_id: str, environment: str, hold: Any, *, + placement_id: str | None = None) -> CapacityResult: ... + def reserve(self, session: Any, request_id: str, cluster_id: str, hold: Any, term: timedelta, *, + placement_id: str | None = None) -> None: ... + def confirm(self, session: Any, request_id: str, cluster_id: str, environment: str) -> CapacityResult | None: ... + def release(self, session: Any, request_id: str, why: str) -> int: ... + + +@runtime_checkable +class MetricsSource(Protocol): + """Each cluster's Thanos Querier (default) or an ACM Observability hub. Used by cmapi-capacity only.""" + def query(self, cluster_id: str, promql: str, at: datetime | None = None) -> list[dict[str, Any]]: ... + + +@runtime_checkable +class SyncSignal(Protocol): + """poll (default) or notify (Argo CD Notifications webhook, then confirmed by a read).""" + def status(self, cluster_id: str) -> AppStatus: ... + + +@runtime_checkable +class OperationsEngine(Protocol): + """builtin (worker steps, default), Argo Workflows or Tekton: docs/02's OperationsEngine, synchronous as the rest of cmapi + (core/operations.py). `available` says whether it can take a run, and why not; `submit` starts the run whose operations row + the caller wrote, in the caller's transaction, and returns the run's name on the engine; `cancel` stops it. The built-in + engine keeps its state in that row and its operation_steps, so it needs no `watch`; an Argo or Tekton adapter adds it.""" + name: str + def available(self) -> tuple[bool, str]: ... + def submit(self, session: Any, operation: Any, template: Any) -> str: ... + def cancel(self, session: Any, operation: Any) -> None: ... + + +@runtime_checkable +class EventPublisher(Protocol): + """none (default), signed webhook, Kafka. Fed from the outbox table, so delivery is at least once.""" + def publish(self, event: CloudEvent) -> None: ... + + +@runtime_checkable +class Notifier(Protocol): + """email (default), Slack, Teams. Expiry notices and approval prompts go to the team DL.""" + def send(self, to: list[str], subject: str, body: str, links: Mapping[str, str] | None = None) -> None: ... + + +@runtime_checkable +class ApprovalChannel(Protocol): + """portal (default), email link, argo-events, servicenow, slack/teams. A channel notifies or + relays; the decision is always POST /requests/{id}:approve with an eligible person's identity.""" + name: str + def notify_pending(self, request: Mapping[str, Any], groups: list[str]) -> None: ... + def notify_decision(self, request: Mapping[str, Any], decision: str) -> None: ... + + +# --------------------------------------------------------------------------- readers + + +@runtime_checkable +class KubeReader(Protocol): + """core/clients/kube.py: watch cache per cluster through the read-only cmapi-reader.""" + def namespaces(self, cluster_id: str) -> list[Mapping[str, Any]]: ... + def get(self, cluster_id: str, kind: str, namespace: str | None, name: str) -> Mapping[str, Any] | None: ... + def quota(self, cluster_id: str, namespace: str) -> Mapping[str, Any] | None: ... + + +@runtime_checkable +class PolicyReportReader(Protocol): + """plugins/policies: PolicyReport and ClusterPolicyReport (wgpolicyk8s.io), CEL policy kinds.""" + def results(self, cluster_id: str) -> list[PolicyResult]: ... + def bundle_tag(self, cluster_id: str) -> str | None: ... + + +@runtime_checkable +class AuditLog(Protocol): + """core/audit.py: audit_events rows; never token values.""" + def record(self, actor: Identity, action: str, target: str, detail: Mapping[str, Any]) -> None: ... + + +@runtime_checkable +class Plugin(Protocol): + """Every plugin: name, a router, models, a planner and its read RBAC (docs/01, Adding an offering).""" + name: str + def routes(self) -> Any: ... + def plan(self, request: Mapping[str, Any], caller: Identity) -> Mapping[str, Any]: ... diff --git a/cmapi/src/cmapi/jobs/apply.py b/cmapi/src/cmapi/jobs/apply.py index 80aafb46..5f367e4e 100644 --- a/cmapi/src/cmapi/jobs/apply.py +++ b/cmapi/src/cmapi/jobs/apply.py @@ -1,170 +1,170 @@ -"""apply: delivery.mode apply, a create or a change whose PR passed its checks (#286; the Atlantis model, Fable's design 1.3). -Apply the PR head's folder, confirm it by a read, and move to applied; the merge job merges after that, so main records only -what succeeded. - - 1. The branch is still at the pinned head, its folder is the plan's files, and the merge check passes. Before any apply a - failure here ends the PR: failed, or superseded for a merge check. Nothing was applied. - 2. apply_started, in its own transaction under the row lock (jobs/delivery.py): from here the cluster may be ahead of main, - so this request can only reach applied or sync_failed, never failed or superseded, and :cancel is refused. - 3. Server-side apply with the deliverer identity, and the removal of the objects the plan drops; a namespace that exists and - is not cmapi-managed is refused before the first write. - 4. confirmed_by_read, the full-plan read (core/sync.py read_plan, #751). Not yet: wait at pollInterval, up to syncTimeout from apply_started. Past it: sync_failed, PR and - branch kept, the lock held; :retry runs this job again. - 5. applied, row.pr.applied_head, and the merge job. - -Also from sync_failed with no merge sha (a :retry of an apply that had not finished). Deletes merge first (the arbitration, -row 4) and never come here. - -A person may merge the PR between the checks and this job, and delete its branch: the branch is then gone or behind main, and -the merge check sees main already holding the plan. Each of those refusals reads the PR first, and a merged PR is adopted -through the merge job's post-merge check, never failed (the arbitration, row 16; #448). -""" -from __future__ import annotations - -from datetime import datetime - -from sqlalchemy.orm import Session - -from cmapi.core.clients.kube import ClusterUnreachable, KubeError -from cmapi.core.context import AppContext -from cmapi.core.db.models import JobRow -from cmapi.core.db.repo import JobRepo, RequestRepo, utcnow -from cmapi.core.errors import Problem -from cmapi.core.git.oplog import Op -from cmapi.core.lifecycle import Event as E, State as S -from cmapi.core.observability import MERGE_CONFLICTS -from cmapi.core.render.manifests import folder -from cmapi.core.sync import ApplyDelivery, ApplyRefused, PruneRefused, confirmed_by_read, scoped_documents -from cmapi.jobs.delivery import (ADOPTION_STALE, APPLY_STARTED, adoption_stored, adoption_writes, apply_started, end_adoption, - end_pr, mark_apply_started, mode_of, planned, pr_of, request_context) - - -def apply(ctx: AppContext, s: Session, job: JobRow) -> None: - repo, jobs = RequestRepo(s), JobRepo(s) - row = repo.get(job.request_id) - serves = row.status == S.PR_OPEN.value or (row.status == S.SYNC_FAILED.value and not row.merge_sha) - if not serves or not row.pr or row.action == "delete" or mode_of(ctx, row.cluster_id) != "apply": - jobs.done(job) - return - with request_context(ctx, row, job): - _apply(ctx, repo, jobs, row, job) - - -def _stop(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow, why: str, started: bool, - event: E = E.PR_FAILED) -> None: - """Before an apply started: the PR ends (failed, or superseded). After: sync_failed, the PR and the branch kept (F1).""" - if started: - if row.status == S.PR_OPEN.value: - repo.move(row, E.SYNC_TIMEOUT, "cmapi-deliverer", f"{why}; the cluster may hold part of {row.pr['head'][:8]}"[:240]) - else: - repo.event(row, "refused", "cmapi-deliverer", why[:300]) - else: - repo.move(row, event, "cmapi-deliverer", why[:240]) - end_pr(ctx, repo, jobs, row, why) - jobs.done(job) - - -def _apply(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow) -> None: - from cmapi.jobs.watch_sync import _deliverer, _live, _managed, _NotYet, _reader_cache, _rules - - head = (job.payload or {}).get("head") or row.pr.get("applied_head") or row.pr["head"] - started = apply_started(repo, row) == head - where = folder(row.cluster_id, row.namespace) - files = planned(row) - previous = row.plan.get("prev") or {} - current = ctx.git.branch_head(row.pr["branch"]) - if current != head: - if _adopt_merged(ctx, repo, jobs, row, job): - return - return _stop(ctx, repo, jobs, row, job, f"the PR head moved from {head[:8]} to {(current or 'nothing')[:8]}", started) - if ctx.git.tree_files(head, where) != files: - return _stop(ctx, repo, jobs, row, job, f"the branch's folder at {head[:8]} is not the approved plan", started) - check = ctx.git.merge_check(head, where, previous, row.plan["files"]) - if not check.ok: - if _adopt_merged(ctx, repo, jobs, row, job): - return - MERGE_CONFLICTS.labels("apply").inc() - why = check.reason(ctx.git.default_branch) - repo.event(row, "merge_check", "worker", why[:300], {"caller": "apply", "main": check.main_sha, "head": head, - "conflict_paths": list(check.conflicts)}) - return _stop(ctx, repo, jobs, row, job, why, started, E.BASE_CHANGED) - try: - client = _deliverer(ctx, row.cluster_id) - d = ApplyDelivery(client) - writes = files - if adoption_stored(row) is not None: - # D16 before cmapi's own write, and each object sent with the uid and resourceVersion the plan read: the API - # server refuses an object that changed between this read and the write (adoption_writes). - found, writes = adoption_writes(ctx, row, files, resuming=started) - if found is not None: - if started: - return _stop(ctx, repo, jobs, row, job, f"{ADOPTION_STALE}: {found.detail}", started) - end_adoption(ctx, repo, jobs, row, found, "cmapi-deliverer") - jobs.done(job) - return - else: - live = d.client.get_object("Namespace", None, row.namespace) - if live is not None and not _managed(live): - return _stop(ctx, repo, jobs, row, job, f"{row.namespace} exists on the cluster and cmapi does not manage it; nothing applied", - started) - # A document outside the request's namespace is refused before apply_started, so the PR ends with nothing applied (#756). - scoped_documents(writes, row.namespace) - if not started: - if not mark_apply_started(ctx, row.request_id, head): - jobs.done(job) # a :cancel won the row first: nothing applied - return - started = True - jobs.fence() - with Op("apply", head_sha=head) as op: - n = d.apply_folder(writes, row.namespace) - pruned = d.prune_objects(row.namespace, files, previous) - cache = _reader_cache(ctx, row.cluster_id) - ok, why = confirmed_by_read(_live(cache.client), row.namespace, files, previous, **_rules(ctx)) - op.set(objects=n, pruned=pruned, confirmed=ok, reason=why) - if not ok: - raise _NotYet(why) - except (ApplyRefused, PruneRefused) as exc: # nothing written, or applied and nothing deleted: waiting cannot fix it - return _stop(ctx, repo, jobs, row, job, str(exc), started) - except KubeError as exc: - if exc.status == 409 and adoption_stored(row) is not None: # a precondition of adoption_writes - return _stop(ctx, repo, jobs, row, job, f"{ADOPTION_STALE}: {str(exc)[:160]}", started) - if exc.status in (400, 403, 409, 422): # the cluster refused the objects: waiting cannot fix it - return _stop(ctx, repo, jobs, row, job, f"the cluster refused the apply: {str(exc)[:160]}", started) - return _wait(ctx, repo, jobs, row, job, f"{type(exc).__name__}: {exc}", started) - except (_NotYet, ClusterUnreachable, Problem) as exc: - return _wait(ctx, repo, jobs, row, job, str(getattr(exc, "detail", None) or exc), started) - repo.move(row, E.APPLIED, "cmapi-deliverer", f"{n} objects from {row.pr['branch']} at {head[:8]}, before the merge, " - f"confirmed by a read: {why}"[:300]) - row.pr = {**row.pr, "applied_head": head} - jobs.done(job) - jobs.enqueue("merge", request_id=row.request_id, cluster_id=row.cluster_id, payload={"head": head}) - - -def _adopt_merged(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow) -> bool: - """A person merged the PR: adopted through the merge job's post-merge check (merged, then watch_sync applies from main), and - True. False while the PR is open or closed unmerged, and the caller's refusal stands.""" - state = ctx.git.pr_status(pr_of(row)) - if state.state != "merged": - return False - from cmapi.jobs.merge import _merged - - _merged(ctx, repo, jobs, row, job, state.merge_sha or "", adopted=True) - return True - - -def _wait(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow, why: str, started: bool) -> None: - """Not confirmed yet, or the cluster cannot be read: wait at pollInterval, with the reason on the request once. The clock - starts at apply_started (or the job, before it); past syncTimeout the request is sync_failed, never failed. A :retry - restarts it (`since`, routers/requests.py), as for watch_sync: the first apply_started would leave it one read.""" - marks = [e.at for e in repo.events(row.request_id) if e.event == APPLY_STARTED] - since = marks[-1] if marks and started else job.created_at - retried = (job.payload or {}).get("since") - if retried: - since = max(since, datetime.fromisoformat(retried)) - waited = (utcnow() - since).total_seconds() - if waited > ctx.delivery.sync_timeout_seconds: - return _stop(ctx, repo, jobs, row, job, f"not confirmed after {int(waited)} s: {why[:160]}", started) - if job.last_error != why[:2000]: - repo.event(row, "sync_wait", "worker", why[:200]) - jobs.retry(job, why, ctx.delivery.poll_seconds) - job.attempts = 0 # waiting is not a failure +"""apply: delivery.mode apply, a create or a change whose PR passed its checks (#286; the Atlantis model, Fable's design 1.3). +Apply the PR head's folder, confirm it by a read, and move to applied; the merge job merges after that, so main records only +what succeeded. + + 1. The branch is still at the pinned head, its folder is the plan's files, and the merge check passes. Before any apply a + failure here ends the PR: failed, or superseded for a merge check. Nothing was applied. + 2. apply_started, in its own transaction under the row lock (jobs/delivery.py): from here the cluster may be ahead of main, + so this request can only reach applied or sync_failed, never failed or superseded, and :cancel is refused. + 3. Server-side apply with the deliverer identity, and the removal of the objects the plan drops; a namespace that exists and + is not cmapi-managed is refused before the first write. + 4. confirmed_by_read, the full-plan read (core/sync.py read_plan, #751). Not yet: wait at pollInterval, up to syncTimeout from apply_started. Past it: sync_failed, PR and + branch kept, the lock held; :retry runs this job again. + 5. applied, row.pr.applied_head, and the merge job. + +Also from sync_failed with no merge sha (a :retry of an apply that had not finished). Deletes merge first (the arbitration, +row 4) and never come here. + +A person may merge the PR between the checks and this job, and delete its branch: the branch is then gone or behind main, and +the merge check sees main already holding the plan. Each of those refusals reads the PR first, and a merged PR is adopted +through the merge job's post-merge check, never failed (the arbitration, row 16; #448). +""" +from __future__ import annotations + +from datetime import datetime + +from sqlalchemy.orm import Session + +from cmapi.core.clients.kube import ClusterUnreachable, KubeError +from cmapi.core.context import AppContext +from cmapi.core.db.models import JobRow +from cmapi.core.db.repo import JobRepo, RequestRepo, utcnow +from cmapi.core.errors import Problem +from cmapi.core.git.oplog import Op +from cmapi.core.lifecycle import Event as E, State as S +from cmapi.core.observability import MERGE_CONFLICTS +from cmapi.core.render.manifests import folder +from cmapi.core.sync import ApplyDelivery, ApplyRefused, PruneRefused, confirmed_by_read, scoped_documents +from cmapi.jobs.delivery import (ADOPTION_STALE, APPLY_STARTED, adoption_stored, adoption_writes, apply_started, end_adoption, + end_pr, mark_apply_started, mode_of, planned, pr_of, request_context) + + +def apply(ctx: AppContext, s: Session, job: JobRow) -> None: + repo, jobs = RequestRepo(s), JobRepo(s) + row = repo.get(job.request_id) + serves = row.status == S.PR_OPEN.value or (row.status == S.SYNC_FAILED.value and not row.merge_sha) + if not serves or not row.pr or row.action == "delete" or mode_of(ctx, row.cluster_id) != "apply": + jobs.done(job) + return + with request_context(ctx, row, job): + _apply(ctx, repo, jobs, row, job) + + +def _stop(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow, why: str, started: bool, + event: E = E.PR_FAILED) -> None: + """Before an apply started: the PR ends (failed, or superseded). After: sync_failed, the PR and the branch kept (F1).""" + if started: + if row.status == S.PR_OPEN.value: + repo.move(row, E.SYNC_TIMEOUT, "cmapi-deliverer", f"{why}; the cluster may hold part of {row.pr['head'][:8]}"[:240]) + else: + repo.event(row, "refused", "cmapi-deliverer", why[:300]) + else: + repo.move(row, event, "cmapi-deliverer", why[:240]) + end_pr(ctx, repo, jobs, row, why) + jobs.done(job) + + +def _apply(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow) -> None: + from cmapi.jobs.watch_sync import _deliverer, _live, _managed, _NotYet, _reader_cache, _rules + + head = (job.payload or {}).get("head") or row.pr.get("applied_head") or row.pr["head"] + started = apply_started(repo, row) == head + where = folder(row.cluster_id, row.namespace) + files = planned(row) + previous = row.plan.get("prev") or {} + current = ctx.git.branch_head(row.pr["branch"]) + if current != head: + if _adopt_merged(ctx, repo, jobs, row, job): + return + return _stop(ctx, repo, jobs, row, job, f"the PR head moved from {head[:8]} to {(current or 'nothing')[:8]}", started) + if ctx.git.tree_files(head, where) != files: + return _stop(ctx, repo, jobs, row, job, f"the branch's folder at {head[:8]} is not the approved plan", started) + check = ctx.git.merge_check(head, where, previous, row.plan["files"]) + if not check.ok: + if _adopt_merged(ctx, repo, jobs, row, job): + return + MERGE_CONFLICTS.labels("apply").inc() + why = check.reason(ctx.git.default_branch) + repo.event(row, "merge_check", "worker", why[:300], {"caller": "apply", "main": check.main_sha, "head": head, + "conflict_paths": list(check.conflicts)}) + return _stop(ctx, repo, jobs, row, job, why, started, E.BASE_CHANGED) + try: + client = _deliverer(ctx, row.cluster_id) + d = ApplyDelivery(client) + writes = files + if adoption_stored(row) is not None: + # D16 before cmapi's own write, and each object sent with the uid and resourceVersion the plan read: the API + # server refuses an object that changed between this read and the write (adoption_writes). + found, writes = adoption_writes(ctx, row, files, resuming=started) + if found is not None: + if started: + return _stop(ctx, repo, jobs, row, job, f"{ADOPTION_STALE}: {found.detail}", started) + end_adoption(ctx, repo, jobs, row, found, "cmapi-deliverer") + jobs.done(job) + return + else: + live = d.client.get_object("Namespace", None, row.namespace) + if live is not None and not _managed(live): + return _stop(ctx, repo, jobs, row, job, f"{row.namespace} exists on the cluster and cmapi does not manage it; nothing applied", + started) + # A document outside the request's namespace is refused before apply_started, so the PR ends with nothing applied (#756). + scoped_documents(writes, row.namespace) + if not started: + if not mark_apply_started(ctx, row.request_id, head): + jobs.done(job) # a :cancel won the row first: nothing applied + return + started = True + jobs.fence() + with Op("apply", head_sha=head) as op: + n = d.apply_folder(writes, row.namespace) + pruned = d.prune_objects(row.namespace, files, previous) + cache = _reader_cache(ctx, row.cluster_id) + ok, why = confirmed_by_read(_live(cache.client), row.namespace, files, previous, **_rules(ctx)) + op.set(objects=n, pruned=pruned, confirmed=ok, reason=why) + if not ok: + raise _NotYet(why) + except (ApplyRefused, PruneRefused) as exc: # nothing written, or applied and nothing deleted: waiting cannot fix it + return _stop(ctx, repo, jobs, row, job, str(exc), started) + except KubeError as exc: + if exc.status == 409 and adoption_stored(row) is not None: # a precondition of adoption_writes + return _stop(ctx, repo, jobs, row, job, f"{ADOPTION_STALE}: {str(exc)[:160]}", started) + if exc.status in (400, 403, 409, 422): # the cluster refused the objects: waiting cannot fix it + return _stop(ctx, repo, jobs, row, job, f"the cluster refused the apply: {str(exc)[:160]}", started) + return _wait(ctx, repo, jobs, row, job, f"{type(exc).__name__}: {exc}", started) + except (_NotYet, ClusterUnreachable, Problem) as exc: + return _wait(ctx, repo, jobs, row, job, str(getattr(exc, "detail", None) or exc), started) + repo.move(row, E.APPLIED, "cmapi-deliverer", f"{n} objects from {row.pr['branch']} at {head[:8]}, before the merge, " + f"confirmed by a read: {why}"[:300]) + row.pr = {**row.pr, "applied_head": head} + jobs.done(job) + jobs.enqueue("merge", request_id=row.request_id, cluster_id=row.cluster_id, payload={"head": head}) + + +def _adopt_merged(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow) -> bool: + """A person merged the PR: adopted through the merge job's post-merge check (merged, then watch_sync applies from main), and + True. False while the PR is open or closed unmerged, and the caller's refusal stands.""" + state = ctx.git.pr_status(pr_of(row), ci=False) + if state.state != "merged": + return False + from cmapi.jobs.merge import _merged + + _merged(ctx, repo, jobs, row, job, state.merge_sha or "", adopted=True) + return True + + +def _wait(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow, why: str, started: bool) -> None: + """Not confirmed yet, or the cluster cannot be read: wait at pollInterval, with the reason on the request once. The clock + starts at apply_started (or the job, before it); past syncTimeout the request is sync_failed, never failed. A :retry + restarts it (`since`, routers/requests.py), as for watch_sync: the first apply_started would leave it one read.""" + marks = [e.at for e in repo.events(row.request_id) if e.event == APPLY_STARTED] + since = marks[-1] if marks and started else job.created_at + retried = (job.payload or {}).get("since") + if retried: + since = max(since, datetime.fromisoformat(retried)) + waited = (utcnow() - since).total_seconds() + if waited > ctx.delivery.sync_timeout_seconds: + return _stop(ctx, repo, jobs, row, job, f"not confirmed after {int(waited)} s: {why[:160]}", started) + if job.last_error != why[:2000]: + repo.event(row, "sync_wait", "worker", why[:200]) + jobs.retry(job, why, ctx.delivery.poll_seconds) + job.attempts = 0 # waiting is not a failure diff --git a/cmapi/src/cmapi/jobs/merge.py b/cmapi/src/cmapi/jobs/merge.py index 0d786c94..b407c35c 100644 --- a/cmapi/src/cmapi/jobs/merge.py +++ b/cmapi/src/cmapi/jobs/merge.py @@ -1,167 +1,167 @@ -"""merge: the PR's merge through the host API, pinned to a sha (#286; Fable's design 1.2, 1.3, 2.3, 2.4). - - argocd mode, and a delete in apply mode pr_open pinned to the head the checks passed on - apply mode, a create or a change applied, pinned to the applied head (row.pr.applied_head) - merge_failed - -Steps: read the PR first. Merged already (a person, or an earlier attempt that stopped after the host merged): adopted, after -the post-merge check. Closed: before an apply the request is failed; after one, a new PR opens from the same branch, which -the reproducible commit re-creates bit for bit if it is gone, and the request never becomes failed. Then the merge check on a -fresh main, the merge, and the post-merge check: the folder at the merge sha must be the plan's. - -A refusal after an apply is merge_failed (F1): the PR and the branch are kept, the reason goes on the PR as a comment and on -the timeline, and the alert fires. A host or network error is retried with the worker's backoff; after five attempts applied -becomes merge_failed (worker.py). From merge_failed only :retry runs this job again. Never a rollback, never a close.""" -from __future__ import annotations - -from datetime import datetime, timezone - -from sqlalchemy.orm import Session - -from cmapi.core.context import AppContext -from cmapi.core.db.models import JobRow -from cmapi.core.db.repo import JobRepo, RequestRepo -from cmapi.core.git.base import HeadMoved, NotMergeable, NotUtf8, PlatformRefused -from cmapi.core.lifecycle import Event as E, State as S -from cmapi.core.git.workspace import BranchRefused -from cmapi.core.observability import GIT_ORPHANS, LEAD_TIME, MERGE_CONFLICTS -from cmapi.core.ports import PrRef -from cmapi.core.render.manifests import folder -from cmapi.jobs.delivery import body_of, branch_request, end_pr, mode_of, planned, pr_of, request_context, title_of - -AFTER_APPLY = (S.APPLIED.value, S.MERGE_FAILED.value) - - -def merge(ctx: AppContext, s: Session, job: JobRow) -> None: - repo, jobs = RequestRepo(s), JobRepo(s) - row = repo.get(job.request_id) - merge_first = row.status == S.PR_OPEN.value and (mode_of(ctx, row.cluster_id) != "apply" or row.action == "delete") - if not row.pr or not (merge_first or row.status in AFTER_APPLY): - jobs.done(job) - return - with request_context(ctx, row, job): - _merge(ctx, repo, jobs, row, job) - - -def merge_failed(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, why: str, detail: dict | None = None) -> None: - """F1: the cluster holds the change and main does not. The lock, the PR and the branch stay; the reason is on the PR.""" - repo.event(row, "merge_failed", "worker", why[:300], detail or {}) - if row.status == S.APPLIED.value: - repo.move(row, E.MERGE_FAILED, "worker", why[:240]) - jobs.fence() - ctx.git.comment(pr_of(row), f"cmapi: {row.request_id} is applied on the cluster and its merge did not happen: {why}. " - "The PR stays open; :retry merges it.") - - -def _merge(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow) -> None: - after_apply = row.status in AFTER_APPLY - pinned = row.pr.get("applied_head") if after_apply else ((job.payload or {}).get("head") or row.pr["head"]) - pr = pr_of(row) - state = ctx.git.pr_status(pr) - if state.state == "merged": - return _merged(ctx, repo, jobs, row, job, state.merge_sha or "", adopted=True) - if state.state == "closed": - if not after_apply: - repo.move(row, E.PR_FAILED, "worker", "the PR was closed") - jobs.done(job) - jobs.enqueue("git_cleanup", request_id=row.request_id, cluster_id=row.cluster_id) - return - try: - pr = _reopen(ctx, repo, jobs, row, pinned) - except BranchRefused as exc: - GIT_ORPHANS.labels("foreign_branch", "refused").inc() - merge_failed(ctx, repo, jobs, row, f"the PR was closed and it cannot open again: {exc}", {"branch": row.pr["branch"]}) - jobs.done(job) - return - check = ctx.git.merge_check(pinned, folder(row.cluster_id, row.namespace), row.plan.get("prev") or {}, row.plan["files"], - whole_folder=row.action == "delete") - if not check.ok: - MERGE_CONFLICTS.labels("merge").inc() - why = check.reason(ctx.git.default_branch) - detail = {"caller": "merge", "main": check.main_sha, "head": pinned, "conflict_paths": list(check.conflicts)} - repo.event(row, "merge_check", "worker", why[:300], detail) - if after_apply: - merge_failed(ctx, repo, jobs, row, why, detail) - else: - repo.move(row, E.BASE_CHANGED, "worker", why[:240]) - end_pr(ctx, repo, jobs, row, why) - jobs.done(job) - return - # The request row, locked until this job commits (Fable's design, 2): a :cancel takes the same lock, so it waits for the - # merge and is then refused, and one that came first is seen here and nothing merges. - before = row.status - repo.s.refresh(row, attribute_names=["status"], with_for_update=True) - if row.status != before: - jobs.done(job) - return - jobs.fence() - try: - sha = ctx.git.merge(pr, pinned) - except (HeadMoved, PlatformRefused) as exc: - why = f"the host refused the merge: {exc}" - if after_apply: - merge_failed(ctx, repo, jobs, row, why, {"http_status": getattr(exc, "status", None)}) - else: - repo.move(row, E.PR_FAILED, "worker", why[:240]) - end_pr(ctx, repo, jobs, row, why) - jobs.done(job) - return - except NotMergeable as exc: - if exc.transient: - raise # the host is still computing: the worker's backoff, then merge_failed - if after_apply: - merge_failed(ctx, repo, jobs, row, f"the host will not merge it: {exc}") - else: - repo.move(row, E.PR_FAILED, "worker", f"the host will not merge it: {exc}"[:240]) - end_pr(ctx, repo, jobs, row, str(exc)) - jobs.done(job) - return - _merged(ctx, repo, jobs, row, job, sha, adopted=False) - - -def _reopen(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, pinned: str) -> PrRef: - """A person closed the PR after the apply: a new PR from the same branch, never failed (Fable 1.3).""" - branch = row.pr["branch"] - jobs.fence() # both the push of a re-created branch and the new PR are external effects - if ctx.git.branch_head(branch) != pinned: - ctx.git.recreate_branch(branch_request(ctx, row), row.pr.get("base") or "", pinned) - new = ctx.git.open_pr(branch, pinned, title_of(row), body_of(row)) - repo.event(row, "pr_reopened", "cmapi-bot", f"#{row.pr['number']} was closed; #{new.number} opened from the same branch", - {"old": row.pr["number"], "new": new.number}) - row.pr = {**row.pr, "number": new.number, "url": new.url, "head": new.head_sha} - return new - - -def _merged(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow, sha: str, adopted: bool) -> None: - """Fable 2.4, a gate on every path that records a merge (this job, a hand merge pr_checks or apply finds): the folder at - the merge sha must be the plan's. Then merged; after an apply also synced, since the read already confirmed it; otherwise - watch_sync. A merge whose folder is not the plan's, or with no sha to read, is merged and then sync_failed, with the lock - held for an operator: nothing is applied from it and a delete never waits for a prune of it (#449).""" - after_apply = row.status in AFTER_APPLY - unreadable: NotUtf8 | None = None - try: - on_main = ctx.git.tree_files(sha, folder(row.cluster_id, row.namespace)) if sha else None - fulfilled = on_main == planned(row) - if fulfilled and row.action == "delete": - # A delete's folder is empty at the merge: no file of any kind, at any depth, is left of it (#616). - fulfilled = not ctx.git.list_folder(folder(row.cluster_id, row.namespace), sha)[0] - except NotUtf8 as exc: - # The merge happened: a folder no plan can hold (#626) is not the plan's. Never retried into failed or merge_failed. - fulfilled, unreadable = False, exc - row.merge_sha = sha or None - how = "adopted: merged on the host" if adopted else "merged" - repo.event(row, "merge_verified", "worker", f"{how} {sha[:8]}; the folder at it {'is' if fulfilled else 'is not'} the plan's", - {"merge_sha": sha, "adopted": adopted}) - repo.move(row, E.MERGED, "cmapi-bot", f"{how} {sha[:8]}") - if not fulfilled: - why = f"the folder at the merge {sha[:8]} is not the approved plan" if sha else "the host gave no merge sha to check" - repo.move(row, E.SYNC_TIMEOUT, "worker", f"{why}: {unreadable}"[:240] if unreadable else why) - elif after_apply: - repo.move(row, E.SYNCED, "cmapi-deliverer", "applied and confirmed by a read before the merge") - approval = "auto" if (row.requirement or {}).get("auto") else "human" - LEAD_TIME.labels(row.plugin, row.action, approval).observe((datetime.now(timezone.utc) - row.created_at).total_seconds()) - else: - jobs.enqueue("watch_sync", request_id=row.request_id, cluster_id=row.cluster_id) - ctx.git.cleanup(row.cluster_id, row.request_id) - jobs.done(job) - jobs.enqueue("git_cleanup", request_id=row.request_id, cluster_id=row.cluster_id) +"""merge: the PR's merge through the host API, pinned to a sha (#286; Fable's design 1.2, 1.3, 2.3, 2.4). + + argocd mode, and a delete in apply mode pr_open pinned to the head the checks passed on + apply mode, a create or a change applied, pinned to the applied head (row.pr.applied_head) + merge_failed + +Steps: read the PR first. Merged already (a person, or an earlier attempt that stopped after the host merged): adopted, after +the post-merge check. Closed: before an apply the request is failed; after one, a new PR opens from the same branch, which +the reproducible commit re-creates bit for bit if it is gone, and the request never becomes failed. Then the merge check on a +fresh main, the merge, and the post-merge check: the folder at the merge sha must be the plan's. + +A refusal after an apply is merge_failed (F1): the PR and the branch are kept, the reason goes on the PR as a comment and on +the timeline, and the alert fires. A host or network error is retried with the worker's backoff; after five attempts applied +becomes merge_failed (worker.py). From merge_failed only :retry runs this job again. Never a rollback, never a close.""" +from __future__ import annotations + +from datetime import datetime, timezone + +from sqlalchemy.orm import Session + +from cmapi.core.context import AppContext +from cmapi.core.db.models import JobRow +from cmapi.core.db.repo import JobRepo, RequestRepo +from cmapi.core.git.base import HeadMoved, NotMergeable, NotUtf8, PlatformRefused +from cmapi.core.lifecycle import Event as E, State as S +from cmapi.core.git.workspace import BranchRefused +from cmapi.core.observability import GIT_ORPHANS, LEAD_TIME, MERGE_CONFLICTS +from cmapi.core.ports import PrRef +from cmapi.core.render.manifests import folder +from cmapi.jobs.delivery import body_of, branch_request, end_pr, mode_of, planned, pr_of, request_context, title_of + +AFTER_APPLY = (S.APPLIED.value, S.MERGE_FAILED.value) + + +def merge(ctx: AppContext, s: Session, job: JobRow) -> None: + repo, jobs = RequestRepo(s), JobRepo(s) + row = repo.get(job.request_id) + merge_first = row.status == S.PR_OPEN.value and (mode_of(ctx, row.cluster_id) != "apply" or row.action == "delete") + if not row.pr or not (merge_first or row.status in AFTER_APPLY): + jobs.done(job) + return + with request_context(ctx, row, job): + _merge(ctx, repo, jobs, row, job) + + +def merge_failed(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, why: str, detail: dict | None = None) -> None: + """F1: the cluster holds the change and main does not. The lock, the PR and the branch stay; the reason is on the PR.""" + repo.event(row, "merge_failed", "worker", why[:300], detail or {}) + if row.status == S.APPLIED.value: + repo.move(row, E.MERGE_FAILED, "worker", why[:240]) + jobs.fence() + ctx.git.comment(pr_of(row), f"cmapi: {row.request_id} is applied on the cluster and its merge did not happen: {why}. " + "The PR stays open; :retry merges it.") + + +def _merge(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow) -> None: + after_apply = row.status in AFTER_APPLY + pinned = row.pr.get("applied_head") if after_apply else ((job.payload or {}).get("head") or row.pr["head"]) + pr = pr_of(row) + state = ctx.git.pr_status(pr, ci=False) + if state.state == "merged": + return _merged(ctx, repo, jobs, row, job, state.merge_sha or "", adopted=True) + if state.state == "closed": + if not after_apply: + repo.move(row, E.PR_FAILED, "worker", "the PR was closed") + jobs.done(job) + jobs.enqueue("git_cleanup", request_id=row.request_id, cluster_id=row.cluster_id) + return + try: + pr = _reopen(ctx, repo, jobs, row, pinned) + except BranchRefused as exc: + GIT_ORPHANS.labels("foreign_branch", "refused").inc() + merge_failed(ctx, repo, jobs, row, f"the PR was closed and it cannot open again: {exc}", {"branch": row.pr["branch"]}) + jobs.done(job) + return + check = ctx.git.merge_check(pinned, folder(row.cluster_id, row.namespace), row.plan.get("prev") or {}, row.plan["files"], + whole_folder=row.action == "delete") + if not check.ok: + MERGE_CONFLICTS.labels("merge").inc() + why = check.reason(ctx.git.default_branch) + detail = {"caller": "merge", "main": check.main_sha, "head": pinned, "conflict_paths": list(check.conflicts)} + repo.event(row, "merge_check", "worker", why[:300], detail) + if after_apply: + merge_failed(ctx, repo, jobs, row, why, detail) + else: + repo.move(row, E.BASE_CHANGED, "worker", why[:240]) + end_pr(ctx, repo, jobs, row, why) + jobs.done(job) + return + # The request row, locked until this job commits (Fable's design, 2): a :cancel takes the same lock, so it waits for the + # merge and is then refused, and one that came first is seen here and nothing merges. + before = row.status + repo.s.refresh(row, attribute_names=["status"], with_for_update=True) + if row.status != before: + jobs.done(job) + return + jobs.fence() + try: + sha = ctx.git.merge(pr, pinned) + except (HeadMoved, PlatformRefused) as exc: + why = f"the host refused the merge: {exc}" + if after_apply: + merge_failed(ctx, repo, jobs, row, why, {"http_status": getattr(exc, "status", None)}) + else: + repo.move(row, E.PR_FAILED, "worker", why[:240]) + end_pr(ctx, repo, jobs, row, why) + jobs.done(job) + return + except NotMergeable as exc: + if exc.transient: + raise # the host is still computing: the worker's backoff, then merge_failed + if after_apply: + merge_failed(ctx, repo, jobs, row, f"the host will not merge it: {exc}") + else: + repo.move(row, E.PR_FAILED, "worker", f"the host will not merge it: {exc}"[:240]) + end_pr(ctx, repo, jobs, row, str(exc)) + jobs.done(job) + return + _merged(ctx, repo, jobs, row, job, sha, adopted=False) + + +def _reopen(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, pinned: str) -> PrRef: + """A person closed the PR after the apply: a new PR from the same branch, never failed (Fable 1.3).""" + branch = row.pr["branch"] + jobs.fence() # both the push of a re-created branch and the new PR are external effects + if ctx.git.branch_head(branch) != pinned: + ctx.git.recreate_branch(branch_request(ctx, row), row.pr.get("base") or "", pinned) + new = ctx.git.open_pr(branch, pinned, title_of(row), body_of(row)) + repo.event(row, "pr_reopened", "cmapi-bot", f"#{row.pr['number']} was closed; #{new.number} opened from the same branch", + {"old": row.pr["number"], "new": new.number}) + row.pr = {**row.pr, "number": new.number, "url": new.url, "head": new.head_sha} + return new + + +def _merged(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow, sha: str, adopted: bool) -> None: + """Fable 2.4, a gate on every path that records a merge (this job, a hand merge pr_checks or apply finds): the folder at + the merge sha must be the plan's. Then merged; after an apply also synced, since the read already confirmed it; otherwise + watch_sync. A merge whose folder is not the plan's, or with no sha to read, is merged and then sync_failed, with the lock + held for an operator: nothing is applied from it and a delete never waits for a prune of it (#449).""" + after_apply = row.status in AFTER_APPLY + unreadable: NotUtf8 | None = None + try: + on_main = ctx.git.tree_files(sha, folder(row.cluster_id, row.namespace)) if sha else None + fulfilled = on_main == planned(row) + if fulfilled and row.action == "delete": + # A delete's folder is empty at the merge: no file of any kind, at any depth, is left of it (#616). + fulfilled = not ctx.git.list_folder(folder(row.cluster_id, row.namespace), sha)[0] + except NotUtf8 as exc: + # The merge happened: a folder no plan can hold (#626) is not the plan's. Never retried into failed or merge_failed. + fulfilled, unreadable = False, exc + row.merge_sha = sha or None + how = "adopted: merged on the host" if adopted else "merged" + repo.event(row, "merge_verified", "worker", f"{how} {sha[:8]}; the folder at it {'is' if fulfilled else 'is not'} the plan's", + {"merge_sha": sha, "adopted": adopted}) + repo.move(row, E.MERGED, "cmapi-bot", f"{how} {sha[:8]}") + if not fulfilled: + why = f"the folder at the merge {sha[:8]} is not the approved plan" if sha else "the host gave no merge sha to check" + repo.move(row, E.SYNC_TIMEOUT, "worker", f"{why}: {unreadable}"[:240] if unreadable else why) + elif after_apply: + repo.move(row, E.SYNCED, "cmapi-deliverer", "applied and confirmed by a read before the merge") + approval = "auto" if (row.requirement or {}).get("auto") else "human" + LEAD_TIME.labels(row.plugin, row.action, approval).observe((datetime.now(timezone.utc) - row.created_at).total_seconds()) + else: + jobs.enqueue("watch_sync", request_id=row.request_id, cluster_id=row.cluster_id) + ctx.git.cleanup(row.cluster_id, row.request_id) + jobs.done(job) + jobs.enqueue("git_cleanup", request_id=row.request_id, cluster_id=row.cluster_id) diff --git a/cmapi/tests/service/conftest.py b/cmapi/tests/service/conftest.py index 1ce62b96..ad068cd3 100644 --- a/cmapi/tests/service/conftest.py +++ b/cmapi/tests/service/conftest.py @@ -1,549 +1,549 @@ -"""Fixtures for the service tests: a real PostgreSQL (CMAPI_TEST_DATABASE_URL, default the throwaway -postgres:16-alpine container on port 55432 named in CRC-BUILD-STATUS.md "Resume"; CI runs the same image -as a service), and fakes for the Git host, the cluster and the validator, so the pipeline, the routers -and the worker jobs run end to end without a cluster. - -The fakes implement the same contracts as the adapters (HostGitProvider, KubeClient) and keep -their state in memory; the tests below drive every lifecycle path through them. -""" -from __future__ import annotations - -import os -import re -import sys -import threading -import time -from contextlib import contextmanager -from datetime import datetime, timedelta, timezone -from pathlib import Path -from typing import Any, Iterator, Mapping - -import jwt -import pytest -from cryptography.hazmat.primitives import serialization -from cryptography.hazmat.primitives.asymmetric import rsa -from fastapi.testclient import TestClient -from sqlalchemy import text - -ROOT = Path(__file__).resolve().parents[2] -EXAMPLES = ROOT.parent / "examples" -sys.path.insert(0, str(ROOT / "src")) - -from cmapi.core.auth import Authenticator, Jwks # noqa: E402 -from cmapi.core.clients.kube import KubeClient, KubeError # noqa: E402 -from cmapi.core.context import build_context # noqa: E402 -from cmapi.core.db import Database # noqa: E402 -from cmapi.core.db.migrate import run as migrate # noqa: E402 -from cmapi.core.git.base import HostGitProvider # noqa: E402 -from cmapi.core.ports import Finding, PrRef, PrStatus # noqa: E402 -from cmapi.core.registry import ImportSource # noqa: E402 -from cmapi.main import create_app # noqa: E402 -from cmapi.core.ratelimit import DEFAULTS as RATE_LIMIT_CLASSES, Limit, RateLimiter # noqa: E402 -from cmapi.settings import Settings # noqa: E402 - -DB_URL = os.environ.get("CMAPI_TEST_DATABASE_URL", "postgresql://cmapi:cmapi@127.0.0.1:55432/cmapi") -ISSUER = "https://keycloak.test/realms/cmapi" -AUDIENCE = "cmapi-nonprod" - -# One session per database (#271). fresh_db truncates the request tables before each test, so a second session on the same -# database deletes this one's rows mid-test, and a test fails with a 404 that is not the code's. A session-level advisory -# lock, held on its own connection until the session ends, turns that into an immediate refusal that names the cause. -SESSION_LOCK_KEY = 0x636D617069 # "cmapi" in ASCII -SESSION_LOCK_EXIT = 75 # EX_TEMPFAIL of sysexits.h, "try again later": pytest's own codes are 0 to 5, and 3 is its internal error -_SESSION_LOCK = pytest.StashKey[Any]() -_SESSION_LOCK_TRIED = pytest.StashKey[bool]() - - -def _hold_the_database(session: pytest.Session) -> None: - import psycopg - - if session.config.stash.get(_SESSION_LOCK_TRIED, False): - return - session.config.stash[_SESSION_LOCK_TRIED] = True - # SQLAlchemy's form (postgresql+psycopg://) works for the app's engine; libpq wants the plain scheme. - conninfo = re.sub(r"^postgres(?:ql)?\+\w+://", "postgresql://", DB_URL) - try: - conn = psycopg.connect(conninfo, autocommit=True, connect_timeout=5) - except psycopg.Error: - # No database, or a URL libpq cannot read (its message quotes the URL, password and all, so it is not shown): the - # tests that need the database fail on their own, as they did before the lock. - return - if not conn.execute("select pg_try_advisory_lock(%s)", (SESSION_LOCK_KEY,)).fetchone()[0]: - where = f"{conn.info.host}:{conn.info.port}/{conn.info.dbname}" # from the connection: never the URL's credentials - conn.close() - pytest.exit(f"another service-test session holds the database {where} (advisory lock {SESSION_LOCK_KEY}): its fixtures " - "truncate the request tables, so two sessions would delete each other's rows. Wait for it to end, or set " - "CMAPI_TEST_DATABASE_URL to a database of your own.", returncode=SESSION_LOCK_EXIT) - session.config.stash[_SESSION_LOCK] = conn - - -def pytest_sessionstart(session: pytest.Session) -> None: - _hold_the_database(session) # before collection, when this file is an initial conftest (pytest tests/service, ...) - - -def pytest_collection_finish(session: pytest.Session) -> None: - # pytest calls pytest_sessionstart only for initial conftests. `pytest tests` from cmapi/ loads this file while collecting, - # after the session started, so the lock is taken here instead: still before any fixture or test runs. - _hold_the_database(session) - - -def pytest_sessionfinish(session: pytest.Session) -> None: - conn = session.config.stash.get(_SESSION_LOCK, None) - if conn is not None: - conn.close() # the advisory lock is the connection's: closing it releases the lock - - -# --------------------------------------------------------------------------- tokens - -class Keys: - def __init__(self): - self.private = rsa.generate_private_key(public_exponent=65537, key_size=2048) - self.kid = "test-kid-1" - pub = self.private.public_key() - self.jwk = {**jwt.algorithms.RSAAlgorithm.to_jwk(pub, as_dict=True), "kid": self.kid, "use": "sig", "alg": "RS256"} - self.pem = self.private.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, - serialization.NoEncryption()) - - def token(self, username: str, *, roles=(), groups=(), employee_id="1001", sub=None, aud=AUDIENCE, iss=ISSUER, - exp_in=300, client="cmapi-portal", extra: Mapping[str, Any] | None = None, kid=None, alg="RS256", - typ: str | None = "at+jwt") -> str: - """`typ` is the JOSE header: an access token of cmapi's realm has at+jwt (RFC 9068). None removes the header type.""" - now = int(time.time()) - claims = {"iss": iss, "aud": [aud, "account"], "sub": sub or f"sub-{username}", "azp": client, "iat": now, - "exp": now + exp_in, "preferred_username": username, "email": f"{username}@ephico2real.com", - "given_name": username.title(), "family_name": "Doe", "groups": list(groups), - "resource_access": {aud: {"roles": list(roles)}}} - if employee_id: - claims["employee_id"] = employee_id - claims.update(extra or {}) - headers = {"kid": kid or self.kid, "typ": typ} # PyJWT deletes a header typ that is None, and writes JWT when the key is absent - if alg == "none": - return jwt.encode(claims, key=None, algorithm="none", headers=headers) - return jwt.encode(claims, self.pem, algorithm=alg, headers=headers) - - -@pytest.fixture(scope="session") -def keys() -> Keys: - return Keys() - - -# --------------------------------------------------------------------------- fakes - -class FakeGit(HostGitProvider): - """An in-memory Git host: branches are dicts of files; a PR is a record with statuses.""" - - def __init__(self): - self.branches: dict[str, dict[str, str]] = {"main": {"README.md": "cluster-configs (test)\n"}} - self.heads: dict[str, str] = {"main": "a" * 40} - self.main_history: list[str] = ["a" * 40] - self.prs: dict[int, dict[str, Any]] = {} - self.statuses: dict[str, dict[str, str]] = {} - self.commits: list[str] = ["aaaaaaaa initial"] - self.based_on: dict[str, dict[str, str]] = {} - self.repository = "cmapi/cluster-configs-test" - self.default_branch = "main" - self.web_url = "https://git.test" - self.down = False - self.owners: dict[str, tuple[str, str]] = {} - self.based_on_sha: dict[str, str] = {} - self.pushes: list[str] = [] - self.submodules: set[str] = set() # paths whose entry is a submodule (a gitlink), for list_folder - - def _check(self): - if self.down: - from cmapi.core.git.base import GitUnavailable - raise GitUnavailable("fake git is down") - - def _sha(self, branch: str) -> str: - import hashlib - h = hashlib.sha1(("".join(sorted(f"{k}={v}" for k, v in self.branches[branch].items()))).encode()).hexdigest() - self.heads[branch] = h - if branch == "main": - self.main_history.append(h) - return h - - def branch_head(self, branch): - self._check() - return self.heads.get(branch) if branch in self.branches else None - - def _branch_of(self, ref): - self._check() - ref = ref or "main" - # Only a branch that still exists: a merged branch is deleted and its head stays in self.heads, and a later head with - # the same content has the same hash here (#154). - branch = ref if ref in self.branches else next((b for b, h in self.heads.items() if h == ref and b in self.branches), None) - if branch is None: - from cmapi.core.git.base import GitUnavailable - raise GitUnavailable(f"no branch {ref}") - return branch - - def read_folder(self, path, ref=None): - branch = self._branch_of(ref) - # The .yaml files directly in the folder, as github.py, gitea.py and workspace.py list one folder, not its subfolders (#578). - prefix = path.rstrip("/") + "/" - files = {p: t for p, t in self.branches[branch].items() - if p.startswith(prefix) and "/" not in p[len(prefix):] and p.endswith(".yaml")} - return files, self.heads[branch] - - def list_folder(self, path, ref=None): - """Every path under the folder, at any depth, as the real listings give it (#616). A path in submodules is one.""" - branch = self._branch_of(ref) - prefix = path.rstrip("/") + "/" - return ({p: ("commit" if p in self.submodules else "blob") for p in self.branches[branch] if p.startswith(prefix)}, - self.heads[branch]) - - def contains(self, revision, sha): - self._check() - history = self.main_history - return revision == sha or (revision in history and sha in history and history.index(sha) <= history.index(revision)) - - def changed_paths(self, head): - self._check() - branch = next(b for b, h in self.heads.items() if h == head and b in self.branches) # as in read_folder (#154) - before, after = self.based_on.get(branch, self.branches[branch]), self.branches[branch] - return {p for p in set(before) | set(after) if before.get(p) != after.get(p)} - - 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 None - - def push_request_branch(self, req): - """The Git layer's contract (#286), in memory: the branch from main with the plan's files. A branch that exists is - adopted when it is this request's with these files, replaced when it is this request's stale attempt, refused otherwise.""" - from cmapi.core.git.base import PushResult - from cmapi.core.git.workspace import BranchRefused, request_branch - - self._check() - branch = request_branch(req.cluster_id, req.request_id) - base = self.heads["main"] - want = dict(self.branches["main"]) - for p, t in req.files.items(): - if t is None: - want.pop(p, None) - else: - want[p] = t - if branch in self.branches: - owner = self.owners.get(branch) - if owner == (req.request_id, req.plan_hash) and self.branches[branch] == want: - return PushResult(self.heads[branch], self.based_on_sha.get(branch, base), "adopted") - if not owner or owner[0] != req.request_id: - raise BranchRefused(f"branch {branch} exists and its head is not cmapi's commit for {req.request_id}") - self.branches[branch] = want - self.based_on[branch] = dict(self.branches["main"]) - self.based_on_sha[branch] = base - self.owners[branch] = (req.request_id, req.plan_hash) - self.pushes.append(branch) - return PushResult(self._sha(branch), base, "created") - - def open_pr(self, branch, head, title, body): - self._check() - if (pr := self.find_pr(branch)) is not None: - return pr - assert branch in self.branches and self.heads[branch] == head, "PR opened on a head that is not the pushed one" - 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) - - def comment(self, pr, text): - self.prs[pr.number].setdefault("comments", []).append(text) - - def delete_branch(self, branch, expected): - if branch not in self.branches: - return True - if self.heads.get(branch) != expected: - return False - del self.branches[branch] - 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() - if p["state"] == "open" and p["branch"].startswith(prefix)] - - def list_branches(self, prefix): - return {b: self.heads[b] for b in self.branches if b.startswith(prefix)} - - def branch_time(self, sha): - return 0 - - def request_of(self, sha): - branch = next((b for b, h in self.heads.items() if h == sha and b in self.branches), None) - return (self.owners.get(branch) or (None,))[0] - - def pr_status(self, pr): - self._check() - p = self.prs[pr.number] - head = self.heads[pr.branch] if pr.branch in self.heads else pr.head_sha - checks = {k: ("success" if v == "success" else "pending" if v == "pending" else "failure") - for k, v in self.statuses.get(head, {}).items()} - return PrStatus(state=p["state"], checks=checks, merge_sha=p["merge_sha"], head_sha=head) - - def set_check(self, sha, context, state, description, target_url=None): - self._check() - self.statuses.setdefault(sha, {})[context] = state - - def merge(self, pr, expected_head): - self._check() - p = self.prs[pr.number] - assert self.heads[pr.branch] == expected_head, "head moved" - required = self.statuses.get(expected_head, {}) - assert all(required.get(c) == "success" for c in ("ci/kubeconform", "ci/kyverno", "cmapi/check")), "protection refused the merge" - base = self.based_on.get(pr.branch) - if base is None: - self.branches["main"] = dict(self.branches[pr.branch]) - else: - # A merge, as a host makes it: main keeps what it gained since the branch left it, and takes the branch's own - # changes. Copying the branch over main would drop a path added to main before the merge (#616). - merged, branch = dict(self.branches["main"]), self.branches[pr.branch] - for path in set(base) | set(branch): - if base.get(path) != branch.get(path): - if path in branch: - merged[path] = branch[path] - else: - merged.pop(path, None) - self.branches["main"] = merged - merge_sha = self._sha("main") - p["state"], p["merge_sha"] = "merged", merge_sha - self.commits.append(f"{merge_sha[:8]} Merge {pr.branch}") - del self.branches[pr.branch] - return merge_sha - - def close(self, pr, comment): - self.prs[pr.number]["state"] = "closed" - self.prs[pr.number]["comment"] = comment - - def log(self, n=20): - return list(reversed(self.commits))[:n] - - # test helper: a hand edit on the bot branch after approval - def tamper(self, branch: str, path: str, text: str) -> None: - self.branches[branch][path] = text - self._sha(branch) - - -class FakeKube(KubeClient): - """One cluster in memory: namespaces, quotas and limit ranges, applied by the deliverer. - - #302: `served_groups` is what API discovery serves (empty: Kyverno is not installed, as on CRC), `forbidden_kinds` the - kinds whose list answers 403, and `calls` each discovery and list call by kind, so a test can show that no call was made. - A list with `limit` pages by `continue`, as the API server does. - - The watch is silent by default: the suite's tests relist the cache (`_list`) where they need it current. A test that holds a - cache list across a change, and needs the change seen without a relist, sets `live_watch`: then each apply and delete is a - watch event (ADDED, MODIFIED, DELETED) after the resourceVersion the watch gives, as the API server serves one (#751).""" - - def __init__(self, cluster_id="CRC", identity="system:serviceaccount:cmapi-system:cmapi-reader"): - self.cluster_id, self.identity = cluster_id, identity - self.objects: dict[tuple[str, str, str], dict[str, Any]] = {} - self.rv = 1 - self.applied: list[str] = [] - self.unreachable = False - self.served_groups: set[str] = set() - self.forbidden_kinds: set[str] = set() - self.calls: list[str] = [] - self.live_watch = False - self._events: list[tuple[int, str, dict[str, Any]]] = [] # (resourceVersion, kind, event), only with live_watch - self._changed = threading.Condition() - - def close(self): - pass - - def _k(self, kind, ns, name): - return (kind, ns or "", name) - - def version(self): - if self.unreachable: - from cmapi.core.clients.kube import ClusterUnreachable - raise ClusterUnreachable("fake cluster down") - return "v1.35.6-fake" - - def whoami(self): - return self.identity - - def served(self, group_version): - self.calls.append(f"discovery {group_version}") - if self.unreachable: - from cmapi.core.clients.kube import ClusterUnreachable - raise ClusterUnreachable("fake cluster down") - return group_version in self.served_groups - - def list(self, kind, namespace=None, label_selector=None, resource_version=None, *, limit=None, continue_=None): - self.calls.append(kind) - if kind in self.forbidden_kinds: - raise KubeError(403, f"list {kind}", "forbidden") - items = [o for (k, ns, _), o in self.objects.items() if k == kind and (namespace is None or ns == namespace)] - if limit is None: - return {"items": items, "metadata": {"resourceVersion": str(self.rv)}} - items.sort(key=lambda o: (o["metadata"].get("namespace", ""), o["metadata"]["name"])) - start = int(continue_ or 0) - more = start + limit < len(items) - return {"items": items[start:start + limit], - "metadata": {"resourceVersion": str(self.rv), **({"continue": str(start + limit)} if more else {})}} - - def get_object(self, kind, namespace, name): - if kind in ("ServiceAccount", "RoleBinding"): - # The reader's grant: list, not get (deploy/manifests/environments/crc/reader/00-cmapi-reader.yaml, #748). - raise KubeError(403, f"get {kind}", "forbidden: the reader may list ServiceAccounts and RoleBindings, not get them") - return self.objects.get(self._k(kind, namespace, name)) - - def watch(self, kind, resource_version, timeout_seconds=300): - if not self.live_watch: - time.sleep(0.05) - return iter(()) - since = int(resource_version or 0) - - def due(): - return [ev for rv, k, ev in self._events if k == kind and rv > since] - - with self._changed: - self._changed.wait_for(due, timeout=0.05) - return iter(due()) - - def _emit(self, kind: str, kind_of_change: str, obj: dict[str, Any]) -> None: - """One watch event at the current resourceVersion, carried in the object's metadata as the API server sets it.""" - if not self.live_watch: - return - event = {"type": kind_of_change, "object": {**obj, "metadata": {**obj["metadata"], "resourceVersion": str(self.rv)}}} - with self._changed: - self._events.append((self.rv, kind, event)) - self._changed.notify_all() - - def apply(self, doc, field_manager="cmapi-deliverer"): - kind, meta = doc["kind"], doc["metadata"] - key = self._k(kind, meta.get("namespace"), meta["name"]) - obj = dict(doc) - if kind == "ResourceQuota": - obj = {**doc, "status": {"hard": dict(doc["spec"]["hard"]), "used": {k: "0" for k in doc["spec"]["hard"]}}} - if kind == "Namespace": - obj = {**doc, "status": {"phase": "Active"}} - obj["metadata"] = {**doc["metadata"], "creationTimestamp": datetime.now(timezone.utc).isoformat()} - existed = key in self.objects - self.objects[key] = obj - self.rv += 1 - self._emit(kind, "MODIFIED" if existed else "ADDED", obj) - self.applied.append(f"{kind}/{meta.get('namespace', '')}/{meta['name']}") - return obj - - def delete(self, kind, namespace, name): - obj = self.objects.pop(self._k(kind, namespace, name), None) - gone = [] if obj is None else [(kind, obj)] - if kind == "Namespace": - for key in [k for k in self.objects if k[1] == name]: - gone.append((key[0], self.objects.pop(key))) - self.rv += 1 - for k, o in gone: - self._emit(k, "DELETED", o) - - def add_unmanaged_namespace(self, name: str): - self.objects[self._k("Namespace", None, name)] = {"kind": "Namespace", "metadata": {"name": name, "labels": {}}} - - -class FakeValidator: - def __init__(self): - self.findings: list[Finding] = [] - self.calls = 0 - self.previous: list = [] # the previous folder that each call gave (#212: a held value is not refused) - self.held: list[Finding] = [] # the failures that a previous version holds, given to a caller that asks (#248) - - def validate(self, files, cluster_id, environment, previous=None, held=None): - self.calls += 1 - self.previous.append(previous) - if held is not None: - held.extend(self.held) - return list(self.findings) - - -class OneSecret(ImportSource): - def __init__(self, cluster_id="CRC"): - self.cluster_id = cluster_id - - def list(self): - return [{"name": "cmapi-cluster-crc", "labels": {"cmapi.net/secret-type": "cluster", "cmapi.net/cluster-id": self.cluster_id}, - "annotations": {}, "data": {"apiUrl": "https://fake.cluster:6443", "token": "fake-token-1234567890"}}] - - -# --------------------------------------------------------------------------- the app - -@pytest.fixture(scope="session") -def test_config(tmp_path_factory) -> Path: - d = tmp_path_factory.mktemp("config") - for name in ("instance.yaml", "approval-rules.yaml", "authz-roles.yaml", "tiers.yaml", "expiration.yaml"): - (d / name).write_text((EXAMPLES / "instances" / "nonprod" / name).read_text()) - (d / "metadata-keys.yaml").write_text((EXAMPLES / "cluster-configs" / "policies" / "metadata-keys.yaml").read_text()) - (d / "instance.yaml").write_text((d / "instance.yaml").read_text() - .replace("https://sso.ephico2real.com/realms/ephico2real", ISSUER) - .replace("repository: caas/cluster-configs-nonprod", "repository: cmapi/cluster-configs-test")) - (d / "clusters.yaml").write_text("clusters:\n CRC:\n environment: dev\n gitopsPath: clusters/CRC\n" - " labels: {region: us-central}\n simulatedCapacity: {cpu: 64, memory: 256Gi}\n") - (d / "capacity.yaml").write_text("overcommit:\n dev: {cpu: 2.0, memory: 1.25}\n rnd: {cpu: 2.0, memory: 1.25}\n" - "targets:\n dev: {commitment: {warn: 0.85, critical: 0.95}}\n rnd: {commitment: {warn: 0.85, critical: 0.95}}\n") - (d / "integrations.yaml").write_text("delivery:\n mode: apply\n syncTimeout: 30s\nsyncSignal:\n default: poll\n pollInterval: 1s\n") - return d - - -@pytest.fixture(scope="session") -def database() -> Database: - os.environ["CMAPI_DATABASE_URL"] = DB_URL - from cmapi.settings import settings - settings.cache_clear() - migrate(["head"]) - return Database(DB_URL) - - -@pytest.fixture -def fresh_db(database: Database) -> Database: - with database.engine.begin() as c: - # The usage tables of #310, and the operations tables of #26, are truncated where the migrations made them: a run of - # an older src (the before-run of a fix) migrates to its own head, without them. - usage = [t for t in ("analysis_sweeps", "namespace_verdicts", "capacity_snapshots", "capacity_reservations", - "operation_steps", "operations") - if c.execute(text("SELECT to_regclass(:t)"), {"t": t}).scalar() is not None] - c.execute(text("TRUNCATE change_requests, request_events, approvals, jobs, audit_events, admin_switches, " - "approval_notifications, expiration_notices, policy_rejections" - + "".join(f", {t}" for t in usage) + " RESTART IDENTITY CASCADE")) - return database - - -# The rate limits of the suite's worlds (#689): high enough that no test meets them. One test sends hundreds of calls a second -# as one person, which no client does; the instance's own limits are tested in test_rate_limits_689.py, which passes -# instance_rate_limits=True. -UNLIMITED = {kind: Limit(1e9, 10**9) for kind in RATE_LIMIT_CLASSES} - - -@contextmanager -def build_world(config_dir: Path, keys: Keys, monkeypatch, *, instance_rate_limits: bool = False): - """The app on one configuration folder, with fakes wired in: yields (client, ctx, git, kube, validator, keys).""" - git, kube, validator = FakeGit(), FakeKube(), FakeValidator() - monkeypatch.setenv("CMAPI_DATABASE_URL", DB_URL) - s = Settings(config_dir=config_dir, database_url=DB_URL, git_provider="gitea", git_url="https://git.test/api/v1", - git_token="t", cursor_key="k", link_key="l", metrics_port=0, imports_dir=None, - kube_token_file=Path("/nonexistent"), kube_ca_file=Path("/nonexistent")) - import cmapi.core.context as context_mod - monkeypatch.setattr(context_mod, "make_provider", lambda *a, **k: git) - monkeypatch.setattr(context_mod, "CliValidator", lambda *a, **k: validator) - ctx = build_context(s, start_registry=False, import_source=OneSecret()) - ctx.registry.client_factory = lambda *a, **k: kube - ctx.registry.start_caches = True - ctx.registry.refresh() - assert ctx.registry.clusters["CRC"].status == "connected", ctx.registry.clusters["CRC"].findings - ctx.registry.cache("CRC").wait_ready(5) - ctx.registry.clusters["CRC"].nodes.wait_ready(5) # #302: the node watch's first list, so no test races it - ctx.deliverer_factory = lambda cid: kube - ctx.auth = Authenticator(ISSUER, AUDIENCE, Jwks(ISSUER, "https://keycloak.test/certs", fetch=lambda url: [keys.jwk])) - if not instance_rate_limits: - ctx.limiter = RateLimiter(limits=dict(UNLIMITED)) - app = create_app(s, ctx) - try: - with TestClient(app) as client: - yield client, ctx, git, kube, validator, keys - finally: - ctx.registry.stop() - - -@pytest.fixture -def world(test_config: Path, fresh_db: Database, keys: Keys, monkeypatch): - """The app with fakes wired in: returns (client, ctx, git, kube, validator, keys).""" - with build_world(test_config, keys, monkeypatch) as w: - yield w +"""Fixtures for the service tests: a real PostgreSQL (CMAPI_TEST_DATABASE_URL, default the throwaway +postgres:16-alpine container on port 55432 named in CRC-BUILD-STATUS.md "Resume"; CI runs the same image +as a service), and fakes for the Git host, the cluster and the validator, so the pipeline, the routers +and the worker jobs run end to end without a cluster. + +The fakes implement the same contracts as the adapters (HostGitProvider, KubeClient) and keep +their state in memory; the tests below drive every lifecycle path through them. +""" +from __future__ import annotations + +import os +import re +import sys +import threading +import time +from contextlib import contextmanager +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Any, Iterator, Mapping + +import jwt +import pytest +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa +from fastapi.testclient import TestClient +from sqlalchemy import text + +ROOT = Path(__file__).resolve().parents[2] +EXAMPLES = ROOT.parent / "examples" +sys.path.insert(0, str(ROOT / "src")) + +from cmapi.core.auth import Authenticator, Jwks # noqa: E402 +from cmapi.core.clients.kube import KubeClient, KubeError # noqa: E402 +from cmapi.core.context import build_context # noqa: E402 +from cmapi.core.db import Database # noqa: E402 +from cmapi.core.db.migrate import run as migrate # noqa: E402 +from cmapi.core.git.base import HostGitProvider # noqa: E402 +from cmapi.core.ports import Finding, PrRef, PrStatus # noqa: E402 +from cmapi.core.registry import ImportSource # noqa: E402 +from cmapi.main import create_app # noqa: E402 +from cmapi.core.ratelimit import DEFAULTS as RATE_LIMIT_CLASSES, Limit, RateLimiter # noqa: E402 +from cmapi.settings import Settings # noqa: E402 + +DB_URL = os.environ.get("CMAPI_TEST_DATABASE_URL", "postgresql://cmapi:cmapi@127.0.0.1:55432/cmapi") +ISSUER = "https://keycloak.test/realms/cmapi" +AUDIENCE = "cmapi-nonprod" + +# One session per database (#271). fresh_db truncates the request tables before each test, so a second session on the same +# database deletes this one's rows mid-test, and a test fails with a 404 that is not the code's. A session-level advisory +# lock, held on its own connection until the session ends, turns that into an immediate refusal that names the cause. +SESSION_LOCK_KEY = 0x636D617069 # "cmapi" in ASCII +SESSION_LOCK_EXIT = 75 # EX_TEMPFAIL of sysexits.h, "try again later": pytest's own codes are 0 to 5, and 3 is its internal error +_SESSION_LOCK = pytest.StashKey[Any]() +_SESSION_LOCK_TRIED = pytest.StashKey[bool]() + + +def _hold_the_database(session: pytest.Session) -> None: + import psycopg + + if session.config.stash.get(_SESSION_LOCK_TRIED, False): + return + session.config.stash[_SESSION_LOCK_TRIED] = True + # SQLAlchemy's form (postgresql+psycopg://) works for the app's engine; libpq wants the plain scheme. + conninfo = re.sub(r"^postgres(?:ql)?\+\w+://", "postgresql://", DB_URL) + try: + conn = psycopg.connect(conninfo, autocommit=True, connect_timeout=5) + except psycopg.Error: + # No database, or a URL libpq cannot read (its message quotes the URL, password and all, so it is not shown): the + # tests that need the database fail on their own, as they did before the lock. + return + if not conn.execute("select pg_try_advisory_lock(%s)", (SESSION_LOCK_KEY,)).fetchone()[0]: + where = f"{conn.info.host}:{conn.info.port}/{conn.info.dbname}" # from the connection: never the URL's credentials + conn.close() + pytest.exit(f"another service-test session holds the database {where} (advisory lock {SESSION_LOCK_KEY}): its fixtures " + "truncate the request tables, so two sessions would delete each other's rows. Wait for it to end, or set " + "CMAPI_TEST_DATABASE_URL to a database of your own.", returncode=SESSION_LOCK_EXIT) + session.config.stash[_SESSION_LOCK] = conn + + +def pytest_sessionstart(session: pytest.Session) -> None: + _hold_the_database(session) # before collection, when this file is an initial conftest (pytest tests/service, ...) + + +def pytest_collection_finish(session: pytest.Session) -> None: + # pytest calls pytest_sessionstart only for initial conftests. `pytest tests` from cmapi/ loads this file while collecting, + # after the session started, so the lock is taken here instead: still before any fixture or test runs. + _hold_the_database(session) + + +def pytest_sessionfinish(session: pytest.Session) -> None: + conn = session.config.stash.get(_SESSION_LOCK, None) + if conn is not None: + conn.close() # the advisory lock is the connection's: closing it releases the lock + + +# --------------------------------------------------------------------------- tokens + +class Keys: + def __init__(self): + self.private = rsa.generate_private_key(public_exponent=65537, key_size=2048) + self.kid = "test-kid-1" + pub = self.private.public_key() + self.jwk = {**jwt.algorithms.RSAAlgorithm.to_jwk(pub, as_dict=True), "kid": self.kid, "use": "sig", "alg": "RS256"} + self.pem = self.private.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, + serialization.NoEncryption()) + + def token(self, username: str, *, roles=(), groups=(), employee_id="1001", sub=None, aud=AUDIENCE, iss=ISSUER, + exp_in=300, client="cmapi-portal", extra: Mapping[str, Any] | None = None, kid=None, alg="RS256", + typ: str | None = "at+jwt") -> str: + """`typ` is the JOSE header: an access token of cmapi's realm has at+jwt (RFC 9068). None removes the header type.""" + now = int(time.time()) + claims = {"iss": iss, "aud": [aud, "account"], "sub": sub or f"sub-{username}", "azp": client, "iat": now, + "exp": now + exp_in, "preferred_username": username, "email": f"{username}@ephico2real.com", + "given_name": username.title(), "family_name": "Doe", "groups": list(groups), + "resource_access": {aud: {"roles": list(roles)}}} + if employee_id: + claims["employee_id"] = employee_id + claims.update(extra or {}) + headers = {"kid": kid or self.kid, "typ": typ} # PyJWT deletes a header typ that is None, and writes JWT when the key is absent + if alg == "none": + return jwt.encode(claims, key=None, algorithm="none", headers=headers) + return jwt.encode(claims, self.pem, algorithm=alg, headers=headers) + + +@pytest.fixture(scope="session") +def keys() -> Keys: + return Keys() + + +# --------------------------------------------------------------------------- fakes + +class FakeGit(HostGitProvider): + """An in-memory Git host: branches are dicts of files; a PR is a record with statuses.""" + + def __init__(self): + self.branches: dict[str, dict[str, str]] = {"main": {"README.md": "cluster-configs (test)\n"}} + self.heads: dict[str, str] = {"main": "a" * 40} + self.main_history: list[str] = ["a" * 40] + self.prs: dict[int, dict[str, Any]] = {} + self.statuses: dict[str, dict[str, str]] = {} + self.commits: list[str] = ["aaaaaaaa initial"] + self.based_on: dict[str, dict[str, str]] = {} + self.repository = "cmapi/cluster-configs-test" + self.default_branch = "main" + self.web_url = "https://git.test" + self.down = False + self.owners: dict[str, tuple[str, str]] = {} + self.based_on_sha: dict[str, str] = {} + self.pushes: list[str] = [] + self.submodules: set[str] = set() # paths whose entry is a submodule (a gitlink), for list_folder + + def _check(self): + if self.down: + from cmapi.core.git.base import GitUnavailable + raise GitUnavailable("fake git is down") + + def _sha(self, branch: str) -> str: + import hashlib + h = hashlib.sha1(("".join(sorted(f"{k}={v}" for k, v in self.branches[branch].items()))).encode()).hexdigest() + self.heads[branch] = h + if branch == "main": + self.main_history.append(h) + return h + + def branch_head(self, branch): + self._check() + return self.heads.get(branch) if branch in self.branches else None + + def _branch_of(self, ref): + self._check() + ref = ref or "main" + # Only a branch that still exists: a merged branch is deleted and its head stays in self.heads, and a later head with + # the same content has the same hash here (#154). + branch = ref if ref in self.branches else next((b for b, h in self.heads.items() if h == ref and b in self.branches), None) + if branch is None: + from cmapi.core.git.base import GitUnavailable + raise GitUnavailable(f"no branch {ref}") + return branch + + def read_folder(self, path, ref=None): + branch = self._branch_of(ref) + # The .yaml files directly in the folder, as github.py, gitea.py and workspace.py list one folder, not its subfolders (#578). + prefix = path.rstrip("/") + "/" + files = {p: t for p, t in self.branches[branch].items() + if p.startswith(prefix) and "/" not in p[len(prefix):] and p.endswith(".yaml")} + return files, self.heads[branch] + + def list_folder(self, path, ref=None): + """Every path under the folder, at any depth, as the real listings give it (#616). A path in submodules is one.""" + branch = self._branch_of(ref) + prefix = path.rstrip("/") + "/" + return ({p: ("commit" if p in self.submodules else "blob") for p in self.branches[branch] if p.startswith(prefix)}, + self.heads[branch]) + + def contains(self, revision, sha): + self._check() + history = self.main_history + return revision == sha or (revision in history and sha in history and history.index(sha) <= history.index(revision)) + + def changed_paths(self, head): + self._check() + branch = next(b for b, h in self.heads.items() if h == head and b in self.branches) # as in read_folder (#154) + before, after = self.based_on.get(branch, self.branches[branch]), self.branches[branch] + return {p for p in set(before) | set(after) if before.get(p) != after.get(p)} + + 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 None + + def push_request_branch(self, req): + """The Git layer's contract (#286), in memory: the branch from main with the plan's files. A branch that exists is + adopted when it is this request's with these files, replaced when it is this request's stale attempt, refused otherwise.""" + from cmapi.core.git.base import PushResult + from cmapi.core.git.workspace import BranchRefused, request_branch + + self._check() + branch = request_branch(req.cluster_id, req.request_id) + base = self.heads["main"] + want = dict(self.branches["main"]) + for p, t in req.files.items(): + if t is None: + want.pop(p, None) + else: + want[p] = t + if branch in self.branches: + owner = self.owners.get(branch) + if owner == (req.request_id, req.plan_hash) and self.branches[branch] == want: + return PushResult(self.heads[branch], self.based_on_sha.get(branch, base), "adopted") + if not owner or owner[0] != req.request_id: + raise BranchRefused(f"branch {branch} exists and its head is not cmapi's commit for {req.request_id}") + self.branches[branch] = want + self.based_on[branch] = dict(self.branches["main"]) + self.based_on_sha[branch] = base + self.owners[branch] = (req.request_id, req.plan_hash) + self.pushes.append(branch) + return PushResult(self._sha(branch), base, "created") + + def open_pr(self, branch, head, title, body): + self._check() + if (pr := self.find_pr(branch)) is not None: + return pr + assert branch in self.branches and self.heads[branch] == head, "PR opened on a head that is not the pushed one" + 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) + + def comment(self, pr, text): + self.prs[pr.number].setdefault("comments", []).append(text) + + def delete_branch(self, branch, expected): + if branch not in self.branches: + return True + if self.heads.get(branch) != expected: + return False + del self.branches[branch] + 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() + if p["state"] == "open" and p["branch"].startswith(prefix)] + + def list_branches(self, prefix): + return {b: self.heads[b] for b in self.branches if b.startswith(prefix)} + + def branch_time(self, sha): + return 0 + + def request_of(self, sha): + branch = next((b for b, h in self.heads.items() if h == sha and b in self.branches), None) + return (self.owners.get(branch) or (None,))[0] + + def pr_status(self, pr, *, ci=True): + self._check() + p = self.prs[pr.number] + head = self.heads[pr.branch] if pr.branch in self.heads else pr.head_sha + checks = {k: ("success" if v == "success" else "pending" if v == "pending" else "failure") + for k, v in self.statuses.get(head, {}).items()} + return PrStatus(state=p["state"], checks=checks, merge_sha=p["merge_sha"], head_sha=head) + + def set_check(self, sha, context, state, description, target_url=None): + self._check() + self.statuses.setdefault(sha, {})[context] = state + + def merge(self, pr, expected_head): + self._check() + p = self.prs[pr.number] + assert self.heads[pr.branch] == expected_head, "head moved" + required = self.statuses.get(expected_head, {}) + assert all(required.get(c) == "success" for c in ("ci/kubeconform", "ci/kyverno", "cmapi/check")), "protection refused the merge" + base = self.based_on.get(pr.branch) + if base is None: + self.branches["main"] = dict(self.branches[pr.branch]) + else: + # A merge, as a host makes it: main keeps what it gained since the branch left it, and takes the branch's own + # changes. Copying the branch over main would drop a path added to main before the merge (#616). + merged, branch = dict(self.branches["main"]), self.branches[pr.branch] + for path in set(base) | set(branch): + if base.get(path) != branch.get(path): + if path in branch: + merged[path] = branch[path] + else: + merged.pop(path, None) + self.branches["main"] = merged + merge_sha = self._sha("main") + p["state"], p["merge_sha"] = "merged", merge_sha + self.commits.append(f"{merge_sha[:8]} Merge {pr.branch}") + del self.branches[pr.branch] + return merge_sha + + def close(self, pr, comment): + self.prs[pr.number]["state"] = "closed" + self.prs[pr.number]["comment"] = comment + + def log(self, n=20): + return list(reversed(self.commits))[:n] + + # test helper: a hand edit on the bot branch after approval + def tamper(self, branch: str, path: str, text: str) -> None: + self.branches[branch][path] = text + self._sha(branch) + + +class FakeKube(KubeClient): + """One cluster in memory: namespaces, quotas and limit ranges, applied by the deliverer. + + #302: `served_groups` is what API discovery serves (empty: Kyverno is not installed, as on CRC), `forbidden_kinds` the + kinds whose list answers 403, and `calls` each discovery and list call by kind, so a test can show that no call was made. + A list with `limit` pages by `continue`, as the API server does. + + The watch is silent by default: the suite's tests relist the cache (`_list`) where they need it current. A test that holds a + cache list across a change, and needs the change seen without a relist, sets `live_watch`: then each apply and delete is a + watch event (ADDED, MODIFIED, DELETED) after the resourceVersion the watch gives, as the API server serves one (#751).""" + + def __init__(self, cluster_id="CRC", identity="system:serviceaccount:cmapi-system:cmapi-reader"): + self.cluster_id, self.identity = cluster_id, identity + self.objects: dict[tuple[str, str, str], dict[str, Any]] = {} + self.rv = 1 + self.applied: list[str] = [] + self.unreachable = False + self.served_groups: set[str] = set() + self.forbidden_kinds: set[str] = set() + self.calls: list[str] = [] + self.live_watch = False + self._events: list[tuple[int, str, dict[str, Any]]] = [] # (resourceVersion, kind, event), only with live_watch + self._changed = threading.Condition() + + def close(self): + pass + + def _k(self, kind, ns, name): + return (kind, ns or "", name) + + def version(self): + if self.unreachable: + from cmapi.core.clients.kube import ClusterUnreachable + raise ClusterUnreachable("fake cluster down") + return "v1.35.6-fake" + + def whoami(self): + return self.identity + + def served(self, group_version): + self.calls.append(f"discovery {group_version}") + if self.unreachable: + from cmapi.core.clients.kube import ClusterUnreachable + raise ClusterUnreachable("fake cluster down") + return group_version in self.served_groups + + def list(self, kind, namespace=None, label_selector=None, resource_version=None, *, limit=None, continue_=None): + self.calls.append(kind) + if kind in self.forbidden_kinds: + raise KubeError(403, f"list {kind}", "forbidden") + items = [o for (k, ns, _), o in self.objects.items() if k == kind and (namespace is None or ns == namespace)] + if limit is None: + return {"items": items, "metadata": {"resourceVersion": str(self.rv)}} + items.sort(key=lambda o: (o["metadata"].get("namespace", ""), o["metadata"]["name"])) + start = int(continue_ or 0) + more = start + limit < len(items) + return {"items": items[start:start + limit], + "metadata": {"resourceVersion": str(self.rv), **({"continue": str(start + limit)} if more else {})}} + + def get_object(self, kind, namespace, name): + if kind in ("ServiceAccount", "RoleBinding"): + # The reader's grant: list, not get (deploy/manifests/environments/crc/reader/00-cmapi-reader.yaml, #748). + raise KubeError(403, f"get {kind}", "forbidden: the reader may list ServiceAccounts and RoleBindings, not get them") + return self.objects.get(self._k(kind, namespace, name)) + + def watch(self, kind, resource_version, timeout_seconds=300): + if not self.live_watch: + time.sleep(0.05) + return iter(()) + since = int(resource_version or 0) + + def due(): + return [ev for rv, k, ev in self._events if k == kind and rv > since] + + with self._changed: + self._changed.wait_for(due, timeout=0.05) + return iter(due()) + + def _emit(self, kind: str, kind_of_change: str, obj: dict[str, Any]) -> None: + """One watch event at the current resourceVersion, carried in the object's metadata as the API server sets it.""" + if not self.live_watch: + return + event = {"type": kind_of_change, "object": {**obj, "metadata": {**obj["metadata"], "resourceVersion": str(self.rv)}}} + with self._changed: + self._events.append((self.rv, kind, event)) + self._changed.notify_all() + + def apply(self, doc, field_manager="cmapi-deliverer"): + kind, meta = doc["kind"], doc["metadata"] + key = self._k(kind, meta.get("namespace"), meta["name"]) + obj = dict(doc) + if kind == "ResourceQuota": + obj = {**doc, "status": {"hard": dict(doc["spec"]["hard"]), "used": {k: "0" for k in doc["spec"]["hard"]}}} + if kind == "Namespace": + obj = {**doc, "status": {"phase": "Active"}} + obj["metadata"] = {**doc["metadata"], "creationTimestamp": datetime.now(timezone.utc).isoformat()} + existed = key in self.objects + self.objects[key] = obj + self.rv += 1 + self._emit(kind, "MODIFIED" if existed else "ADDED", obj) + self.applied.append(f"{kind}/{meta.get('namespace', '')}/{meta['name']}") + return obj + + def delete(self, kind, namespace, name): + obj = self.objects.pop(self._k(kind, namespace, name), None) + gone = [] if obj is None else [(kind, obj)] + if kind == "Namespace": + for key in [k for k in self.objects if k[1] == name]: + gone.append((key[0], self.objects.pop(key))) + self.rv += 1 + for k, o in gone: + self._emit(k, "DELETED", o) + + def add_unmanaged_namespace(self, name: str): + self.objects[self._k("Namespace", None, name)] = {"kind": "Namespace", "metadata": {"name": name, "labels": {}}} + + +class FakeValidator: + def __init__(self): + self.findings: list[Finding] = [] + self.calls = 0 + self.previous: list = [] # the previous folder that each call gave (#212: a held value is not refused) + self.held: list[Finding] = [] # the failures that a previous version holds, given to a caller that asks (#248) + + def validate(self, files, cluster_id, environment, previous=None, held=None): + self.calls += 1 + self.previous.append(previous) + if held is not None: + held.extend(self.held) + return list(self.findings) + + +class OneSecret(ImportSource): + def __init__(self, cluster_id="CRC"): + self.cluster_id = cluster_id + + def list(self): + return [{"name": "cmapi-cluster-crc", "labels": {"cmapi.net/secret-type": "cluster", "cmapi.net/cluster-id": self.cluster_id}, + "annotations": {}, "data": {"apiUrl": "https://fake.cluster:6443", "token": "fake-token-1234567890"}}] + + +# --------------------------------------------------------------------------- the app + +@pytest.fixture(scope="session") +def test_config(tmp_path_factory) -> Path: + d = tmp_path_factory.mktemp("config") + for name in ("instance.yaml", "approval-rules.yaml", "authz-roles.yaml", "tiers.yaml", "expiration.yaml"): + (d / name).write_text((EXAMPLES / "instances" / "nonprod" / name).read_text()) + (d / "metadata-keys.yaml").write_text((EXAMPLES / "cluster-configs" / "policies" / "metadata-keys.yaml").read_text()) + (d / "instance.yaml").write_text((d / "instance.yaml").read_text() + .replace("https://sso.ephico2real.com/realms/ephico2real", ISSUER) + .replace("repository: caas/cluster-configs-nonprod", "repository: cmapi/cluster-configs-test")) + (d / "clusters.yaml").write_text("clusters:\n CRC:\n environment: dev\n gitopsPath: clusters/CRC\n" + " labels: {region: us-central}\n simulatedCapacity: {cpu: 64, memory: 256Gi}\n") + (d / "capacity.yaml").write_text("overcommit:\n dev: {cpu: 2.0, memory: 1.25}\n rnd: {cpu: 2.0, memory: 1.25}\n" + "targets:\n dev: {commitment: {warn: 0.85, critical: 0.95}}\n rnd: {commitment: {warn: 0.85, critical: 0.95}}\n") + (d / "integrations.yaml").write_text("delivery:\n mode: apply\n syncTimeout: 30s\nsyncSignal:\n default: poll\n pollInterval: 1s\n") + return d + + +@pytest.fixture(scope="session") +def database() -> Database: + os.environ["CMAPI_DATABASE_URL"] = DB_URL + from cmapi.settings import settings + settings.cache_clear() + migrate(["head"]) + return Database(DB_URL) + + +@pytest.fixture +def fresh_db(database: Database) -> Database: + with database.engine.begin() as c: + # The usage tables of #310, and the operations tables of #26, are truncated where the migrations made them: a run of + # an older src (the before-run of a fix) migrates to its own head, without them. + usage = [t for t in ("analysis_sweeps", "namespace_verdicts", "capacity_snapshots", "capacity_reservations", + "operation_steps", "operations") + if c.execute(text("SELECT to_regclass(:t)"), {"t": t}).scalar() is not None] + c.execute(text("TRUNCATE change_requests, request_events, approvals, jobs, audit_events, admin_switches, " + "approval_notifications, expiration_notices, policy_rejections" + + "".join(f", {t}" for t in usage) + " RESTART IDENTITY CASCADE")) + return database + + +# The rate limits of the suite's worlds (#689): high enough that no test meets them. One test sends hundreds of calls a second +# as one person, which no client does; the instance's own limits are tested in test_rate_limits_689.py, which passes +# instance_rate_limits=True. +UNLIMITED = {kind: Limit(1e9, 10**9) for kind in RATE_LIMIT_CLASSES} + + +@contextmanager +def build_world(config_dir: Path, keys: Keys, monkeypatch, *, instance_rate_limits: bool = False): + """The app on one configuration folder, with fakes wired in: yields (client, ctx, git, kube, validator, keys).""" + git, kube, validator = FakeGit(), FakeKube(), FakeValidator() + monkeypatch.setenv("CMAPI_DATABASE_URL", DB_URL) + s = Settings(config_dir=config_dir, database_url=DB_URL, git_provider="gitea", git_url="https://git.test/api/v1", + git_token="t", cursor_key="k", link_key="l", metrics_port=0, imports_dir=None, + kube_token_file=Path("/nonexistent"), kube_ca_file=Path("/nonexistent")) + import cmapi.core.context as context_mod + monkeypatch.setattr(context_mod, "make_provider", lambda *a, **k: git) + monkeypatch.setattr(context_mod, "CliValidator", lambda *a, **k: validator) + ctx = build_context(s, start_registry=False, import_source=OneSecret()) + ctx.registry.client_factory = lambda *a, **k: kube + ctx.registry.start_caches = True + ctx.registry.refresh() + assert ctx.registry.clusters["CRC"].status == "connected", ctx.registry.clusters["CRC"].findings + ctx.registry.cache("CRC").wait_ready(5) + ctx.registry.clusters["CRC"].nodes.wait_ready(5) # #302: the node watch's first list, so no test races it + ctx.deliverer_factory = lambda cid: kube + ctx.auth = Authenticator(ISSUER, AUDIENCE, Jwks(ISSUER, "https://keycloak.test/certs", fetch=lambda url: [keys.jwk])) + if not instance_rate_limits: + ctx.limiter = RateLimiter(limits=dict(UNLIMITED)) + app = create_app(s, ctx) + try: + with TestClient(app) as client: + yield client, ctx, git, kube, validator, keys + finally: + ctx.registry.stop() + + +@pytest.fixture +def world(test_config: Path, fresh_db: Database, keys: Keys, monkeypatch): + """The app with fakes wired in: returns (client, ctx, git, kube, validator, keys).""" + with build_world(test_config, keys, monkeypatch) as w: + yield w diff --git a/cmapi/tests/service/test_github_actions_ci.py b/cmapi/tests/service/test_github_actions_ci.py index 5a20a892..40c43a62 100644 --- a/cmapi/tests/service/test_github_actions_ci.py +++ b/cmapi/tests/service/test_github_actions_ci.py @@ -1,331 +1,340 @@ -"""GitHub's PR adapter reads host CI from the config repository's Actions: the workflow jobs of the PR head, by name, through -the Actions API (#60). Not the commit statuses, which the bot's own token can post, and not the Checks API, which a -fine-grained token cannot call (BUG-69, #279). Host CI is on by default. The provider runs on a MockTransport shaped by GitHub's -REST docs, "Workflow runs" and "Workflow jobs" (fetched 2026-12-01), and by the answers measured on cmapi-cluster-configs that -day (run 45649310281: jobs ci/kubeconform and ci/kyverno, each the check run of the same name and id, app github-actions).""" -from __future__ import annotations - -import httpx -import pytest - -from cmapi.core.git.base import GitUnavailable, IncompleteList -from cmapi.core.git.github import GitHubProvider -from cmapi.core.ports import PrRef -from cmapi.jobs.pr_checks import CONTEXT_KUBECONFORM, CONTEXT_KYVERNO - -SHA = "c" * 40 -API = "https://github.test" -PR = PrRef(7, "https://github.test/o/r/pull/7", "cmapi/CRC/r1", SHA) -RUNS = "/repos/o/r/actions/runs" -RUN_LOOKUP = "/repos/o/r/actions/workflows/ci.yml/runs" - - -def run_of(run_id=1, **fields): - """One pull_request run of this PR as GitHub lists it. pull_requests is empty, as measured on cmapi-cluster-configs.""" - return {"id": run_id, "run_attempt": 1, "head_sha": SHA, "event": "pull_request", "head_branch": PR.branch, - "head_repository": {"full_name": "o/r"}, "pull_requests": [], **fields} - - -def job(name, conclusion="success", status="completed"): - return {"name": name, "status": status, "conclusion": conclusion, "head_sha": SHA} - - -def paged(request, key, items): - per_page, page = min(int(request.url.params.get("per_page", 30)), 100), int(request.url.params.get("page", 1)) - chunk = items[(page - 1) * per_page:page * per_page] - headers = {} - if page * per_page < len(items): - headers["Link"] = f'<{API}{request.url.path}?per_page={per_page}&page={page + 1}>; rel="next"' - return httpx.Response(200, json={"total_count": len(items), key: chunk}, headers=headers) - - -def provider(runs=None, *, seen=None, pr=None, on_runs=None, on_jobs=None, **kw): - """runs: {run id: [jobs]} on SHA.""" - runs = {1: [job(CONTEXT_KUBECONFORM), job(CONTEXT_KYVERNO)]} if runs is None else runs - - def handle(request): - if seen is not None: - seen.append(request) - path = request.url.path - assert "check-runs" not in path and "check-suites" not in path, "the Checks API is never called" - assert "/status" not in path, "a commit status is never read as CI: the bot's token can post one (#60)" - if path == "/repos/o/r/pulls/7": - return httpx.Response(200, json=pr or {"state": "open", "merged": False, "head": {"sha": SHA, "ref": PR.branch}}) - if path in (RUN_LOOKUP, RUNS): - if on_runs: - return on_runs(request) - assert request.url.params["head_sha"] == SHA - return paged(request, "workflow_runs", [run_of(i) for i in runs]) - if path.startswith(RUNS + "/") and path.endswith("/jobs"): - if on_jobs: - return on_jobs(request) - assert request.url.params["filter"] == "latest", "a re-run's newest attempt alone" - return paged(request, "jobs", runs[int(path.split("/")[-2])]) - if path.startswith(RUNS + "/") and path.split("/")[-1].isdigit(): - return httpx.Response(200, json={"run_attempt": 1}) - return httpx.Response(404, json={"message": f"not routed: {path}"}) - git = GitHubProvider(API, "o/r", "token", **kw) - git._client = httpx.Client(base_url=API, transport=httpx.MockTransport(handle)) - return git - - -def checks(**kw): - return dict(provider(**kw).pr_status(PR).checks) - - -def test_host_ci_is_on_by_default_and_the_worker_posts_cmapi_check_alone(): - git = GitHubProvider(API, "o/r", "token") - assert (git.external_ci, git.post_statuses, git.posts_ci) == (True, True, False) - - -def test_host_ci_off_reads_nothing_and_posts_nothing(): - seen = [] - git = provider(seen=seen, host_checks=False) - assert git.pr_status(PR).checks == {} and not git.external_ci and not git.post_statuses and not git.posts_ci - assert [r.url.path for r in seen] == ["/repos/o/r/pulls/7"] - - -def test_post_status_without_host_ci_still_posts_no_ci_context(): - git = GitHubProvider(API, "o/r", "token", host_checks=False, post_status=True) - assert git.post_statuses and not git.posts_ci and not git.external_ci - - -def test_the_two_jobs_of_the_workflow_read_as_the_two_ci_contexts(): - assert checks() == {CONTEXT_KUBECONFORM: "success", CONTEXT_KYVERNO: "success"} - - -@pytest.mark.parametrize("status,conclusion,expected", [ - ("completed", "success", "success"), - ("completed", "failure", "failure"), - ("completed", "cancelled", "failure"), - ("completed", "timed_out", "failure"), - ("completed", "action_required", "failure"), - ("completed", "skipped", "failure"), # validated nothing: not a pass here, though branch protection passes it - ("completed", "neutral", "failure"), - ("completed", None, "pending"), # completed before its conclusion is there (#87, e6300b8c) - ("queued", None, "pending"), - ("in_progress", None, "pending"), - ("waiting", None, "pending"), - ("requested", None, "pending"), - ("pending", None, "pending"), - ("in_progress", "success", "pending"), # unfinished, whatever the conclusion field says -]) -def test_each_job_state_reads_as_a_check_state(status, conclusion, expected): - assert checks(runs={1: [job(CONTEXT_KYVERNO, conclusion, status)]}) == {CONTEXT_KYVERNO: expected} - - -@pytest.mark.parametrize("other", ["success", "failure"]) -def test_one_name_in_two_runs_of_the_ci_workflow_reads_as_the_worse(other): - got = checks(runs={1: [job(CONTEXT_KYVERNO, "failure")], 2: [job(CONTEXT_KYVERNO, other)]}) - assert got == {CONTEXT_KYVERNO: "failure"} - - -def test_a_name_that_no_job_carries_is_not_invented(): - assert checks(runs={1: [job(CONTEXT_KUBECONFORM)]}) == {CONTEXT_KUBECONFORM: "success"} - assert checks(runs={}) == {} - - -def test_a_run_of_another_commit_says_nothing_about_this_one(): - def runs(request): - return paged(request, "workflow_runs", [run_of(head_sha="d" * 40)]) - - def jobs(request): - raise AssertionError("the jobs of another commit's run are not read") - assert checks(on_runs=runs, on_jobs=jobs) == {} - - -def test_it_asks_for_the_runs_of_the_pr_head_and_the_latest_attempt_of_each_job(): - seen = [] - provider(seen=seen).pr_status(PR) - runs = [r for r in seen if r.url.path == RUN_LOOKUP] - jobs = [r for r in seen if r.url.path.endswith("/jobs")] - assert [r.url.params["head_sha"] for r in runs] == [SHA] - assert [(r.url.path, r.url.params["filter"]) for r in jobs] == [(f"{RUNS}/1/jobs", "latest")] - - -def test_a_failure_on_a_later_page_of_jobs_counts(): - got = checks(runs={1: [job(f"other-{i}") for i in range(150)] + [job(CONTEXT_KYVERNO, "failure")]}) - assert len(got) == 151 and got[CONTEXT_KYVERNO] == "failure" - - -def test_a_run_on_a_later_page_of_runs_is_read(): - runs = {i: [] for i in range(1, 151)} - runs[150] = [job(CONTEXT_KYVERNO, "failure")] - assert checks(runs=runs) == {CONTEXT_KYVERNO: "failure"} - - -def test_as_many_runs_as_github_can_list_for_one_commit_is_not_read_as_complete(): - """"This endpoint will return up to 1,000 results for each search when using ... head_sha" (REST docs, 2026-12-01).""" - with pytest.raises(IncompleteList, match="1000"): - provider(runs={i: [] for i in range(1, 1001)}).pr_status(PR) - - -def test_the_next_link_is_a_signal_and_is_never_followed_to_another_host(): - """The Authorization header goes with every request on this client, so a URL from a response is never called.""" - seen = [] - - def evil(request): - if request.url.params.get("page", "1") == "1": - return httpx.Response(200, json={"workflow_runs": []}, headers={"Link": '; rel="next"'}) - return httpx.Response(200, json={"workflow_runs": []}) - provider(on_runs=evil, seen=seen).pr_status(PR) - assert {r.url.host for r in seen} == {"github.test"} - - -def test_a_host_that_never_stops_paging_is_an_error_not_a_partial_read(): - calls = [] - - def endless(request): - calls.append(request) - return httpx.Response(200, json={"jobs": [job(CONTEXT_KYVERNO)]}, headers={"Link": f'<{API}/x?page=9>; rel="next"'}) - with pytest.raises(GitUnavailable, match="pages"): - provider(on_jobs=endless).pr_status(PR) - assert len(calls) == GitHubProvider.MAX_PAGES - - -@pytest.mark.parametrize("which", ["runs", "jobs"]) -@pytest.mark.parametrize("code", [401, 403, 404, 422]) -def test_a_refused_read_raises_instead_of_reading_as_no_ci(code, which): - """403 is what a token without Actions read gets ("Resource not accessible by personal access token", #279): the request - records it at each attempt and fails, never a wait read as CI that has not reported.""" - refuse = lambda r: httpx.Response(code, json={"message": "Resource not accessible by personal access token"}) # noqa: E731 - with pytest.raises(GitUnavailable, match=f"{code}.*Resource not accessible"): - provider(**{f"on_{which}": refuse}).pr_status(PR) - - -@pytest.mark.parametrize("code", [429, 502]) -def test_a_5xx_or_429_is_retryable(code): - with pytest.raises(GitUnavailable): - provider(on_runs=lambda r: httpx.Response(code, text="busy")).pr_status(PR) - - -def test_a_refused_later_page_of_runs_raises(): - def runs(request): - if request.url.params.get("page", "1") == "1": - return httpx.Response(200, json={"workflow_runs": [{"id": 1, "head_sha": SHA}]}, - headers={"Link": f'<{API}{request.url.path}?page=2>; rel="next"'}) - return httpx.Response(403, json={"message": "Resource not accessible"}) - with pytest.raises(GitUnavailable, match="403"): - provider(on_runs=runs).pr_status(PR) - - -@pytest.mark.parametrize("pr,state,merge_sha", [ - ({"state": "closed", "merged": True, "merge_commit_sha": "d" * 40, "head": {"sha": SHA}}, "merged", "d" * 40), - ({"state": "closed", "merged": False, "merge_commit_sha": "e" * 40, "head": {"sha": SHA}}, "closed", None), -]) -def test_a_finished_pr_needs_no_read_of_its_ci(pr, state, merge_sha): - got = provider(pr=pr, on_runs=lambda r: httpx.Response(403, json={"message": "no"})).pr_status(PR) - assert (got.state, got.merge_sha, dict(got.checks), got.head_sha) == (state, merge_sha, {}, SHA) - - -def test_ci_run_lookup_identifies_the_workflow_event_and_head(): - seen = [] - provider(runs={}, seen=seen).pr_status(PR) - request, = [r for r in seen if "/actions/" in r.url.path] - assert request.url.path == "/repos/o/r/actions/workflows/ci.yml/runs" - assert dict(request.url.params) == {"head_sha": SHA, "event": "pull_request", "per_page": "100", "page": "1"} - - -@pytest.mark.parametrize("fields", [ - {"event": "push"}, - {"head_branch": "cmapi/CRC/r2"}, # another branch at the same commit - {"head_branch": None}, - {"head_repository": {"full_name": "fork/r"}}, # a fork's PR on the same commit and branch name - {"head_repository": None}, # the fork was deleted - {"head_repository": {"full_name": "fork/r"}, "pull_requests": [{"number": PR.number}]}, -], ids=["push", "another-branch", "no-branch", "fork", "no-repository", "fork-listing-this-pr"]) -def test_a_run_that_is_not_this_pull_requests_is_not_inspected(fields): - def jobs(request): - pytest.fail("requested the jobs of a run that is not this PR's") - - got = checks(on_runs=lambda request: httpx.Response(200, json={"total_count": 1, "workflow_runs": [run_of(**fields)]}), - on_jobs=jobs) - assert got == {} - - -@pytest.mark.parametrize("pull_requests", [[], None, [{"number": 8}]], ids=["empty", "null", "another-number"]) -def test_this_prs_run_is_credited_whatever_pull_requests_holds(pull_requests): - """pull_requests lists open PRs that match by head_sha or head_branch, "not necessarily" the one that triggered the run - (github/rest-api-description, fetched 2026-12-01), and it was [] on every pull_request run measured on - cmapi-cluster-configs that day. The run's repository, branch, commit, event and workflow identify it.""" - got = checks(on_runs=lambda request: httpx.Response(200, json={ - "total_count": 1, "workflow_runs": [run_of(pull_requests=pull_requests)]})) - assert got == {CONTEXT_KUBECONFORM: "success", CONTEXT_KYVERNO: "success"} - - -def test_the_repository_name_is_compared_without_case(): - got = checks(on_runs=lambda request: httpx.Response(200, json={ - "total_count": 1, "workflow_runs": [run_of(head_repository={"full_name": "O/R"})]})) - assert got == {CONTEXT_KUBECONFORM: "success", CONTEXT_KYVERNO: "success"} - - -@pytest.mark.parametrize("observed", ["d" * 40, None]) -def test_ci_lookup_requires_the_open_pr_to_report_the_approved_head(observed): - def runs(request): - pytest.fail("requested CI without a matching approved head") - - state = provider(pr={"state": "open", "head": {"sha": observed}}, on_runs=runs).pr_status(PR) - assert state.head_sha == observed - assert state.checks == {} - - -def test_a_rerun_during_job_pagination_discards_the_read(): - seen_pages = [] - - def handle(request): - path = request.url.path - if path.endswith("/pulls/7"): - return httpx.Response(200, json={"state": "open", "head": {"sha": SHA}}) - if path.endswith("/runs"): - return paged(request, "workflow_runs", [run_of()]) - if path.endswith("/1/jobs"): - seen_pages.append(int(request.url.params["page"])) - return paged(request, "jobs", [job(f"lint-{i}") for i in range(101)]) - assert path == RUNS + "/1" - return httpx.Response(200, json={"id": 1, "run_attempt": 2}) - - git = GitHubProvider(API, "o/r", "token") - git._client = httpx.Client(base_url=API, transport=httpx.MockTransport(handle)) - assert git.pr_status(PR).checks == {} - assert seen_pages == [1, 2] - - -def test_a_list_answer_without_its_key_reads_as_empty(): - assert checks(on_runs=lambda request: httpx.Response(200, json={"total_count": 0})) == {} - - -def test_the_ci_workflow_file_is_ci_yml_unless_configured(): - from cmapi.core.git import make_provider - - assert GitHubProvider(API, "o/r", "token").ci_workflow == "ci.yml" - assert make_provider("github", API, "o/r", "token").ci_workflow == "ci.yml" - assert make_provider("github", API, "o/r", "token", ci_workflow="validate.yaml").ci_workflow == "validate.yaml" - seen = [] - - def handle(request): - seen.append(request.url.path) - if request.url.path == "/repos/o/r/pulls/7": - return httpx.Response(200, json={"state": "open", "merged": False, "head": {"sha": SHA, "ref": PR.branch}}) - if request.url.path == "/repos/o/r/actions/workflows/validate.yaml/runs": - return httpx.Response(200, json={"total_count": 1, "workflow_runs": [run_of(5)]}) - if request.url.path == RUNS + "/5/jobs": - return httpx.Response(200, json={"total_count": 1, "jobs": [job(CONTEXT_KYVERNO)]}) - return httpx.Response(404, json={"message": "Not Found"}) - - git = GitHubProvider(API, "o/r", "token", ci_workflow="validate.yaml") - git._client = httpx.Client(base_url=API, transport=httpx.MockTransport(handle)) - assert dict(git.pr_status(PR).checks) == {CONTEXT_KYVERNO: "success"} - assert "/repos/o/r/actions/workflows/validate.yaml/runs" in seen and RUN_LOOKUP not in seen - - -@pytest.mark.parametrize("value,ok", [("ci.yml", True), ("validate.yaml", True), (None, True), - (".github/workflows/ci.yml", False), ("ci", False), ("../ci.yml", False), - ("ci.yml?event=push", False), ("", False), (7, False), (True, False)]) -def test_the_configured_ci_workflow_is_a_file_name(value, ok): - """GET .../actions/workflows/{workflow_id}/runs takes "the workflow file name" (REST docs, fetched 2026-12-01): one path - segment. A path, or text that would change the URL, stops the start.""" - from cmapi.core.config import _git_problems - - problems = _git_problems({} if value is None else {"ciWorkflow": value}) - assert (problems == []) is ok, problems - assert ok or "git.ciWorkflow" in problems[0] +"""GitHub's PR adapter reads host CI from the config repository's Actions: the workflow jobs of the PR head, by name, through +the Actions API (#60). Not the commit statuses, which the bot's own token can post, and not the Checks API, which a +fine-grained token cannot call (BUG-69, #279). Host CI is on by default. The provider runs on a MockTransport shaped by GitHub's +REST docs, "Workflow runs" and "Workflow jobs" (fetched 2026-12-01), and by the answers measured on cmapi-cluster-configs that +day (run 45649310281: jobs ci/kubeconform and ci/kyverno, each the check run of the same name and id, app github-actions).""" +from __future__ import annotations + +import httpx +import pytest + +from cmapi.core.git.base import GitUnavailable, IncompleteList +from cmapi.core.git.github import GitHubProvider +from cmapi.core.ports import PrRef +from cmapi.jobs.pr_checks import CONTEXT_KUBECONFORM, CONTEXT_KYVERNO + +SHA = "c" * 40 +API = "https://github.test" +PR = PrRef(7, "https://github.test/o/r/pull/7", "cmapi/CRC/r1", SHA) +RUNS = "/repos/o/r/actions/runs" +RUN_LOOKUP = "/repos/o/r/actions/workflows/ci.yml/runs" + + +def run_of(run_id=1, **fields): + """One pull_request run of this PR as GitHub lists it. pull_requests is empty, as measured on cmapi-cluster-configs.""" + return {"id": run_id, "run_attempt": 1, "head_sha": SHA, "event": "pull_request", "head_branch": PR.branch, + "head_repository": {"full_name": "o/r"}, "pull_requests": [], **fields} + + +def job(name, conclusion="success", status="completed"): + return {"name": name, "status": status, "conclusion": conclusion, "head_sha": SHA} + + +def paged(request, key, items): + per_page, page = min(int(request.url.params.get("per_page", 30)), 100), int(request.url.params.get("page", 1)) + chunk = items[(page - 1) * per_page:page * per_page] + headers = {} + if page * per_page < len(items): + headers["Link"] = f'<{API}{request.url.path}?per_page={per_page}&page={page + 1}>; rel="next"' + return httpx.Response(200, json={"total_count": len(items), key: chunk}, headers=headers) + + +def provider(runs=None, *, seen=None, pr=None, on_runs=None, on_jobs=None, **kw): + """runs: {run id: [jobs]} on SHA.""" + runs = {1: [job(CONTEXT_KUBECONFORM), job(CONTEXT_KYVERNO)]} if runs is None else runs + + def handle(request): + if seen is not None: + seen.append(request) + path = request.url.path + assert "check-runs" not in path and "check-suites" not in path, "the Checks API is never called" + assert "/status" not in path, "a commit status is never read as CI: the bot's token can post one (#60)" + if path == "/repos/o/r/pulls/7": + return httpx.Response(200, json=pr or {"state": "open", "merged": False, "head": {"sha": SHA, "ref": PR.branch}}) + if path in (RUN_LOOKUP, RUNS): + if on_runs: + return on_runs(request) + assert request.url.params["head_sha"] == SHA + return paged(request, "workflow_runs", [run_of(i) for i in runs]) + if path.startswith(RUNS + "/") and path.endswith("/jobs"): + if on_jobs: + return on_jobs(request) + assert request.url.params["filter"] == "latest", "a re-run's newest attempt alone" + return paged(request, "jobs", runs[int(path.split("/")[-2])]) + if path.startswith(RUNS + "/") and path.split("/")[-1].isdigit(): + return httpx.Response(200, json={"run_attempt": 1}) + return httpx.Response(404, json={"message": f"not routed: {path}"}) + git = GitHubProvider(API, "o/r", "token", **kw) + git._client = httpx.Client(base_url=API, transport=httpx.MockTransport(handle)) + return git + + +def checks(**kw): + return dict(provider(**kw).pr_status(PR).checks) + + +def test_state_only_read_skips_the_actions_api(): + seen = [] + + status = provider(seen=seen).pr_status(PR, ci=False) + + assert status.state == "open" and status.checks == {} + assert [r.url.path for r in seen] == ["/repos/o/r/pulls/7"] + + +def test_host_ci_is_on_by_default_and_the_worker_posts_cmapi_check_alone(): + git = GitHubProvider(API, "o/r", "token") + assert (git.external_ci, git.post_statuses, git.posts_ci) == (True, True, False) + + +def test_host_ci_off_reads_nothing_and_posts_nothing(): + seen = [] + git = provider(seen=seen, host_checks=False) + assert git.pr_status(PR).checks == {} and not git.external_ci and not git.post_statuses and not git.posts_ci + assert [r.url.path for r in seen] == ["/repos/o/r/pulls/7"] + + +def test_post_status_without_host_ci_still_posts_no_ci_context(): + git = GitHubProvider(API, "o/r", "token", host_checks=False, post_status=True) + assert git.post_statuses and not git.posts_ci and not git.external_ci + + +def test_the_two_jobs_of_the_workflow_read_as_the_two_ci_contexts(): + assert checks() == {CONTEXT_KUBECONFORM: "success", CONTEXT_KYVERNO: "success"} + + +@pytest.mark.parametrize("status,conclusion,expected", [ + ("completed", "success", "success"), + ("completed", "failure", "failure"), + ("completed", "cancelled", "failure"), + ("completed", "timed_out", "failure"), + ("completed", "action_required", "failure"), + ("completed", "skipped", "failure"), # validated nothing: not a pass here, though branch protection passes it + ("completed", "neutral", "failure"), + ("completed", None, "pending"), # completed before its conclusion is there (#87, e6300b8c) + ("queued", None, "pending"), + ("in_progress", None, "pending"), + ("waiting", None, "pending"), + ("requested", None, "pending"), + ("pending", None, "pending"), + ("in_progress", "success", "pending"), # unfinished, whatever the conclusion field says +]) +def test_each_job_state_reads_as_a_check_state(status, conclusion, expected): + assert checks(runs={1: [job(CONTEXT_KYVERNO, conclusion, status)]}) == {CONTEXT_KYVERNO: expected} + + +@pytest.mark.parametrize("other", ["success", "failure"]) +def test_one_name_in_two_runs_of_the_ci_workflow_reads_as_the_worse(other): + got = checks(runs={1: [job(CONTEXT_KYVERNO, "failure")], 2: [job(CONTEXT_KYVERNO, other)]}) + assert got == {CONTEXT_KYVERNO: "failure"} + + +def test_a_name_that_no_job_carries_is_not_invented(): + assert checks(runs={1: [job(CONTEXT_KUBECONFORM)]}) == {CONTEXT_KUBECONFORM: "success"} + assert checks(runs={}) == {} + + +def test_a_run_of_another_commit_says_nothing_about_this_one(): + def runs(request): + return paged(request, "workflow_runs", [run_of(head_sha="d" * 40)]) + + def jobs(request): + raise AssertionError("the jobs of another commit's run are not read") + assert checks(on_runs=runs, on_jobs=jobs) == {} + + +def test_it_asks_for_the_runs_of_the_pr_head_and_the_latest_attempt_of_each_job(): + seen = [] + provider(seen=seen).pr_status(PR) + runs = [r for r in seen if r.url.path == RUN_LOOKUP] + jobs = [r for r in seen if r.url.path.endswith("/jobs")] + assert [r.url.params["head_sha"] for r in runs] == [SHA] + assert [(r.url.path, r.url.params["filter"]) for r in jobs] == [(f"{RUNS}/1/jobs", "latest")] + + +def test_a_failure_on_a_later_page_of_jobs_counts(): + got = checks(runs={1: [job(f"other-{i}") for i in range(150)] + [job(CONTEXT_KYVERNO, "failure")]}) + assert len(got) == 151 and got[CONTEXT_KYVERNO] == "failure" + + +def test_a_run_on_a_later_page_of_runs_is_read(): + runs = {i: [] for i in range(1, 151)} + runs[150] = [job(CONTEXT_KYVERNO, "failure")] + assert checks(runs=runs) == {CONTEXT_KYVERNO: "failure"} + + +def test_as_many_runs_as_github_can_list_for_one_commit_is_not_read_as_complete(): + """"This endpoint will return up to 1,000 results for each search when using ... head_sha" (REST docs, 2026-12-01).""" + with pytest.raises(IncompleteList, match="1000"): + provider(runs={i: [] for i in range(1, 1001)}).pr_status(PR) + + +def test_the_next_link_is_a_signal_and_is_never_followed_to_another_host(): + """The Authorization header goes with every request on this client, so a URL from a response is never called.""" + seen = [] + + def evil(request): + if request.url.params.get("page", "1") == "1": + return httpx.Response(200, json={"workflow_runs": []}, headers={"Link": '; rel="next"'}) + return httpx.Response(200, json={"workflow_runs": []}) + provider(on_runs=evil, seen=seen).pr_status(PR) + assert {r.url.host for r in seen} == {"github.test"} + + +def test_a_host_that_never_stops_paging_is_an_error_not_a_partial_read(): + calls = [] + + def endless(request): + calls.append(request) + return httpx.Response(200, json={"jobs": [job(CONTEXT_KYVERNO)]}, headers={"Link": f'<{API}/x?page=9>; rel="next"'}) + with pytest.raises(GitUnavailable, match="pages"): + provider(on_jobs=endless).pr_status(PR) + assert len(calls) == GitHubProvider.MAX_PAGES + + +@pytest.mark.parametrize("which", ["runs", "jobs"]) +@pytest.mark.parametrize("code", [401, 403, 404, 422]) +def test_a_refused_read_raises_instead_of_reading_as_no_ci(code, which): + """403 is what a token without Actions read gets ("Resource not accessible by personal access token", #279): the request + records it at each attempt and fails, never a wait read as CI that has not reported.""" + refuse = lambda r: httpx.Response(code, json={"message": "Resource not accessible by personal access token"}) # noqa: E731 + with pytest.raises(GitUnavailable, match=f"{code}.*Resource not accessible"): + provider(**{f"on_{which}": refuse}).pr_status(PR) + + +@pytest.mark.parametrize("code", [429, 502]) +def test_a_5xx_or_429_is_retryable(code): + with pytest.raises(GitUnavailable): + provider(on_runs=lambda r: httpx.Response(code, text="busy")).pr_status(PR) + + +def test_a_refused_later_page_of_runs_raises(): + def runs(request): + if request.url.params.get("page", "1") == "1": + return httpx.Response(200, json={"workflow_runs": [{"id": 1, "head_sha": SHA}]}, + headers={"Link": f'<{API}{request.url.path}?page=2>; rel="next"'}) + return httpx.Response(403, json={"message": "Resource not accessible"}) + with pytest.raises(GitUnavailable, match="403"): + provider(on_runs=runs).pr_status(PR) + + +@pytest.mark.parametrize("pr,state,merge_sha", [ + ({"state": "closed", "merged": True, "merge_commit_sha": "d" * 40, "head": {"sha": SHA}}, "merged", "d" * 40), + ({"state": "closed", "merged": False, "merge_commit_sha": "e" * 40, "head": {"sha": SHA}}, "closed", None), +]) +def test_a_finished_pr_needs_no_read_of_its_ci(pr, state, merge_sha): + got = provider(pr=pr, on_runs=lambda r: httpx.Response(403, json={"message": "no"})).pr_status(PR) + assert (got.state, got.merge_sha, dict(got.checks), got.head_sha) == (state, merge_sha, {}, SHA) + + +def test_ci_run_lookup_identifies_the_workflow_event_and_head(): + seen = [] + provider(runs={}, seen=seen).pr_status(PR) + request, = [r for r in seen if "/actions/" in r.url.path] + assert request.url.path == "/repos/o/r/actions/workflows/ci.yml/runs" + assert dict(request.url.params) == {"head_sha": SHA, "event": "pull_request", "per_page": "100", "page": "1"} + + +@pytest.mark.parametrize("fields", [ + {"event": "push"}, + {"head_branch": "cmapi/CRC/r2"}, # another branch at the same commit + {"head_branch": None}, + {"head_repository": {"full_name": "fork/r"}}, # a fork's PR on the same commit and branch name + {"head_repository": None}, # the fork was deleted + {"head_repository": {"full_name": "fork/r"}, "pull_requests": [{"number": PR.number}]}, +], ids=["push", "another-branch", "no-branch", "fork", "no-repository", "fork-listing-this-pr"]) +def test_a_run_that_is_not_this_pull_requests_is_not_inspected(fields): + def jobs(request): + pytest.fail("requested the jobs of a run that is not this PR's") + + got = checks(on_runs=lambda request: httpx.Response(200, json={"total_count": 1, "workflow_runs": [run_of(**fields)]}), + on_jobs=jobs) + assert got == {} + + +@pytest.mark.parametrize("pull_requests", [[], None, [{"number": 8}]], ids=["empty", "null", "another-number"]) +def test_this_prs_run_is_credited_whatever_pull_requests_holds(pull_requests): + """pull_requests lists open PRs that match by head_sha or head_branch, "not necessarily" the one that triggered the run + (github/rest-api-description, fetched 2026-12-01), and it was [] on every pull_request run measured on + cmapi-cluster-configs that day. The run's repository, branch, commit, event and workflow identify it.""" + got = checks(on_runs=lambda request: httpx.Response(200, json={ + "total_count": 1, "workflow_runs": [run_of(pull_requests=pull_requests)]})) + assert got == {CONTEXT_KUBECONFORM: "success", CONTEXT_KYVERNO: "success"} + + +def test_the_repository_name_is_compared_without_case(): + got = checks(on_runs=lambda request: httpx.Response(200, json={ + "total_count": 1, "workflow_runs": [run_of(head_repository={"full_name": "O/R"})]})) + assert got == {CONTEXT_KUBECONFORM: "success", CONTEXT_KYVERNO: "success"} + + +@pytest.mark.parametrize("observed", ["d" * 40, None]) +def test_ci_lookup_requires_the_open_pr_to_report_the_approved_head(observed): + def runs(request): + pytest.fail("requested CI without a matching approved head") + + state = provider(pr={"state": "open", "head": {"sha": observed}}, on_runs=runs).pr_status(PR) + assert state.head_sha == observed + assert state.checks == {} + + +def test_a_rerun_during_job_pagination_discards_the_read(): + seen_pages = [] + + def handle(request): + path = request.url.path + if path.endswith("/pulls/7"): + return httpx.Response(200, json={"state": "open", "head": {"sha": SHA}}) + if path.endswith("/runs"): + return paged(request, "workflow_runs", [run_of()]) + if path.endswith("/1/jobs"): + seen_pages.append(int(request.url.params["page"])) + return paged(request, "jobs", [job(f"lint-{i}") for i in range(101)]) + assert path == RUNS + "/1" + return httpx.Response(200, json={"id": 1, "run_attempt": 2}) + + git = GitHubProvider(API, "o/r", "token") + git._client = httpx.Client(base_url=API, transport=httpx.MockTransport(handle)) + assert git.pr_status(PR).checks == {} + assert seen_pages == [1, 2] + + +def test_a_list_answer_without_its_key_reads_as_empty(): + assert checks(on_runs=lambda request: httpx.Response(200, json={"total_count": 0})) == {} + + +def test_the_ci_workflow_file_is_ci_yml_unless_configured(): + from cmapi.core.git import make_provider + + assert GitHubProvider(API, "o/r", "token").ci_workflow == "ci.yml" + assert make_provider("github", API, "o/r", "token").ci_workflow == "ci.yml" + assert make_provider("github", API, "o/r", "token", ci_workflow="validate.yaml").ci_workflow == "validate.yaml" + seen = [] + + def handle(request): + seen.append(request.url.path) + if request.url.path == "/repos/o/r/pulls/7": + return httpx.Response(200, json={"state": "open", "merged": False, "head": {"sha": SHA, "ref": PR.branch}}) + if request.url.path == "/repos/o/r/actions/workflows/validate.yaml/runs": + return httpx.Response(200, json={"total_count": 1, "workflow_runs": [run_of(5)]}) + if request.url.path == RUNS + "/5/jobs": + return httpx.Response(200, json={"total_count": 1, "jobs": [job(CONTEXT_KYVERNO)]}) + return httpx.Response(404, json={"message": "Not Found"}) + + git = GitHubProvider(API, "o/r", "token", ci_workflow="validate.yaml") + git._client = httpx.Client(base_url=API, transport=httpx.MockTransport(handle)) + assert dict(git.pr_status(PR).checks) == {CONTEXT_KYVERNO: "success"} + assert "/repos/o/r/actions/workflows/validate.yaml/runs" in seen and RUN_LOOKUP not in seen + + +@pytest.mark.parametrize("value,ok", [("ci.yml", True), ("validate.yaml", True), (None, True), + (".github/workflows/ci.yml", False), ("ci", False), ("../ci.yml", False), + ("ci.yml?event=push", False), ("", False), (7, False), (True, False)]) +def test_the_configured_ci_workflow_is_a_file_name(value, ok): + """GET .../actions/workflows/{workflow_id}/runs takes "the workflow file name" (REST docs, fetched 2026-12-01): one path + segment. A path, or text that would change the URL, stops the start.""" + from cmapi.core.config import _git_problems + + problems = _git_problems({} if value is None else {"ciWorkflow": value}) + assert (problems == []) is ok, problems + assert ok or "git.ciWorkflow" in problems[0] From 51c010a790136d498038acbc191c9dd3c5e0c05a Mon Sep 17 00:00:00 2001 From: Arthur Araujo da Silva <164519555+BlackYuriJDU@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:17:05 +0000 Subject: [PATCH 2/3] style: restore LF line endings in the files this PR changes The previous commit rewrote the eight changed files with CRLF line endings, so the diff showed about 2,500 changed lines for a change of about 20. The repository uses LF. Convert the files back; the content does not change. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_012fbGqictriLD4EWAf37sNa --- cmapi/src/cmapi.egg-info/PKG-INFO | 22 + cmapi/src/cmapi.egg-info/SOURCES.txt | 164 +++ cmapi/src/cmapi.egg-info/dependency_links.txt | 1 + cmapi/src/cmapi.egg-info/entry_points.txt | 5 + cmapi/src/cmapi.egg-info/requires.txt | 18 + cmapi/src/cmapi.egg-info/top_level.txt | 1 + cmapi/src/cmapi/core/git/base.py | 774 ++++++------ cmapi/src/cmapi/core/git/gitea.py | 632 +++++----- cmapi/src/cmapi/core/git/github.py | 736 +++++------ cmapi/src/cmapi/core/ports.py | 462 +++---- cmapi/src/cmapi/jobs/apply.py | 340 ++--- cmapi/src/cmapi/jobs/merge.py | 334 ++--- cmapi/tests/service/conftest.py | 1098 ++++++++--------- cmapi/tests/service/test_github_actions_ci.py | 680 +++++----- 14 files changed, 2739 insertions(+), 2528 deletions(-) create mode 100644 cmapi/src/cmapi.egg-info/PKG-INFO create mode 100644 cmapi/src/cmapi.egg-info/SOURCES.txt create mode 100644 cmapi/src/cmapi.egg-info/dependency_links.txt create mode 100644 cmapi/src/cmapi.egg-info/entry_points.txt create mode 100644 cmapi/src/cmapi.egg-info/requires.txt create mode 100644 cmapi/src/cmapi.egg-info/top_level.txt diff --git a/cmapi/src/cmapi.egg-info/PKG-INFO b/cmapi/src/cmapi.egg-info/PKG-INFO new file mode 100644 index 00000000..88ad8078 --- /dev/null +++ b/cmapi/src/cmapi.egg-info/PKG-INFO @@ -0,0 +1,22 @@ +Metadata-Version: 2.4 +Name: cmapi +Version: 0.2.0 +Summary: cmapi: one API and portal for namespaces across OpenShift clusters, with every write a pull request +Requires-Python: >=3.12 +Requires-Dist: fastapi==0.162.2 +Requires-Dist: starlette==1.10.0 +Requires-Dist: uvicorn[standard]==0.32.1 +Requires-Dist: pydantic==2.14.2 +Requires-Dist: pydantic-settings==2.16.2 +Requires-Dist: sqlalchemy==2.1.8 +Requires-Dist: psycopg[binary]==3.3.8 +Requires-Dist: alembic==1.20.1 +Requires-Dist: httpx==0.28.1 +Requires-Dist: pyjwt[crypto]==2.15.1 +Requires-Dist: pyyaml==6.0.2 +Requires-Dist: google-re2==1.1.20251105 +Requires-Dist: prometheus-client==0.24.1 +Requires-Dist: structlog==26.1.0 +Provides-Extra: test +Requires-Dist: pytest==9.2.0; extra == "test" +Requires-Dist: jsonschema==4.26.0; extra == "test" diff --git a/cmapi/src/cmapi.egg-info/SOURCES.txt b/cmapi/src/cmapi.egg-info/SOURCES.txt new file mode 100644 index 00000000..3fecec99 --- /dev/null +++ b/cmapi/src/cmapi.egg-info/SOURCES.txt @@ -0,0 +1,164 @@ +pyproject.toml +src/cmapi/__init__.py +src/cmapi/main.py +src/cmapi/settings.py +src/cmapi/worker.py +src/cmapi.egg-info/PKG-INFO +src/cmapi.egg-info/SOURCES.txt +src/cmapi.egg-info/dependency_links.txt +src/cmapi.egg-info/entry_points.txt +src/cmapi.egg-info/requires.txt +src/cmapi.egg-info/top_level.txt +src/cmapi/capacity/__init__.py +src/cmapi/capacity/snapshots.py +src/cmapi/capacity/sweep.py +src/cmapi/capacity/thanos.py +src/cmapi/capacity/usage.py +src/cmapi/capacity/verdicts.py +src/cmapi/contract/__init__.py +src/cmapi/contract/changelog.json +src/cmapi/contract/samples.json +src/cmapi/core/__init__.py +src/cmapi/core/adoption.py +src/cmapi/core/approvals.py +src/cmapi/core/auth.py +src/cmapi/core/authz.py +src/cmapi/core/bodylimit.py +src/cmapi/core/capacity.py +src/cmapi/core/capacity_backend.py +src/cmapi/core/capacity_ledger.py +src/cmapi/core/changelog.py +src/cmapi/core/channels.py +src/cmapi/core/cluster_tokens.py +src/cmapi/core/clustertls.py +src/cmapi/core/config.py +src/cmapi/core/configfile.py +src/cmapi/core/context.py +src/cmapi/core/cors.py +src/cmapi/core/docs.py +src/cmapi/core/errors.py +src/cmapi/core/etag.py +src/cmapi/core/expression.py +src/cmapi/core/giturl.py +src/cmapi/core/http_settings.py +src/cmapi/core/kpi.py +src/cmapi/core/kube_yaml.py +src/cmapi/core/lifecycle.py +src/cmapi/core/listquery.py +src/cmapi/core/metadata.py +src/cmapi/core/models.py +src/cmapi/core/naming.py +src/cmapi/core/observability.py +src/cmapi/core/operations.py +src/cmapi/core/pipeline.py +src/cmapi/core/placement.py +src/cmapi/core/plan_read.py +src/cmapi/core/plugins.py +src/cmapi/core/policy.py +src/cmapi/core/policybundle.py +src/cmapi/core/policygen.py +src/cmapi/core/ports.py +src/cmapi/core/problem_docs.py +src/cmapi/core/ratelimit.py +src/cmapi/core/registry.py +src/cmapi/core/rejections.py +src/cmapi/core/sync.py +src/cmapi/core/tiers.py +src/cmapi/core/views.py +src/cmapi/core/clients/__init__.py +src/cmapi/core/clients/kube.py +src/cmapi/core/clients/nodes.py +src/cmapi/core/clients/policyreports.py +src/cmapi/core/clients/redact.py +src/cmapi/core/clients/trust.py +src/cmapi/core/db/__init__.py +src/cmapi/core/db/alembic.ini +src/cmapi/core/db/migrate.py +src/cmapi/core/db/models.py +src/cmapi/core/db/repo.py +src/cmapi/core/db/migrations/env.py +src/cmapi/core/db/migrations/versions/0001_cmapi_schema.py +src/cmapi/core/db/migrations/versions/0002_one_approval_per_person.py +src/cmapi/core/db/migrations/versions/0003_job_lease_generation.py +src/cmapi/core/db/migrations/versions/0004_approval_counted_for.py +src/cmapi/core/db/migrations/versions/0005_applied_and_merge_failed_hold_the_lock.py +src/cmapi/core/db/migrations/versions/0006_policy_rejections.py +src/cmapi/core/db/migrations/versions/0007_request_event_clock_timestamp.py +src/cmapi/core/db/migrations/versions/0008_idempotency_key_of_the_caller.py +src/cmapi/core/db/migrations/versions/0009_idempotency_key_of_the_caller_only.py +src/cmapi/core/db/migrations/versions/0010_usage_verdicts.py +src/cmapi/core/db/migrations/versions/0011_capacity_reservations.py +src/cmapi/core/db/migrations/versions/0012_capacity_snapshots_and_placements.py +src/cmapi/core/db/migrations/versions/0013_operations.py +src/cmapi/core/db/migrations/versions/0014_approval_decision.py +src/cmapi/core/git/__init__.py +src/cmapi/core/git/base.py +src/cmapi/core/git/gitea.py +src/cmapi/core/git/github.py +src/cmapi/core/git/oplog.py +src/cmapi/core/git/transport.py +src/cmapi/core/git/workspace.py +src/cmapi/core/identity/__init__.py +src/cmapi/core/identity/checks.py +src/cmapi/core/identity/claims.py +src/cmapi/core/identity/directory.py +src/cmapi/core/identity/keycloak_admin.py +src/cmapi/core/render/__init__.py +src/cmapi/core/render/manifests.py +src/cmapi/core/validate/__init__.py +src/cmapi/jobs/__init__.py +src/cmapi/jobs/apply.py +src/cmapi/jobs/approval_timeout.py +src/cmapi/jobs/capacity_snapshot.py +src/cmapi/jobs/channel_notify.py +src/cmapi/jobs/delivery.py +src/cmapi/jobs/expire_check.py +src/cmapi/jobs/git_cleanup.py +src/cmapi/jobs/git_reconcile.py +src/cmapi/jobs/merge.py +src/cmapi/jobs/open_pr.py +src/cmapi/jobs/pr_checks.py +src/cmapi/jobs/push_branch.py +src/cmapi/jobs/rejections_prune.py +src/cmapi/jobs/token_renew.py +src/cmapi/jobs/usage_sweep.py +src/cmapi/jobs/watch_sync.py +src/cmapi/ops/__init__.py +src/cmapi/ops/templates/cluster-onboard.yaml +src/cmapi/ops/templates/rebuild-verify.yaml +src/cmapi/ops/templates/reconcile.yaml +src/cmapi/ops/templates/tiers-rerender.yaml +src/cmapi/plugins/__init__.py +src/cmapi/plugins/adoption/__init__.py +src/cmapi/plugins/adoption/router.py +src/cmapi/plugins/capacity/__init__.py +src/cmapi/plugins/capacity/placement.py +src/cmapi/plugins/capacity/router.py +src/cmapi/plugins/directory/__init__.py +src/cmapi/plugins/expiration/__init__.py +src/cmapi/plugins/expiration/router.py +src/cmapi/plugins/expiration/rules.py +src/cmapi/plugins/namespaces/__init__.py +src/cmapi/plugins/namespaces/router.py +src/cmapi/plugins/namespaces/state.py +src/cmapi/plugins/policies/__init__.py +src/cmapi/plugins/policies/router.py +src/cmapi/plugins/quotas/__init__.py +src/cmapi/plugins/tiers/__init__.py +src/cmapi/routers/__init__.py +src/cmapi/routers/admin.py +src/cmapi/routers/health.py +src/cmapi/routers/me.py +src/cmapi/routers/operations.py +src/cmapi/routers/requests.py +src/cmapi/tools/__init__.py +src/cmapi/tools/docs_assets.py +src/cmapi/tools/git_bootstrap.py +src/cmapi/tools/openapi.py +src/cmapi/tools/policies.py +src/cmapi/tools/realm_sync.py +src/cmapi/tools/reference_instance/approval-rules.yaml +src/cmapi/tools/reference_instance/authz-roles.yaml +src/cmapi/tools/reference_instance/expiration.yaml +src/cmapi/tools/reference_instance/instance.yaml +src/cmapi/tools/reference_instance/tiers.yaml \ No newline at end of file diff --git a/cmapi/src/cmapi.egg-info/dependency_links.txt b/cmapi/src/cmapi.egg-info/dependency_links.txt new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/cmapi/src/cmapi.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/cmapi/src/cmapi.egg-info/entry_points.txt b/cmapi/src/cmapi.egg-info/entry_points.txt new file mode 100644 index 00000000..51c4ab29 --- /dev/null +++ b/cmapi/src/cmapi.egg-info/entry_points.txt @@ -0,0 +1,5 @@ +[console_scripts] +cmapi-api = cmapi.main:run +cmapi-migrate = cmapi.core.db.migrate:run +cmapi-tools = cmapi.tools:run +cmapi-worker = cmapi.worker:run diff --git a/cmapi/src/cmapi.egg-info/requires.txt b/cmapi/src/cmapi.egg-info/requires.txt new file mode 100644 index 00000000..668fb87f --- /dev/null +++ b/cmapi/src/cmapi.egg-info/requires.txt @@ -0,0 +1,18 @@ +fastapi==0.162.2 +starlette==1.10.0 +uvicorn[standard]==0.32.1 +pydantic==2.14.2 +pydantic-settings==2.16.2 +sqlalchemy==2.1.8 +psycopg[binary]==3.3.8 +alembic==1.20.1 +httpx==0.28.1 +pyjwt[crypto]==2.15.1 +pyyaml==6.0.2 +google-re2==1.1.20251105 +prometheus-client==0.24.1 +structlog==26.1.0 + +[test] +pytest==9.2.0 +jsonschema==4.26.0 diff --git a/cmapi/src/cmapi.egg-info/top_level.txt b/cmapi/src/cmapi.egg-info/top_level.txt new file mode 100644 index 00000000..ae4a906f --- /dev/null +++ b/cmapi/src/cmapi.egg-info/top_level.txt @@ -0,0 +1 @@ +cmapi diff --git a/cmapi/src/cmapi/core/git/base.py b/cmapi/src/cmapi/core/git/base.py index 5cc81ee5..d461d88f 100644 --- a/cmapi/src/cmapi/core/git/base.py +++ b/cmapi/src/cmapi/core/git/base.py @@ -1,387 +1,387 @@ -"""What the platform adapters share (#286): one httpx client, one structured event per host call, and the error contract. - -The platform layer is thin: open a PR from the request branch, read its state, merge it pinned to a sha, comment, close. A -provider with a Git layer (GitHub) writes branches and reads trees through it; one without (the Gitea stand-in) through REST. - -A Git host failure is GitUnavailable; the worker turns it into a retry with backoff. HeadMoved and NotMergeable say why a -merge did not happen; PlatformRefused is a refusal that a retry cannot fix. Each call logs its op, outcome, HTTP status and, -on a refusal, the host's message (core/git/oplog.py), and counts in cmapi_git_platform_requests_total{platform,op,code}. - -The host's message is text the host chose: a host or a proxy in front of it may echo the request, the Authorization header -included. So every text taken from an answer passes through host_text, which removes each form of the bot's credential and -only then cuts (docs/02 "Client rules", #424); every error, request event, log line and API answer built from it is clean. -""" -from __future__ import annotations - -import base64 -import ssl -from dataclasses import dataclass -from datetime import datetime -from typing import Any, Callable, Iterable, Literal, Mapping - -import httpx - -from cmapi.core.clients.redact import order_forms, redact, redact_cut, sent_forms -from cmapi.core.ports import PrRef, PrStatus - -CheckState = Literal["pending", "success", "failure"] - - -class GitUnavailable(RuntimeError): - pass - - -class IncompleteList(GitUnavailable): - """The host gave a list that it can have cut, so nothing may read it as complete. A caller that does not handle it - treats the host as unavailable, which is the safe reading.""" - - -class PlatformRefused(GitUnavailable): - """401, 403, 404, 422 and the like: the host said no, and saying it again will not change that.""" - - def __init__(self, message: str, status: int | None = None, host_message: str = ""): - super().__init__(message) - self.status, self.host_message = status, host_message - - -class HeadMoved(PlatformRefused): - """The PR's head is not the pinned sha: nothing was merged.""" - - -class NotMergeable(GitUnavailable): - """The host will not merge now. transient: it is still computing, or a required check is pending.""" - - def __init__(self, message: str, transient: bool = False): - super().__init__(message) - self.transient = transient - - -# U+FFFD, what a REST host answers for a byte that is not UTF-8 in a name: measured on api.github.com (git/trees and Contents, -# 2026-11-24), and what Gitea's JSON encoder writes (json-iterator, writeStringSlowPathWithHTMLEscaped). It cannot be told from -# a name that holds U+FFFD itself, so no provider carries either (#626). -REPLACEMENT = "\ufffd" - - -class NotUtf8(Exception): - """Paths under a folder whose name, or a manifest whose text (part), is not UTF-8, so cmapi cannot carry them (#626). - - Git keeps a name as bytes, and a plan, the API's JSON and the database hold text. Each path is as shown() shows it. Not - GitUnavailable: Git answered, and a retry reads the same folder.""" - - def __init__(self, paths: Iterable[str], part: Literal["name", "text"]): - self.paths, self.part = sorted(paths), part - # U+FFFD is valid UTF-8: a REST host's stand-in for a lost byte, or typed on purpose. Either way no plan can carry it. - self.rule = "is not UTF-8 or holds U+FFFD" if any(REPLACEMENT in p for p in self.paths) else "is not UTF-8" - super().__init__(f"the {part} of {', '.join(self.paths[:3])}{' and more' if len(self.paths) > 3 else ''} {self.rule}") - - -def shown(raw: bytes) -> str: - """A path of NotUtf8, to show: each backslash doubled, as Git's own quoting always escapes one (core.quotePath), and each - byte that is not UTF-8 as \\xNN (codecs, 'backslashreplace'). So each shown path stands for one name only (#626).""" - return raw.replace(b"\\", b"\\\\").decode(errors="backslashreplace") - - -def git_name(raw: bytes) -> tuple[str, bool]: - """A name as `git ls-tree -z` gives it ("the filename is output verbatim", git-ls-tree(1)), as text, and whether cmapi can - carry it: valid UTF-8 with no U+FFFD. A name it cannot carry comes back as shown() shows it.""" - try: - name = raw.decode() - except UnicodeDecodeError: - return shown(raw), False - return (name, True) if REPLACEMENT not in name else (shown(raw), False) - - -def refuse_lost_names(paths: Iterable[str]) -> None: - """NotUtf8 for each name a REST host gave with U+FFFD: the byte it stands for is lost, so no plan can name the path.""" - lost = [shown(p.encode()) for p in paths if REPLACEMENT in p] - if lost: - raise NotUtf8(lost, "name") - - -def manifest_text(texts: Mapping[str, bytes]) -> dict[str, str]: - """Each manifest's bytes as text, strict UTF-8 as YAML is read here; NotUtf8 names every one that is not.""" - files, bad = {}, [] - for path, data in texts.items(): - try: - files[path] = data.decode() - except UnicodeDecodeError: - bad.append(shown(path.encode())) - if bad: - raise NotUtf8(bad, "text") - return files - - -def as_plan(read: Callable[[], bool]) -> bool: - """A folder read compared with the plan's, by read. A folder that holds a name or text that is not UTF-8 is never the - plan's, since the plan refuses one (#626), so the comparison is False rather than an error.""" - try: - return read() - except NotUtf8: - return False - - -@dataclass(frozen=True) -class BranchRequest: - """What a provider needs to write a request's branch.""" - cluster_id: str - request_id: str - folder: str - plan_hash: str - message: str - files: Mapping[str, str | None] # the plan's files: text, or None for a path the plan removes - prev: Mapping[str, str] # the folder before the plan (plan.prev) - approved_at: datetime # both commit dates: the reproducible commit - - -@dataclass(frozen=True) -class PushResult: - head: str - base: str - result: Literal["created", "adopted", "replaced"] - - -@dataclass(frozen=True) -class MergeCheck: - """git merge-tree --write-tree
, and the folder's two comparisons (Fable 2.3).""" - main_sha: str - head_sha: str - conflicts: tuple[str, ...] = () - base_matches: bool = True # the folder on main is the plan's prev - result_matches: bool = True # the folder in the merged tree is the plan's files - tree: str | None = None - - @property - def ok(self) -> bool: - return not self.conflicts and self.base_matches and self.result_matches - - def reason(self, branch: str = "main") -> str: - if self.conflicts: - return f"conflicts with {branch} at {self.main_sha[:8]} in {', '.join(self.conflicts)}" - if not self.base_matches: - return f"the folder on {branch} at {self.main_sha[:8]} is no longer the plan's base" - if not self.result_matches: - return f"the merge of {self.head_sha[:8]} into {branch} at {self.main_sha[:8]} would not leave the folder as planned" - return "clean" - - -def is_commit_id(ref: str, lengths: tuple[int, ...] = (40,)) -> bool: - """Whether an explicit ref has the spelling of a full lowercase object ID of one of these lengths (SHA-1 has 40).""" - return len(ref) in lengths and all(c in "0123456789abcdef" for c in ref) - - -def credential_values(token: str | None, basic_auth: tuple[str, str] | None) -> tuple[str, ...]: - """Each value of the bot's credential that a host could echo: the token, and with Basic auth the password and the header's - value as httpx sends it, base64 of user:password in UTF-8 (RFC 7617).""" - values = [token or ""] - if basic_auth: - user, password = basic_auth - values += [password, base64.b64encode(f"{user}:{password}".encode("utf-8")).decode("ascii")] - return tuple(v for v in values if v) - - -class HostGitProvider: - """The contract. Subclasses fill in the host's endpoints.""" - - name = "host" - BOT_NAME = "cmapi-git-bot" - BOT_EMAIL = "cmapi-git-bot@noreply.invalid" - # Whether the host's own CI reports ci/kubeconform and ci/kyverno (GitHub: the config repository's Actions jobs, #60). The - # worker then waits for them there and never posts them. The Gitea stand-in has no runner, so it keeps False. - external_ci = False - # Whether the worker posts its checks as commit statuses. The Gitea stand-in protects main with all three - # (tools/git_bootstrap.py); GitHub posts cmapi/check alone, with host CI or git.postStatus on (the arbitration of #286, row 11). - post_statuses = True - # Whether the worker may post ci/kubeconform and ci/kyverno from its own validators when the host runs no CI. Only on the - # Gitea stand-in, whose protection can name a context but not who sets it. On GitHub never: a ci/* the bot's token posted is - # the worker vouching for itself (#60). - posts_ci = True - - def __init__(self, api_url: str, repository: str, token: str, *, default_branch: str = "main", - verify: ssl.SSLContext | str | bool = True, web_url: str | None = None, timeout: float = 20.0, - basic_auth: tuple[str, str] | None = None): - self.api_url, self.repository, self.default_branch = api_url.rstrip("/"), repository, default_branch - self.web_url = (web_url or self.api_url).rstrip("/") - self._client = httpx.Client(base_url=self.api_url, verify=verify, timeout=timeout, - headers=self._headers(token) if token else {"Accept": "application/json"}, - auth=basic_auth) - from cmapi.core.git.oplog import register_secret - - credentials = credential_values(token, basic_auth) - for value in credentials: - register_secret(value) - self._forms = order_forms({form for value in credentials for form in sent_forms(value)}) - - def _headers(self, token: str) -> dict[str, str]: - return {"Authorization": f"token {token}", "Accept": "application/json"} - - def redact(self, text: str) -> str: - """`text` without the bot's credential in any form (core/clients/redact.py): the whole text, before any cut.""" - return redact(text, self._forms) - - def host_text(self, r: httpx.Response, limit: int = 300) -> str: - """The host's answer as error text: redacted, then cut to `limit` characters (#424).""" - return redact_cut(r.text, self._forms, limit) - - def commit_lines(self, commits: Iterable[Mapping[str, Any]]) -> list[str]: - """` ` of each commit of the host's list. The subject is text the host returns, and GET - /api/v1/admin/git-log serves it to every reports:read caller, so it is redacted; the sha is left as it is (#424).""" - return [f"{c['sha'][:8]} {self.redact(c['commit']['message'].splitlines()[0])}" for c in commits] - - def _call(self, operation: str, method: str, path: str, *, ok: tuple[int, ...] = (200, 201, 204), - log_fields: Mapping[str, Any] | None = None, **kw: Any) -> httpx.Response: - from cmapi.core.git.oplog import Op - from cmapi.core.observability import PLATFORM_REQUESTS - - with Op(operation, method=method, path=path, platform=self.name, **(log_fields or {})) as op: - try: - r = self._client.request(method, path, **kw) - except httpx.HTTPError as exc: - PLATFORM_REQUESTS.labels(self.name, operation, "error").inc() - op.outcome = "retry" - # An HTTP library's error can show the header it refused ("illegal header value b'...'"). Not chained: the - # worker logs traceback.format_exc(), which prints the cause's own, unredacted text (#444). - raise GitUnavailable(self.redact(f"{operation}: {type(exc).__name__}: {exc}")) from None - PLATFORM_REQUESTS.labels(self.name, operation, f"{r.status_code // 100}xx").inc() - op.set(http_status=r.status_code, host_request_id=r.headers.get("x-github-request-id") or r.headers.get("x-request-id")) - if r.status_code >= 500 or r.status_code == 429: - op.set(message=self.host_text(r)) - op.outcome = "retry" - raise GitUnavailable(f"{operation}: the Git host answered {r.status_code}: {self.host_text(r, 200)}") - if r.status_code not in ok: - op.outcome = "refused" - op.set(message=self.host_text(r)) - return r - - # ---- the Git side: a Git layer, or the host's REST API - # How long a full object ID is on this host: 40 hex characters (SHA-1). A host with SHA-256 repositories adds 64. - object_id_lengths: tuple[int, ...] = (40,) - - def _folder_head(self, ref: str | None) -> str: - """An omitted ref selects the configured branch. An explicit object ID pins the read.""" - if ref and is_commit_id(ref, self.object_id_lengths): - return ref - branch = ref or self.default_branch - head = self.branch_head(branch) - if head is None: - raise GitUnavailable(f"branch {branch} does not exist") - return head - - def read_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: - """Files under path at ref (default branch head), keyed by repository path, and the commit sha.""" - raise NotImplementedError - - def tree_files(self, ref: str, folder: str) -> dict[str, str]: - files, _ = self.read_folder(folder, ref) - return files - - def list_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: - """Every entry under path at ref, at any depth, that is not a folder, and the commit sha: {repository path: Git object - type}, "blob" for a file, an executable or a symlink and "commit" for a submodule. read_folder reads cmapi's manifests - (the .yaml files directly in the folder); this lists what a delete removes, whatever made it (#616). IncompleteList - when the host cannot give each entry.""" - raise NotImplementedError - - def branch_head(self, branch: str) -> str | None: - raise NotImplementedError - - def contains(self, revision: str, sha: str) -> bool: - """Whether sha is revision or one of its ancestors.""" - raise NotImplementedError - - def changed_paths(self, head: str) -> set[str]: - """Every path any commit on head touches since it left the default branch. IncompleteList when the host cannot - give each one.""" - raise NotImplementedError - - def log(self, n: int = 20) -> list[str]: - raise NotImplementedError - - def push_request_branch(self, req: BranchRequest) -> PushResult: - """The request's branch, one commit of the plan on the default branch's head.""" - raise NotImplementedError - - def recreate_branch(self, req: BranchRequest, base: str, expected: str) -> str: - """The branch again from its recorded base, the same sha (the reproducible commit).""" - raise NotImplementedError - - def merge_check(self, head: str, folder: str, prev: Mapping[str, str], files: Mapping[str, str | None], *, - whole_folder: bool = False) -> MergeCheck: - """Before an apply and a merge. With no Git layer (the Gitea stand-in): the folder on the default branch compared with the - plan's base; the host's own merge refuses a conflict. A provider with the Git layer runs git merge-tree. - - whole_folder, a delete (#616): the folder must leave Git whole, so main's full listing is the plan's removals, each a - file, and the head's folder is empty. A path main gained after the push is refused here, before the merge, not found - after it (_merged).""" - from cmapi.core.git.oplog import Op - - with Op("merge_check", head_sha=head) as op: - try: - on_main, main = self.read_folder(folder) - base_ok = on_main == dict(prev) - except NotUtf8: # a name the plan cannot hold: main is not its base (#626) - main, base_ok = self._folder_head(None), False - result_ok = True - if whole_folder: - base_ok = base_ok and as_plan(lambda: self.list_folder(folder, main)[0] == dict.fromkeys(files, "blob")) - result_ok = as_plan(lambda: not self.list_folder(folder, head)[0]) - check = MergeCheck(main, head, (), base_ok, result_ok) - op.set(main_sha=main, base_matches=check.base_matches, result_matches=check.result_matches) - if not check.ok: - op.outcome = "refused" - return check - - def delete_branch(self, branch: str, expected: str) -> bool: - """Delete the host's branch only when it is at expected. Missing is success.""" - raise NotImplementedError - - def list_branches(self, prefix: str) -> dict[str, str]: - """{branch: sha} of the host's branches under prefix, for git_reconcile.""" - raise NotImplementedError - - def request_of(self, sha: str) -> str | None: - """The Cmapi-Request-Id trailer of a commit: whose branch head this is. None: not cmapi's, or not known.""" - return None - - def branch_time(self, sha: str) -> int: - """The commit time of a branch head, for git_reconcile's grace period.""" - raise NotImplementedError - - # ---- the PR: the host's API - def find_pr(self, branch: str) -> PrRef | None: - """The open PR from the branch into the default branch.""" - raise NotImplementedError - - def open_pr(self, branch: str, head: str, title: str, body: str) -> PrRef: - """Open it, or return the one that exists for the branch. Its head must be head.""" - raise NotImplementedError - - def pr_status(self, pr: PrRef, *, ci: bool = True) -> PrStatus: - raise NotImplementedError - - def merge(self, pr: PrRef, expected_head: str) -> str: - """Merge only if the PR head is expected_head: the merge sha. HeadMoved, NotMergeable, PlatformRefused, GitUnavailable.""" - raise NotImplementedError - - def comment(self, pr: PrRef, text: str) -> None: - raise NotImplementedError - - def close(self, pr: PrRef, comment: str) -> None: - raise NotImplementedError - - def list_open(self, prefix: str) -> list[PrRef]: - """Every open PR whose source branch starts with prefix, all pages, or it raises.""" - raise NotImplementedError - - def set_check(self, sha: str, context: str, state: CheckState, description: str, target_url: str | None = None) -> None: - raise NotImplementedError - - # ---- this pod's working storage - def cleanup(self, cluster_id: str, request_id: str) -> None: - """The request's worktree on this pod. A provider with no Git layer keeps none.""" - - def sweep(self, open_requests: Iterable[tuple[str, str]]): - """The sweeper's pass, in the worker loop between jobs. A provider with no Git layer has nothing to sweep.""" - return None - - def dispose(self) -> None: - """Release what the provider holds at shutdown. Not close(), which closes a PR.""" +"""What the platform adapters share (#286): one httpx client, one structured event per host call, and the error contract. + +The platform layer is thin: open a PR from the request branch, read its state, merge it pinned to a sha, comment, close. A +provider with a Git layer (GitHub) writes branches and reads trees through it; one without (the Gitea stand-in) through REST. + +A Git host failure is GitUnavailable; the worker turns it into a retry with backoff. HeadMoved and NotMergeable say why a +merge did not happen; PlatformRefused is a refusal that a retry cannot fix. Each call logs its op, outcome, HTTP status and, +on a refusal, the host's message (core/git/oplog.py), and counts in cmapi_git_platform_requests_total{platform,op,code}. + +The host's message is text the host chose: a host or a proxy in front of it may echo the request, the Authorization header +included. So every text taken from an answer passes through host_text, which removes each form of the bot's credential and +only then cuts (docs/02 "Client rules", #424); every error, request event, log line and API answer built from it is clean. +""" +from __future__ import annotations + +import base64 +import ssl +from dataclasses import dataclass +from datetime import datetime +from typing import Any, Callable, Iterable, Literal, Mapping + +import httpx + +from cmapi.core.clients.redact import order_forms, redact, redact_cut, sent_forms +from cmapi.core.ports import PrRef, PrStatus + +CheckState = Literal["pending", "success", "failure"] + + +class GitUnavailable(RuntimeError): + pass + + +class IncompleteList(GitUnavailable): + """The host gave a list that it can have cut, so nothing may read it as complete. A caller that does not handle it + treats the host as unavailable, which is the safe reading.""" + + +class PlatformRefused(GitUnavailable): + """401, 403, 404, 422 and the like: the host said no, and saying it again will not change that.""" + + def __init__(self, message: str, status: int | None = None, host_message: str = ""): + super().__init__(message) + self.status, self.host_message = status, host_message + + +class HeadMoved(PlatformRefused): + """The PR's head is not the pinned sha: nothing was merged.""" + + +class NotMergeable(GitUnavailable): + """The host will not merge now. transient: it is still computing, or a required check is pending.""" + + def __init__(self, message: str, transient: bool = False): + super().__init__(message) + self.transient = transient + + +# U+FFFD, what a REST host answers for a byte that is not UTF-8 in a name: measured on api.github.com (git/trees and Contents, +# 2026-11-24), and what Gitea's JSON encoder writes (json-iterator, writeStringSlowPathWithHTMLEscaped). It cannot be told from +# a name that holds U+FFFD itself, so no provider carries either (#626). +REPLACEMENT = "\ufffd" + + +class NotUtf8(Exception): + """Paths under a folder whose name, or a manifest whose text (part), is not UTF-8, so cmapi cannot carry them (#626). + + Git keeps a name as bytes, and a plan, the API's JSON and the database hold text. Each path is as shown() shows it. Not + GitUnavailable: Git answered, and a retry reads the same folder.""" + + def __init__(self, paths: Iterable[str], part: Literal["name", "text"]): + self.paths, self.part = sorted(paths), part + # U+FFFD is valid UTF-8: a REST host's stand-in for a lost byte, or typed on purpose. Either way no plan can carry it. + self.rule = "is not UTF-8 or holds U+FFFD" if any(REPLACEMENT in p for p in self.paths) else "is not UTF-8" + super().__init__(f"the {part} of {', '.join(self.paths[:3])}{' and more' if len(self.paths) > 3 else ''} {self.rule}") + + +def shown(raw: bytes) -> str: + """A path of NotUtf8, to show: each backslash doubled, as Git's own quoting always escapes one (core.quotePath), and each + byte that is not UTF-8 as \\xNN (codecs, 'backslashreplace'). So each shown path stands for one name only (#626).""" + return raw.replace(b"\\", b"\\\\").decode(errors="backslashreplace") + + +def git_name(raw: bytes) -> tuple[str, bool]: + """A name as `git ls-tree -z` gives it ("the filename is output verbatim", git-ls-tree(1)), as text, and whether cmapi can + carry it: valid UTF-8 with no U+FFFD. A name it cannot carry comes back as shown() shows it.""" + try: + name = raw.decode() + except UnicodeDecodeError: + return shown(raw), False + return (name, True) if REPLACEMENT not in name else (shown(raw), False) + + +def refuse_lost_names(paths: Iterable[str]) -> None: + """NotUtf8 for each name a REST host gave with U+FFFD: the byte it stands for is lost, so no plan can name the path.""" + lost = [shown(p.encode()) for p in paths if REPLACEMENT in p] + if lost: + raise NotUtf8(lost, "name") + + +def manifest_text(texts: Mapping[str, bytes]) -> dict[str, str]: + """Each manifest's bytes as text, strict UTF-8 as YAML is read here; NotUtf8 names every one that is not.""" + files, bad = {}, [] + for path, data in texts.items(): + try: + files[path] = data.decode() + except UnicodeDecodeError: + bad.append(shown(path.encode())) + if bad: + raise NotUtf8(bad, "text") + return files + + +def as_plan(read: Callable[[], bool]) -> bool: + """A folder read compared with the plan's, by read. A folder that holds a name or text that is not UTF-8 is never the + plan's, since the plan refuses one (#626), so the comparison is False rather than an error.""" + try: + return read() + except NotUtf8: + return False + + +@dataclass(frozen=True) +class BranchRequest: + """What a provider needs to write a request's branch.""" + cluster_id: str + request_id: str + folder: str + plan_hash: str + message: str + files: Mapping[str, str | None] # the plan's files: text, or None for a path the plan removes + prev: Mapping[str, str] # the folder before the plan (plan.prev) + approved_at: datetime # both commit dates: the reproducible commit + + +@dataclass(frozen=True) +class PushResult: + head: str + base: str + result: Literal["created", "adopted", "replaced"] + + +@dataclass(frozen=True) +class MergeCheck: + """git merge-tree --write-tree
, and the folder's two comparisons (Fable 2.3).""" + main_sha: str + head_sha: str + conflicts: tuple[str, ...] = () + base_matches: bool = True # the folder on main is the plan's prev + result_matches: bool = True # the folder in the merged tree is the plan's files + tree: str | None = None + + @property + def ok(self) -> bool: + return not self.conflicts and self.base_matches and self.result_matches + + def reason(self, branch: str = "main") -> str: + if self.conflicts: + return f"conflicts with {branch} at {self.main_sha[:8]} in {', '.join(self.conflicts)}" + if not self.base_matches: + return f"the folder on {branch} at {self.main_sha[:8]} is no longer the plan's base" + if not self.result_matches: + return f"the merge of {self.head_sha[:8]} into {branch} at {self.main_sha[:8]} would not leave the folder as planned" + return "clean" + + +def is_commit_id(ref: str, lengths: tuple[int, ...] = (40,)) -> bool: + """Whether an explicit ref has the spelling of a full lowercase object ID of one of these lengths (SHA-1 has 40).""" + return len(ref) in lengths and all(c in "0123456789abcdef" for c in ref) + + +def credential_values(token: str | None, basic_auth: tuple[str, str] | None) -> tuple[str, ...]: + """Each value of the bot's credential that a host could echo: the token, and with Basic auth the password and the header's + value as httpx sends it, base64 of user:password in UTF-8 (RFC 7617).""" + values = [token or ""] + if basic_auth: + user, password = basic_auth + values += [password, base64.b64encode(f"{user}:{password}".encode("utf-8")).decode("ascii")] + return tuple(v for v in values if v) + + +class HostGitProvider: + """The contract. Subclasses fill in the host's endpoints.""" + + name = "host" + BOT_NAME = "cmapi-git-bot" + BOT_EMAIL = "cmapi-git-bot@noreply.invalid" + # Whether the host's own CI reports ci/kubeconform and ci/kyverno (GitHub: the config repository's Actions jobs, #60). The + # worker then waits for them there and never posts them. The Gitea stand-in has no runner, so it keeps False. + external_ci = False + # Whether the worker posts its checks as commit statuses. The Gitea stand-in protects main with all three + # (tools/git_bootstrap.py); GitHub posts cmapi/check alone, with host CI or git.postStatus on (the arbitration of #286, row 11). + post_statuses = True + # Whether the worker may post ci/kubeconform and ci/kyverno from its own validators when the host runs no CI. Only on the + # Gitea stand-in, whose protection can name a context but not who sets it. On GitHub never: a ci/* the bot's token posted is + # the worker vouching for itself (#60). + posts_ci = True + + def __init__(self, api_url: str, repository: str, token: str, *, default_branch: str = "main", + verify: ssl.SSLContext | str | bool = True, web_url: str | None = None, timeout: float = 20.0, + basic_auth: tuple[str, str] | None = None): + self.api_url, self.repository, self.default_branch = api_url.rstrip("/"), repository, default_branch + self.web_url = (web_url or self.api_url).rstrip("/") + self._client = httpx.Client(base_url=self.api_url, verify=verify, timeout=timeout, + headers=self._headers(token) if token else {"Accept": "application/json"}, + auth=basic_auth) + from cmapi.core.git.oplog import register_secret + + credentials = credential_values(token, basic_auth) + for value in credentials: + register_secret(value) + self._forms = order_forms({form for value in credentials for form in sent_forms(value)}) + + def _headers(self, token: str) -> dict[str, str]: + return {"Authorization": f"token {token}", "Accept": "application/json"} + + def redact(self, text: str) -> str: + """`text` without the bot's credential in any form (core/clients/redact.py): the whole text, before any cut.""" + return redact(text, self._forms) + + def host_text(self, r: httpx.Response, limit: int = 300) -> str: + """The host's answer as error text: redacted, then cut to `limit` characters (#424).""" + return redact_cut(r.text, self._forms, limit) + + def commit_lines(self, commits: Iterable[Mapping[str, Any]]) -> list[str]: + """` ` of each commit of the host's list. The subject is text the host returns, and GET + /api/v1/admin/git-log serves it to every reports:read caller, so it is redacted; the sha is left as it is (#424).""" + return [f"{c['sha'][:8]} {self.redact(c['commit']['message'].splitlines()[0])}" for c in commits] + + def _call(self, operation: str, method: str, path: str, *, ok: tuple[int, ...] = (200, 201, 204), + log_fields: Mapping[str, Any] | None = None, **kw: Any) -> httpx.Response: + from cmapi.core.git.oplog import Op + from cmapi.core.observability import PLATFORM_REQUESTS + + with Op(operation, method=method, path=path, platform=self.name, **(log_fields or {})) as op: + try: + r = self._client.request(method, path, **kw) + except httpx.HTTPError as exc: + PLATFORM_REQUESTS.labels(self.name, operation, "error").inc() + op.outcome = "retry" + # An HTTP library's error can show the header it refused ("illegal header value b'...'"). Not chained: the + # worker logs traceback.format_exc(), which prints the cause's own, unredacted text (#444). + raise GitUnavailable(self.redact(f"{operation}: {type(exc).__name__}: {exc}")) from None + PLATFORM_REQUESTS.labels(self.name, operation, f"{r.status_code // 100}xx").inc() + op.set(http_status=r.status_code, host_request_id=r.headers.get("x-github-request-id") or r.headers.get("x-request-id")) + if r.status_code >= 500 or r.status_code == 429: + op.set(message=self.host_text(r)) + op.outcome = "retry" + raise GitUnavailable(f"{operation}: the Git host answered {r.status_code}: {self.host_text(r, 200)}") + if r.status_code not in ok: + op.outcome = "refused" + op.set(message=self.host_text(r)) + return r + + # ---- the Git side: a Git layer, or the host's REST API + # How long a full object ID is on this host: 40 hex characters (SHA-1). A host with SHA-256 repositories adds 64. + object_id_lengths: tuple[int, ...] = (40,) + + def _folder_head(self, ref: str | None) -> str: + """An omitted ref selects the configured branch. An explicit object ID pins the read.""" + if ref and is_commit_id(ref, self.object_id_lengths): + return ref + branch = ref or self.default_branch + head = self.branch_head(branch) + if head is None: + raise GitUnavailable(f"branch {branch} does not exist") + return head + + def read_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: + """Files under path at ref (default branch head), keyed by repository path, and the commit sha.""" + raise NotImplementedError + + def tree_files(self, ref: str, folder: str) -> dict[str, str]: + files, _ = self.read_folder(folder, ref) + return files + + def list_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: + """Every entry under path at ref, at any depth, that is not a folder, and the commit sha: {repository path: Git object + type}, "blob" for a file, an executable or a symlink and "commit" for a submodule. read_folder reads cmapi's manifests + (the .yaml files directly in the folder); this lists what a delete removes, whatever made it (#616). IncompleteList + when the host cannot give each entry.""" + raise NotImplementedError + + def branch_head(self, branch: str) -> str | None: + raise NotImplementedError + + def contains(self, revision: str, sha: str) -> bool: + """Whether sha is revision or one of its ancestors.""" + raise NotImplementedError + + def changed_paths(self, head: str) -> set[str]: + """Every path any commit on head touches since it left the default branch. IncompleteList when the host cannot + give each one.""" + raise NotImplementedError + + def log(self, n: int = 20) -> list[str]: + raise NotImplementedError + + def push_request_branch(self, req: BranchRequest) -> PushResult: + """The request's branch, one commit of the plan on the default branch's head.""" + raise NotImplementedError + + def recreate_branch(self, req: BranchRequest, base: str, expected: str) -> str: + """The branch again from its recorded base, the same sha (the reproducible commit).""" + raise NotImplementedError + + def merge_check(self, head: str, folder: str, prev: Mapping[str, str], files: Mapping[str, str | None], *, + whole_folder: bool = False) -> MergeCheck: + """Before an apply and a merge. With no Git layer (the Gitea stand-in): the folder on the default branch compared with the + plan's base; the host's own merge refuses a conflict. A provider with the Git layer runs git merge-tree. + + whole_folder, a delete (#616): the folder must leave Git whole, so main's full listing is the plan's removals, each a + file, and the head's folder is empty. A path main gained after the push is refused here, before the merge, not found + after it (_merged).""" + from cmapi.core.git.oplog import Op + + with Op("merge_check", head_sha=head) as op: + try: + on_main, main = self.read_folder(folder) + base_ok = on_main == dict(prev) + except NotUtf8: # a name the plan cannot hold: main is not its base (#626) + main, base_ok = self._folder_head(None), False + result_ok = True + if whole_folder: + base_ok = base_ok and as_plan(lambda: self.list_folder(folder, main)[0] == dict.fromkeys(files, "blob")) + result_ok = as_plan(lambda: not self.list_folder(folder, head)[0]) + check = MergeCheck(main, head, (), base_ok, result_ok) + op.set(main_sha=main, base_matches=check.base_matches, result_matches=check.result_matches) + if not check.ok: + op.outcome = "refused" + return check + + def delete_branch(self, branch: str, expected: str) -> bool: + """Delete the host's branch only when it is at expected. Missing is success.""" + raise NotImplementedError + + def list_branches(self, prefix: str) -> dict[str, str]: + """{branch: sha} of the host's branches under prefix, for git_reconcile.""" + raise NotImplementedError + + def request_of(self, sha: str) -> str | None: + """The Cmapi-Request-Id trailer of a commit: whose branch head this is. None: not cmapi's, or not known.""" + return None + + def branch_time(self, sha: str) -> int: + """The commit time of a branch head, for git_reconcile's grace period.""" + raise NotImplementedError + + # ---- the PR: the host's API + def find_pr(self, branch: str) -> PrRef | None: + """The open PR from the branch into the default branch.""" + raise NotImplementedError + + def open_pr(self, branch: str, head: str, title: str, body: str) -> PrRef: + """Open it, or return the one that exists for the branch. Its head must be head.""" + raise NotImplementedError + + def pr_status(self, pr: PrRef, *, ci: bool = True) -> PrStatus: + raise NotImplementedError + + def merge(self, pr: PrRef, expected_head: str) -> str: + """Merge only if the PR head is expected_head: the merge sha. HeadMoved, NotMergeable, PlatformRefused, GitUnavailable.""" + raise NotImplementedError + + def comment(self, pr: PrRef, text: str) -> None: + raise NotImplementedError + + def close(self, pr: PrRef, comment: str) -> None: + raise NotImplementedError + + def list_open(self, prefix: str) -> list[PrRef]: + """Every open PR whose source branch starts with prefix, all pages, or it raises.""" + raise NotImplementedError + + def set_check(self, sha: str, context: str, state: CheckState, description: str, target_url: str | None = None) -> None: + raise NotImplementedError + + # ---- this pod's working storage + def cleanup(self, cluster_id: str, request_id: str) -> None: + """The request's worktree on this pod. A provider with no Git layer keeps none.""" + + def sweep(self, open_requests: Iterable[tuple[str, str]]): + """The sweeper's pass, in the worker loop between jobs. A provider with no Git layer has nothing to sweep.""" + return None + + def dispose(self) -> None: + """Release what the provider holds at shutdown. Not close(), which closes a PR.""" diff --git a/cmapi/src/cmapi/core/git/gitea.py b/cmapi/src/cmapi/core/git/gitea.py index 3af20e2a..c86cdc31 100644 --- a/cmapi/src/cmapi/core/git/gitea.py +++ b/cmapi/src/cmapi/core/git/gitea.py @@ -1,316 +1,316 @@ -"""GitProvider for Gitea (API v1). Endpoints as documented for Gitea 1.25: - - GET /repos/{o}/{r}/branches/{b} head sha - GET /repos/{o}/{r}/git/commits/{sha} a commit: its message (the trailers) and its parents - GET /repos/{o}/{r}/contents/{path}?ref= folder listing, file content (base64) - POST /repos/{o}/{r}/branches {new_branch_name, old_ref_name} - POST /repos/{o}/{r}/contents one commit with several files {files: [...]} - POST /repos/{o}/{r}/pulls {head, base, title, body} - GET /repos/{o}/{r}/pulls/{n} state, merged, head.sha, merge_commit_sha - GET /repos/{o}/{r}/pulls?state=open&head= open PR from a branch - POST /repos/{o}/{r}/statuses/{sha} commit status {state, context, description} - GET /repos/{o}/{r}/commits/{sha}/status combined status - POST /repos/{o}/{r}/pulls/{n}/merge {Do: merge, head_commit_id, delete_branch_after_merge} - PATCH /repos/{o}/{r}/pulls/{n} {state: closed} -""" -from __future__ import annotations - -import base64 -from itertools import count -from pathlib import PurePosixPath -from typing import Any, Iterator, Mapping -from urllib.parse import quote - -from cmapi.core.git.base import (BranchRequest, CheckState, GitUnavailable, HostGitProvider, PushResult, manifest_text, - refuse_lost_names) -from cmapi.core.git.workspace import TRAILER_PLAN_HASH, TRAILER_REQUEST, BranchMoved, BranchRefused, request_branch -from cmapi.core.ports import PrRef, PrStatus - - -class GiteaProvider(HostGitProvider): - name = "gitea" - object_id_lengths = (40, 64) # a Gitea repository is SHA-1 or SHA-256, as the Git layer's _OID reads both - - def _repo(self) -> str: - return f"/repos/{self.repository}" - - def branch_head(self, branch: str) -> str | None: - # A name is data in the path: "#", "?" and "%" are escaped (RFC 3986, sections 2.4 and 3.3). Gitea routes branches, - # compare and contents with a "/*" wildcard, so a "/" in a branch name or a file path stays a "/" (#638). - r = self._call("branch_head", "GET", f"{self._repo()}/branches/{quote(branch)}", ok=(200, 404)) - return r.json()["commit"]["id"] if r.status_code == 200 else None - - def _tree_entries(self, oid: str) -> Iterator[dict[str, Any]]: - for page in count(1): - r = self._call("read_folder", "GET", f"{self._repo()}/git/trees/{oid}", params={"page": page}) - if r.status_code != 200: - raise GitUnavailable(f"read tree {oid}: HTTP {r.status_code}") - body = r.json() - entries = body["tree"] or [] - if body["truncated"] and (not entries or body["page"] != page): - raise GitUnavailable(f"incomplete page {page} of tree {oid}") - yield from entries - if not body["truncated"]: - return - - def read_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: - head = self._folder_head(ref) - # Gitea Contents resolves a branch or tag before a commit. Trees and blobs accept object IDs. - directory = PurePosixPath(path.strip("/")) - tree = head - for i, part in enumerate(directory.parts): - entry = next((e for e in self._tree_entries(tree) if e["path"] == part), None) - if entry is None: - return {}, head - if entry["type"] != "tree": - if i + 1 < len(directory.parts): - return {}, head - entries = [entry] # Contents also supports a direct file path. - directory = directory.parent - break - tree = entry["sha"] - else: - entries = self._tree_entries(tree) - manifests = {str(directory / e["path"]): e["sha"] for e in entries - if e["type"] == "blob" and e["mode"] in ("100644", "100755") and e["path"].endswith(".yaml")} - # Gitea's JSON writes a byte that is not UTF-8 as U+FFFD (json-iterator): no plan can name the file (#626). - refuse_lost_names(manifests) - texts: dict[str, bytes] = {} - for path, sha in manifests.items(): - r = self._call("read_file", "GET", f"{self._repo()}/git/blobs/{sha}") - if r.status_code != 200: - raise GitUnavailable(f"read blob {sha}: HTTP {r.status_code}") - texts[path] = base64.b64decode(r.json()["content"]) - return manifest_text(texts), head - - def list_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: - """Every blob and submodule under path, at any depth (#616): each subtree read with _tree_entries, page by page, so no - recursive listing that the host may cut is read as complete.""" - entries, head = self._walk(path, ref) - refuse_lost_names(entries) # a delete removes each path, so it must name each one (#626) - return {p: kind for p, (kind, _) in entries.items()}, head - - def _walk(self, path: str, ref: str | None) -> tuple[dict[str, tuple[str, str]], str]: - """list_folder with each entry's object ID: {path: (type, ID)}. The ID is what a delete sends as its sha, the tree - entry's own, which Gitea compares it with, so no URL has to carry a name that holds "#" or "?" (#616).""" - head = self._folder_head(ref) - tree = head - directory = PurePosixPath(path.strip("/")) - for part in directory.parts: - entry = next((e for e in self._tree_entries(tree) if e["path"] == part), None) - if entry is None or entry["type"] != "tree": - return {}, head - tree = entry["sha"] - listed: dict[str, tuple[str, str]] = {} - pending = [(directory, tree)] - while pending: - where, oid = pending.pop() - for e in self._tree_entries(oid): - if e["type"] == "tree": - pending.append((where / e["path"], e["sha"])) - else: - listed[str(where / e["path"])] = (e["type"], e["sha"]) - return listed, head - - def push_request_branch(self, req: BranchRequest) -> PushResult: - """Through Gitea's REST API, not the Git layer: the chart's stand-in, whose Gitea the cluster serves over plain http, which - the Git layer refuses. A branch that exists is handled as the Git layer handles it (the arbitration of #286, row 3; - #450): adopted when its head is this request's commit of this plan with the plan's files; deleted and written again - when it is this request's own stale attempt; refused, and left as it is, when it is anyone else's. An open PR proves - nothing about the head. REST has no lease, so the delete of a stale attempt reads the head first (delete_branch).""" - branch = request_branch(req.cluster_id, req.request_id) - base = self.branch_head(self.default_branch) - if base is None: - raise GitUnavailable(f"branch {self.default_branch} does not exist") - existing = self.branch_head(branch) - if existing is not None: - trailers, parents = self._commit(existing) - planned = {p: t for p, t in req.files.items() if t is not None} - if trailers.get(TRAILER_REQUEST) != [req.request_id]: - raise BranchRefused(f"branch {branch} exists at {existing[:8]} and its head is not cmapi's commit for " - f"{req.request_id}: it is not adopted or overwritten") - if trailers.get(TRAILER_PLAN_HASH) == [req.plan_hash] and len(parents) == 1 and \ - self.read_folder(req.folder, existing)[0] == planned: - return PushResult(existing, parents[0], "adopted") - if not self.delete_branch(branch, existing): - raise BranchMoved(f"branch {branch} moved from {existing[:8]} before its stale attempt was replaced") - # The folder at main's commit, which the new branch starts from, read before the branch exists: a read that fails (a name - # that is not UTF-8, #626, or the host) leaves no branch at main's commit, which a retry would refuse as not cmapi's. - current, _ = self.read_folder(req.folder, base) - # A removal is any path of the folder, not only a manifest (#616). Only a plan that removes one walks the subfolders. - listed = self._walk(req.folder, base)[0] if any(text is None for text in req.files.values()) else {} - r = self._call("create_branch", "POST", f"{self._repo()}/branches", - json={"new_branch_name": branch, "old_ref_name": base}, ok=(201,)) - if r.status_code != 201: - raise GitUnavailable(f"create branch {branch}: {r.status_code} {self.host_text(r, 200)}") - ops = [] - for path, text in req.files.items(): - if text is None: - if path in listed: - ops.append({"operation": "delete", "path": path, "sha": listed[path][1]}) - elif path in current: - if current[path] != text: - ops.append({"operation": "update", "path": path, "sha": self._blob_sha(path, branch), "content": _b64(text)}) - else: - ops.append({"operation": "create", "path": path, "content": _b64(text)}) - if ops: - r = self._call("commit", "POST", f"{self._repo()}/contents", - json={"branch": branch, "message": req.message, "files": ops, - "author": {"name": self.BOT_NAME, "email": self.BOT_EMAIL}, - "committer": {"name": self.BOT_NAME, "email": self.BOT_EMAIL}}, ok=(200, 201)) - if r.status_code not in (200, 201): - raise GitUnavailable(f"commit on {branch}: {r.status_code} {self.host_text(r)}") - head = self.branch_head(branch) - return PushResult(head or base, base, "created" if existing is None else "replaced") - - def _commit(self, sha: str) -> tuple[dict[str, list[str]], list[str]]: - """A commit's cmapi trailers ({key: [values]}, from its message's last paragraph) and its parents' shas.""" - r = self._call("commit_read", "GET", f"{self._repo()}/git/commits/{sha}", ok=(200,)) - if r.status_code != 200: - raise GitUnavailable(f"read commit {sha[:8]}: {r.status_code} {self.host_text(r, 200)}") - body = r.json() - paragraphs = [p for p in ((body.get("commit") or {}).get("message") or "").strip().split("\n\n") if p.strip()] - trailers: dict[str, list[str]] = {} - for line in (paragraphs[-1].splitlines() if paragraphs else []): - key, sep, value = line.partition(":") - if sep and key.strip() in (TRAILER_REQUEST, TRAILER_PLAN_HASH): - trailers.setdefault(key.strip(), []).append(value.strip()) - return trailers, [p["sha"] for p in body.get("parents") or []] - - - def recreate_branch(self, req: BranchRequest, base: str, expected: str) -> str: - raise GitUnavailable("the Gitea stand-in is not on the Git layer: a closed PR's branch is not re-created") - - def open_pr(self, branch: str, head: str, title: str, body: str) -> PrRef: - existing = self.find_pr(branch) - if existing is None: - r = self._call("open_pr", "POST", f"{self._repo()}/pulls", - json={"head": branch, "base": self.default_branch, "title": title, "body": body}, ok=(201,)) - if r.status_code != 201: - raise GitUnavailable(f"open PR from {branch}: {r.status_code} {self.host_text(r)}") - existing = self._pr_ref(r.json()) - return existing - - def comment(self, pr: PrRef, text: str) -> None: - self._call("comment", "POST", f"{self._repo()}/issues/{pr.number}/comments", json={"body": text}, ok=(201,)) - - def delete_branch(self, branch: str, expected: str) -> bool: - """Gitea's REST delete is not conditional: the head is read first, and a race in between is the stand-in's to accept.""" - head = self.branch_head(branch) - if head is None: - return True - if head != expected: - return False - r = self._call("delete_branch", "DELETE", f"{self._repo()}/branches/{quote(branch)}", ok=(204, 404)) - return r.status_code in (204, 404) - - def _list_pages(self, operation: str, resource: str, **filters: str) -> Iterator[dict[str, Any]]: - path = f"{self._repo()}/{resource}" - for page in count(1): - response = self._call(operation, "GET", path, params={**filters, "limit": 50, "page": page}) - if response.status_code != 200: - raise GitUnavailable(f"{operation}: GET {path} page {page}: HTTP {response.status_code}") - yield from response.json() - if "next" not in response.links: - return - - def list_open(self, prefix: str) -> list[PrRef]: - return [self._pr_ref(p) for p in self._list_pages("find_pr", "pulls", state="open") - if p["head"]["ref"].startswith(prefix)] - - def list_branches(self, prefix: str) -> dict[str, str]: - return {b["name"]: b["commit"]["id"] for b in self._list_pages("branches", "branches") - if b["name"].startswith(prefix)} - - def branch_time(self, sha: str) -> int: - from datetime import datetime - - r = self._call("commit_read", "GET", f"{self._repo()}/git/commits/{sha}") - return int(datetime.fromisoformat(r.json()["created"].replace("Z", "+00:00")).timestamp()) - - def contains(self, revision: str, sha: str) -> bool: - if revision == sha: - return True - r = self._call("compare", "GET", f"{self._repo()}/compare/{quote(revision)}...{sha}") - if r.status_code == 404: # not this repository's: a multi-source Application's other source, or a force-pushed commit - return False - if r.status_code != 200: - raise GitUnavailable(f"compare {revision[:8]}...{sha[:8]}: {r.status_code} {self.host_text(r, 200)}") - return r.json().get("total_commits", 1) == 0 - - def changed_paths(self, head: str) -> set[str]: - r = self._call("compare", "GET", f"{self._repo()}/compare/{quote(self.default_branch)}...{head}") - if r.status_code != 200: - raise GitUnavailable(f"compare {head[:8]}: {r.status_code} {self.host_text(r, 200)}") - return {f["filename"] for c in r.json().get("commits") or [] for f in c.get("files") or []} - - def _blob_sha(self, path: str, ref: str) -> str: - r = self._call("read_file", "GET", f"{self._repo()}/contents/{quote(path)}", params={"ref": ref}) - return r.json()["sha"] - - 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"]) - - def find_pr(self, branch: str) -> PrRef | None: - r = self._call("find_pr", "GET", f"{self._repo()}/pulls", params={"state": "open", "limit": 50}) - for p in r.json(): - if p["head"]["ref"] == branch: - return self._pr_ref(p) - return None - - def pr_status(self, pr: PrRef, *, ci: bool = True) -> PrStatus: - r = self._call("pr_status", "GET", f"{self._repo()}/pulls/{pr.number}") - if r.status_code != 200: - raise GitUnavailable(f"PR {pr.number}: {r.status_code}") - p = r.json() - head = p["head"]["sha"] - checks: dict[str, CheckState] = {} - if ci: - s = self._call("pr_checks", "GET", f"{self._repo()}/commits/{head}/status", ok=(200, 404)) - if s.status_code == 200: - for st in s.json().get("statuses") or []: - checks[st["context"]] = {"success": "success", "pending": "pending"}.get(st["status"], "failure") - state = "merged" if p.get("merged") else ("open" if p["state"] == "open" else "closed") - return PrStatus(state=state, checks=checks, merge_sha=p.get("merge_commit_sha") if p.get("merged") else None, head_sha=head) - - def set_check(self, sha: str, context: str, state: CheckState, description: str, target_url: str | None = None) -> None: - body = {"context": context, "state": state, "description": description[:255]} - if target_url: - body["target_url"] = target_url - r = self._call("set_check", "POST", f"{self._repo()}/statuses/{sha}", json=body, ok=(201,)) - if r.status_code != 201: - raise GitUnavailable(f"status {context} on {sha[:8]}: {r.status_code} {self.host_text(r, 200)}") - - def merge(self, pr: PrRef, expected_head: str) -> str: - r = self._call("merge", "POST", f"{self._repo()}/pulls/{pr.number}/merge", - json={"Do": "merge", "head_commit_id": expected_head, "delete_branch_after_merge": False, - "MergeTitleField": f"Merge {pr.branch}"}, ok=(200,)) - if r.status_code != 200: - raise GitUnavailable(f"merge PR {pr.number}: {r.status_code} {self.host_text(r)}") - p = self._call("pr_status", "GET", f"{self._repo()}/pulls/{pr.number}").json() - return p.get("merge_commit_sha") or self.branch_head(self.default_branch) or "" - - def close(self, pr: PrRef, comment: str) -> None: - self._call("comment", "POST", f"{self._repo()}/issues/{pr.number}/comments", json={"body": comment}, ok=(201,)) - self._call("close", "PATCH", f"{self._repo()}/pulls/{pr.number}", json={"state": "closed"}, ok=(201, 200)) - - def log(self, n: int = 20) -> list[str]: - r = self._call("log", "GET", f"{self._repo()}/commits", params={"sha": self.default_branch, "limit": n}) - return self.commit_lines(r.json()) - - -def _b64(text: str) -> str: - return base64.b64encode(text.encode()).decode() - - -def _common_folder(files: Mapping[str, Any]) -> str: - paths = list(files) - if not paths: - return "" - parts = paths[0].split("/")[:-1] - for p in paths[1:]: - q = p.split("/")[:-1] - while parts and parts != q[:len(parts)]: - parts = parts[:-1] - return "/".join(parts) +"""GitProvider for Gitea (API v1). Endpoints as documented for Gitea 1.25: + + GET /repos/{o}/{r}/branches/{b} head sha + GET /repos/{o}/{r}/git/commits/{sha} a commit: its message (the trailers) and its parents + GET /repos/{o}/{r}/contents/{path}?ref= folder listing, file content (base64) + POST /repos/{o}/{r}/branches {new_branch_name, old_ref_name} + POST /repos/{o}/{r}/contents one commit with several files {files: [...]} + POST /repos/{o}/{r}/pulls {head, base, title, body} + GET /repos/{o}/{r}/pulls/{n} state, merged, head.sha, merge_commit_sha + GET /repos/{o}/{r}/pulls?state=open&head= open PR from a branch + POST /repos/{o}/{r}/statuses/{sha} commit status {state, context, description} + GET /repos/{o}/{r}/commits/{sha}/status combined status + POST /repos/{o}/{r}/pulls/{n}/merge {Do: merge, head_commit_id, delete_branch_after_merge} + PATCH /repos/{o}/{r}/pulls/{n} {state: closed} +""" +from __future__ import annotations + +import base64 +from itertools import count +from pathlib import PurePosixPath +from typing import Any, Iterator, Mapping +from urllib.parse import quote + +from cmapi.core.git.base import (BranchRequest, CheckState, GitUnavailable, HostGitProvider, PushResult, manifest_text, + refuse_lost_names) +from cmapi.core.git.workspace import TRAILER_PLAN_HASH, TRAILER_REQUEST, BranchMoved, BranchRefused, request_branch +from cmapi.core.ports import PrRef, PrStatus + + +class GiteaProvider(HostGitProvider): + name = "gitea" + object_id_lengths = (40, 64) # a Gitea repository is SHA-1 or SHA-256, as the Git layer's _OID reads both + + def _repo(self) -> str: + return f"/repos/{self.repository}" + + def branch_head(self, branch: str) -> str | None: + # A name is data in the path: "#", "?" and "%" are escaped (RFC 3986, sections 2.4 and 3.3). Gitea routes branches, + # compare and contents with a "/*" wildcard, so a "/" in a branch name or a file path stays a "/" (#638). + r = self._call("branch_head", "GET", f"{self._repo()}/branches/{quote(branch)}", ok=(200, 404)) + return r.json()["commit"]["id"] if r.status_code == 200 else None + + def _tree_entries(self, oid: str) -> Iterator[dict[str, Any]]: + for page in count(1): + r = self._call("read_folder", "GET", f"{self._repo()}/git/trees/{oid}", params={"page": page}) + if r.status_code != 200: + raise GitUnavailable(f"read tree {oid}: HTTP {r.status_code}") + body = r.json() + entries = body["tree"] or [] + if body["truncated"] and (not entries or body["page"] != page): + raise GitUnavailable(f"incomplete page {page} of tree {oid}") + yield from entries + if not body["truncated"]: + return + + def read_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: + head = self._folder_head(ref) + # Gitea Contents resolves a branch or tag before a commit. Trees and blobs accept object IDs. + directory = PurePosixPath(path.strip("/")) + tree = head + for i, part in enumerate(directory.parts): + entry = next((e for e in self._tree_entries(tree) if e["path"] == part), None) + if entry is None: + return {}, head + if entry["type"] != "tree": + if i + 1 < len(directory.parts): + return {}, head + entries = [entry] # Contents also supports a direct file path. + directory = directory.parent + break + tree = entry["sha"] + else: + entries = self._tree_entries(tree) + manifests = {str(directory / e["path"]): e["sha"] for e in entries + if e["type"] == "blob" and e["mode"] in ("100644", "100755") and e["path"].endswith(".yaml")} + # Gitea's JSON writes a byte that is not UTF-8 as U+FFFD (json-iterator): no plan can name the file (#626). + refuse_lost_names(manifests) + texts: dict[str, bytes] = {} + for path, sha in manifests.items(): + r = self._call("read_file", "GET", f"{self._repo()}/git/blobs/{sha}") + if r.status_code != 200: + raise GitUnavailable(f"read blob {sha}: HTTP {r.status_code}") + texts[path] = base64.b64decode(r.json()["content"]) + return manifest_text(texts), head + + def list_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: + """Every blob and submodule under path, at any depth (#616): each subtree read with _tree_entries, page by page, so no + recursive listing that the host may cut is read as complete.""" + entries, head = self._walk(path, ref) + refuse_lost_names(entries) # a delete removes each path, so it must name each one (#626) + return {p: kind for p, (kind, _) in entries.items()}, head + + def _walk(self, path: str, ref: str | None) -> tuple[dict[str, tuple[str, str]], str]: + """list_folder with each entry's object ID: {path: (type, ID)}. The ID is what a delete sends as its sha, the tree + entry's own, which Gitea compares it with, so no URL has to carry a name that holds "#" or "?" (#616).""" + head = self._folder_head(ref) + tree = head + directory = PurePosixPath(path.strip("/")) + for part in directory.parts: + entry = next((e for e in self._tree_entries(tree) if e["path"] == part), None) + if entry is None or entry["type"] != "tree": + return {}, head + tree = entry["sha"] + listed: dict[str, tuple[str, str]] = {} + pending = [(directory, tree)] + while pending: + where, oid = pending.pop() + for e in self._tree_entries(oid): + if e["type"] == "tree": + pending.append((where / e["path"], e["sha"])) + else: + listed[str(where / e["path"])] = (e["type"], e["sha"]) + return listed, head + + def push_request_branch(self, req: BranchRequest) -> PushResult: + """Through Gitea's REST API, not the Git layer: the chart's stand-in, whose Gitea the cluster serves over plain http, which + the Git layer refuses. A branch that exists is handled as the Git layer handles it (the arbitration of #286, row 3; + #450): adopted when its head is this request's commit of this plan with the plan's files; deleted and written again + when it is this request's own stale attempt; refused, and left as it is, when it is anyone else's. An open PR proves + nothing about the head. REST has no lease, so the delete of a stale attempt reads the head first (delete_branch).""" + branch = request_branch(req.cluster_id, req.request_id) + base = self.branch_head(self.default_branch) + if base is None: + raise GitUnavailable(f"branch {self.default_branch} does not exist") + existing = self.branch_head(branch) + if existing is not None: + trailers, parents = self._commit(existing) + planned = {p: t for p, t in req.files.items() if t is not None} + if trailers.get(TRAILER_REQUEST) != [req.request_id]: + raise BranchRefused(f"branch {branch} exists at {existing[:8]} and its head is not cmapi's commit for " + f"{req.request_id}: it is not adopted or overwritten") + if trailers.get(TRAILER_PLAN_HASH) == [req.plan_hash] and len(parents) == 1 and \ + self.read_folder(req.folder, existing)[0] == planned: + return PushResult(existing, parents[0], "adopted") + if not self.delete_branch(branch, existing): + raise BranchMoved(f"branch {branch} moved from {existing[:8]} before its stale attempt was replaced") + # The folder at main's commit, which the new branch starts from, read before the branch exists: a read that fails (a name + # that is not UTF-8, #626, or the host) leaves no branch at main's commit, which a retry would refuse as not cmapi's. + current, _ = self.read_folder(req.folder, base) + # A removal is any path of the folder, not only a manifest (#616). Only a plan that removes one walks the subfolders. + listed = self._walk(req.folder, base)[0] if any(text is None for text in req.files.values()) else {} + r = self._call("create_branch", "POST", f"{self._repo()}/branches", + json={"new_branch_name": branch, "old_ref_name": base}, ok=(201,)) + if r.status_code != 201: + raise GitUnavailable(f"create branch {branch}: {r.status_code} {self.host_text(r, 200)}") + ops = [] + for path, text in req.files.items(): + if text is None: + if path in listed: + ops.append({"operation": "delete", "path": path, "sha": listed[path][1]}) + elif path in current: + if current[path] != text: + ops.append({"operation": "update", "path": path, "sha": self._blob_sha(path, branch), "content": _b64(text)}) + else: + ops.append({"operation": "create", "path": path, "content": _b64(text)}) + if ops: + r = self._call("commit", "POST", f"{self._repo()}/contents", + json={"branch": branch, "message": req.message, "files": ops, + "author": {"name": self.BOT_NAME, "email": self.BOT_EMAIL}, + "committer": {"name": self.BOT_NAME, "email": self.BOT_EMAIL}}, ok=(200, 201)) + if r.status_code not in (200, 201): + raise GitUnavailable(f"commit on {branch}: {r.status_code} {self.host_text(r)}") + head = self.branch_head(branch) + return PushResult(head or base, base, "created" if existing is None else "replaced") + + def _commit(self, sha: str) -> tuple[dict[str, list[str]], list[str]]: + """A commit's cmapi trailers ({key: [values]}, from its message's last paragraph) and its parents' shas.""" + r = self._call("commit_read", "GET", f"{self._repo()}/git/commits/{sha}", ok=(200,)) + if r.status_code != 200: + raise GitUnavailable(f"read commit {sha[:8]}: {r.status_code} {self.host_text(r, 200)}") + body = r.json() + paragraphs = [p for p in ((body.get("commit") or {}).get("message") or "").strip().split("\n\n") if p.strip()] + trailers: dict[str, list[str]] = {} + for line in (paragraphs[-1].splitlines() if paragraphs else []): + key, sep, value = line.partition(":") + if sep and key.strip() in (TRAILER_REQUEST, TRAILER_PLAN_HASH): + trailers.setdefault(key.strip(), []).append(value.strip()) + return trailers, [p["sha"] for p in body.get("parents") or []] + + + def recreate_branch(self, req: BranchRequest, base: str, expected: str) -> str: + raise GitUnavailable("the Gitea stand-in is not on the Git layer: a closed PR's branch is not re-created") + + def open_pr(self, branch: str, head: str, title: str, body: str) -> PrRef: + existing = self.find_pr(branch) + if existing is None: + r = self._call("open_pr", "POST", f"{self._repo()}/pulls", + json={"head": branch, "base": self.default_branch, "title": title, "body": body}, ok=(201,)) + if r.status_code != 201: + raise GitUnavailable(f"open PR from {branch}: {r.status_code} {self.host_text(r)}") + existing = self._pr_ref(r.json()) + return existing + + def comment(self, pr: PrRef, text: str) -> None: + self._call("comment", "POST", f"{self._repo()}/issues/{pr.number}/comments", json={"body": text}, ok=(201,)) + + def delete_branch(self, branch: str, expected: str) -> bool: + """Gitea's REST delete is not conditional: the head is read first, and a race in between is the stand-in's to accept.""" + head = self.branch_head(branch) + if head is None: + return True + if head != expected: + return False + r = self._call("delete_branch", "DELETE", f"{self._repo()}/branches/{quote(branch)}", ok=(204, 404)) + return r.status_code in (204, 404) + + def _list_pages(self, operation: str, resource: str, **filters: str) -> Iterator[dict[str, Any]]: + path = f"{self._repo()}/{resource}" + for page in count(1): + response = self._call(operation, "GET", path, params={**filters, "limit": 50, "page": page}) + if response.status_code != 200: + raise GitUnavailable(f"{operation}: GET {path} page {page}: HTTP {response.status_code}") + yield from response.json() + if "next" not in response.links: + return + + def list_open(self, prefix: str) -> list[PrRef]: + return [self._pr_ref(p) for p in self._list_pages("find_pr", "pulls", state="open") + if p["head"]["ref"].startswith(prefix)] + + def list_branches(self, prefix: str) -> dict[str, str]: + return {b["name"]: b["commit"]["id"] for b in self._list_pages("branches", "branches") + if b["name"].startswith(prefix)} + + def branch_time(self, sha: str) -> int: + from datetime import datetime + + r = self._call("commit_read", "GET", f"{self._repo()}/git/commits/{sha}") + return int(datetime.fromisoformat(r.json()["created"].replace("Z", "+00:00")).timestamp()) + + def contains(self, revision: str, sha: str) -> bool: + if revision == sha: + return True + r = self._call("compare", "GET", f"{self._repo()}/compare/{quote(revision)}...{sha}") + if r.status_code == 404: # not this repository's: a multi-source Application's other source, or a force-pushed commit + return False + if r.status_code != 200: + raise GitUnavailable(f"compare {revision[:8]}...{sha[:8]}: {r.status_code} {self.host_text(r, 200)}") + return r.json().get("total_commits", 1) == 0 + + def changed_paths(self, head: str) -> set[str]: + r = self._call("compare", "GET", f"{self._repo()}/compare/{quote(self.default_branch)}...{head}") + if r.status_code != 200: + raise GitUnavailable(f"compare {head[:8]}: {r.status_code} {self.host_text(r, 200)}") + return {f["filename"] for c in r.json().get("commits") or [] for f in c.get("files") or []} + + def _blob_sha(self, path: str, ref: str) -> str: + r = self._call("read_file", "GET", f"{self._repo()}/contents/{quote(path)}", params={"ref": ref}) + return r.json()["sha"] + + 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"]) + + def find_pr(self, branch: str) -> PrRef | None: + r = self._call("find_pr", "GET", f"{self._repo()}/pulls", params={"state": "open", "limit": 50}) + for p in r.json(): + if p["head"]["ref"] == branch: + return self._pr_ref(p) + return None + + def pr_status(self, pr: PrRef, *, ci: bool = True) -> PrStatus: + r = self._call("pr_status", "GET", f"{self._repo()}/pulls/{pr.number}") + if r.status_code != 200: + raise GitUnavailable(f"PR {pr.number}: {r.status_code}") + p = r.json() + head = p["head"]["sha"] + checks: dict[str, CheckState] = {} + if ci: + s = self._call("pr_checks", "GET", f"{self._repo()}/commits/{head}/status", ok=(200, 404)) + if s.status_code == 200: + for st in s.json().get("statuses") or []: + checks[st["context"]] = {"success": "success", "pending": "pending"}.get(st["status"], "failure") + state = "merged" if p.get("merged") else ("open" if p["state"] == "open" else "closed") + return PrStatus(state=state, checks=checks, merge_sha=p.get("merge_commit_sha") if p.get("merged") else None, head_sha=head) + + def set_check(self, sha: str, context: str, state: CheckState, description: str, target_url: str | None = None) -> None: + body = {"context": context, "state": state, "description": description[:255]} + if target_url: + body["target_url"] = target_url + r = self._call("set_check", "POST", f"{self._repo()}/statuses/{sha}", json=body, ok=(201,)) + if r.status_code != 201: + raise GitUnavailable(f"status {context} on {sha[:8]}: {r.status_code} {self.host_text(r, 200)}") + + def merge(self, pr: PrRef, expected_head: str) -> str: + r = self._call("merge", "POST", f"{self._repo()}/pulls/{pr.number}/merge", + json={"Do": "merge", "head_commit_id": expected_head, "delete_branch_after_merge": False, + "MergeTitleField": f"Merge {pr.branch}"}, ok=(200,)) + if r.status_code != 200: + raise GitUnavailable(f"merge PR {pr.number}: {r.status_code} {self.host_text(r)}") + p = self._call("pr_status", "GET", f"{self._repo()}/pulls/{pr.number}").json() + return p.get("merge_commit_sha") or self.branch_head(self.default_branch) or "" + + def close(self, pr: PrRef, comment: str) -> None: + self._call("comment", "POST", f"{self._repo()}/issues/{pr.number}/comments", json={"body": comment}, ok=(201,)) + self._call("close", "PATCH", f"{self._repo()}/pulls/{pr.number}", json={"state": "closed"}, ok=(201, 200)) + + def log(self, n: int = 20) -> list[str]: + r = self._call("log", "GET", f"{self._repo()}/commits", params={"sha": self.default_branch, "limit": n}) + return self.commit_lines(r.json()) + + +def _b64(text: str) -> str: + return base64.b64encode(text.encode()).decode() + + +def _common_folder(files: Mapping[str, Any]) -> str: + paths = list(files) + if not paths: + return "" + parts = paths[0].split("/")[:-1] + for p in paths[1:]: + q = p.split("/")[:-1] + while parts and parts != q[:len(parts)]: + parts = parts[:-1] + return "/".join(parts) diff --git a/cmapi/src/cmapi/core/git/github.py b/cmapi/src/cmapi/core/git/github.py index e5400340..844b91dc 100644 --- a/cmapi/src/cmapi/core/git/github.py +++ b/cmapi/src/cmapi/core/git/github.py @@ -1,368 +1,368 @@ -"""GitHub: the Git layer for every branch, commit and read in the worker (core/git/workspace.py), and REST for the PR (#286). - -The worker writes the request branch with git, pushes it with a lease, and deletes it with a lease. GitHub's REST API opens the -PR, reads its state, merges it pinned to a sha, comments and closes. - -Host CI is on by default (instance.git.hostChecks, #60): the config repository's GitHub Actions run kubeconform and Kyverno, and -pr_status reads their outcome as the workflow jobs ci/kubeconform and ci/kyverno of the PR head, through the Actions API: the -runs of one workflow file (instance.git.ciWorkflow, ci.yml unless set) for the pull_request event, never a job of that name -in another workflow or in a push run. Not the commit statuses: an Actions job reports a check run, never a commit status -(measured on cmapi-cluster-configs, 2026-12-01), and a status can be posted by any token that holds Commit statuses write, the -bot's included. Not the Checks API either: a fine-grained token has no Checks permission (BUG-69, #279), while "Actions" read -covers the runs and jobs endpoints (GitHub, "Permissions required for fine-grained personal access tokens", fetched -2026-12-01). The worker posts one commit status, cmapi/check, and never a ci/* context on GitHub. With hostChecks false it -reads no CI and posts nothing unless instance.git.postStatus is on (the arbitration of #286, row 11). - -The API process has no Git layer: the bot's SSH key is mounted in the worker alone (F2), so plan-time reads of a folder, the -branch head and the log go through the contents, branches and commits endpoints with the bot's token, as before #286 (the -arbitration, row 12: for PR-A). - -The bot account's token: Contents read and write (git fetch and push over HTTPS, and the reads above), Pull requests read and -write, Metadata read; with host CI on (the default), Actions read and Commit statuses read and write; Commit statuses read and -write alone with postStatus. Endpoints as documented by GitHub (2026-11, 2026-12): - - GET /repos/{o}/{r}/pulls?head=&state=open POST /repos/{o}/{r}/pulls GET /repos/{o}/{r}/pulls/{n} - PUT /repos/{o}/{r}/pulls/{n}/merge {sha} PATCH /repos/{o}/{r}/pulls/{n} POST /repos/{o}/{r}/issues/{n}/comments - GET /repos/{o}/{r}/actions/workflows/{file}/runs?head_sha=&event=pull_request - GET /repos/{o}/{r}/actions/runs/{id}/jobs?filter=latest GET /repos/{o}/{r}/actions/runs/{id} - POST /repos/{o}/{r}/statuses/{sha} GET /repos/{o}/{r}/pulls?state=open (list) - The API process, reads only: GET /repos/{o}/{r}/branches/{b}, /contents/{path}?ref= (the folder's tree sha), /commits?sha=, - /git/commits/{sha}, /git/trees/{sha}[?recursive=1] (the folder read_folder reads, and the one a delete lists, #616), - /git/blobs/{sha} (a manifest) -""" -from __future__ import annotations - -import base64 -from typing import Any, Iterable, Mapping -from urllib.parse import quote - -from cmapi.core.git.base import (BranchRequest, CheckState, GitUnavailable, HeadMoved, HostGitProvider, IncompleteList, MergeCheck, - NotMergeable, PlatformRefused, PushResult, manifest_text, refuse_lost_names) -from cmapi.core.ports import PrRef, PrStatus - - -def _worse(a: CheckState | None, b: CheckState) -> CheckState: - """One context reported twice reads as the worse report: a pass from one source never hides the other's failure.""" - return max(a or b, b, key=("success", "pending", "failure").index) - - -def _job_state(job: Mapping[str, Any]) -> CheckState: - """What one workflow job says about a required check (the rule of #87, e6300b8c, on the job that reports the check run). - Unfinished is pending, whatever else the job carries; a null conclusion has not reported an outcome yet, even when status - already says completed. Finished is a pass only on success. GitHub's branch protection also passes skipped and neutral, but - here ci/* is the evidence that the validation ran and passed, and a skipped job validated nothing, so they fail.""" - conclusion = job.get("conclusion") - if job.get("status") != "completed" or conclusion is None: - return "pending" - return "success" if conclusion == "success" else "failure" - - -class GitHubProvider(HostGitProvider): - name = "github" - posts_ci = False # ci/* come from the repository's Actions or from nobody; the worker posts cmapi/check alone (#60) - MAX_PAGES = 100 # 10,000 entries: past this a host is not answering a list, and a partial list must not read as complete - # "This endpoint will return up to 1,000 results for each search when using the following parameters: ... head_sha" (REST - # docs, Workflow runs, fetched 2026-12-01): that many runs on one commit may be a list GitHub cut. - MAX_RUNS_PER_SHA = 1000 - # The file name, under .github/workflows/, of the config repository's workflow whose jobs are the CI: "You can replace - # workflow_id with the workflow file name. For example, you could use main.yaml" (REST docs, List workflow runs for a - # workflow, fetched 2026-12-01). The template's name (examples/cluster-configs/.github/workflows/ci.yml). - CI_WORKFLOW = "ci.yml" - - def __init__(self, api_url: str, repository: str, token: str, *, workspace=None, host_checks: bool = True, - post_status: bool = False, ci_workflow: str | None = None, **kw: Any): - super().__init__(api_url, repository, token, **kw) - self.workspace = workspace - self.ci_workflow = ci_workflow or self.CI_WORKFLOW - self.external_ci = bool(host_checks) - self.post_statuses = bool(host_checks or post_status) - - def _headers(self, token: str) -> dict[str, str]: - return {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json", - "X-GitHub-Api-Version": "2022-11-28"} - - def _repo(self) -> str: - return f"/repos/{self.repository}" - - def _git(self): - if self.workspace is None: - raise GitUnavailable("this process has no Git layer: only the worker writes branches (core/context.py)") - return self.workspace - - # ---- the Git side: the Git layer in the worker; REST reads in the API process - def branch_head(self, branch: str) -> str | None: - if self.workspace is not None: - return self.workspace.branch_head(branch) - # One path parameter: GitHub asks for a "/" in it as %2F, and "#", "?" and "%" are escaped as data (#638). - r = self._call("branch_head", "GET", f"{self._repo()}/branches/{quote(branch, safe='')}", ok=(200, 404)) - return r.json()["commit"]["sha"] if r.status_code == 200 else None - - def read_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: - """The regular .yaml files directly in path at ref, read from the folder's tree as workspace._folder reads them (#625, - #632). Not from the Contents listing: version 2022-11-28 lists a submodule and a symlink to a file as "file", reads - that symlink as its target's text, lists at most 1,000 entries, and gives no content for a file past 1 MB. A tree - types each entry by its mode, and a blob read holds up to 100 MB. Contents still finds the folder in one request: its - object form carries the folder's tree sha (REST docs, Repository contents and Git blobs, fetched 2026-11-23).""" - if self.workspace is not None: - return self.workspace.read_folder(path, ref) - head = self._folder_head(ref) - directory = path.strip("/") - # A path is data in the URL: "#" or "?" would end it (RFC 3986, section 3.3), and "%41" would read as "A". - r = self._call("read_folder", "GET", f"{self._repo()}/contents/{quote(directory)}", params={"ref": head}, - headers={"Accept": "application/vnd.github.object+json"}, ok=(200, 404)) - if r.status_code == 404: - return {}, head - if r.status_code != 200: # 403 is a refusal or a rate limit (REST docs), never a missing folder - raise GitUnavailable(f"read folder {directory} at {head[:8]}: HTTP {r.status_code}") - found = r.json() - if found["type"] != "dir": # a file, symlink or submodule: git ls-tree of "/" lists nothing either - return {}, head - prefix = f"{directory}/" if directory else "" - manifests = {prefix + e["path"]: e["sha"] for e in self._tree(found["sha"]) - if e["type"] == "blob" and e["mode"] in ("100644", "100755") and e["path"].endswith(".yaml")} - refuse_lost_names(manifests) # a byte that is not UTF-8 came as U+FFFD: no plan can name the file (#626) - return manifest_text({p: self._blob_bytes(sha) for p, sha in manifests.items()}), head - - def _blob_bytes(self, sha: str) -> bytes: - """GET git/blobs/{sha}: "The content in the response will always be Base64 encoded", for blobs up to 100 MB (REST docs, - Git blobs, fetched 2026-11-23). manifest_text reads it as strict UTF-8, as the worker reads a manifest.""" - b = self._call("read_file", "GET", f"{self._repo()}/git/blobs/{sha}") - if b.status_code != 200: - raise GitUnavailable(f"read blob {sha[:8]}: HTTP {b.status_code}") - return base64.b64decode(b.json()["content"]) - - def _tree(self, oid: str, *, recursive: bool = False) -> list[dict[str, Any]]: - """GET git/trees/{oid}: the entries of one tree, or of every tree under it. "If truncated is true in the response then - the number of items in the tree array exceeded our maximum limit" (100,000 entries or 7 MB recursive; REST docs, - 2026-11): IncompleteList, never a short list read as complete.""" - r = self._call("list_folder", "GET", f"{self._repo()}/git/trees/{oid}", params={"recursive": "1"} if recursive else None) - if r.status_code != 200: - raise GitUnavailable(f"read tree {oid[:8]}: HTTP {r.status_code}") - body = r.json() - if body.get("truncated"): - raise IncompleteList(f"the tree {oid[:8]} is truncated: past GitHub's limit for a tree") - return body["tree"] - - def list_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: - """The Git Trees API, not Contents: a tree gives each entry's Git type and mode, and Contents stops at 1,000 entries. - From the commit's root tree (GET git/commits/{sha}), the walk to the folder reads one tree per part, then the folder's - tree with recursive=1.""" - if self.workspace is not None: - return self.workspace.list_folder(path, ref) - head = self._folder_head(ref) - c = self._call("list_folder", "GET", f"{self._repo()}/git/commits/{head}") - if c.status_code != 200: - raise GitUnavailable(f"read commit {head[:8]}: HTTP {c.status_code}") - directory = path.strip("/") - tree = c.json()["tree"]["sha"] - for part in filter(None, directory.split("/")): - entry = next((e for e in self._tree(tree) if e["path"] == part), None) - if entry is None or entry["type"] != "tree": - return {}, head - tree = entry["sha"] - prefix = f"{directory}/" if directory else "" - listed = {prefix + e["path"]: e["type"] for e in self._tree(tree, recursive=True) if e["type"] in ("blob", "commit")} - refuse_lost_names(listed) # a delete removes each path, so it must name each one (#626) - return listed, head - - def log(self, n: int = 20) -> list[str]: - if self.workspace is not None: - # The Git layer's token is in oplog's registry, not in this provider's forms (#424). - from cmapi.core.git.oplog import redact as redact_registered - - return [redact_registered(line) for line in self.workspace.log(n)] - r = self._call("log", "GET", f"{self._repo()}/commits", params={"sha": self.default_branch, "per_page": n}) - return self.commit_lines(r.json()) - - def contains(self, revision: str, sha: str) -> bool: - return self._git().contains(revision, sha) - - def changed_paths(self, head: str) -> set[str]: - return self._git().changed_paths(head) - - def push_request_branch(self, req: BranchRequest) -> PushResult: - return self._git().push_branch(req) - - def recreate_branch(self, req: BranchRequest, base: str, expected: str) -> str: - return self._git().recreate(req, base, expected) - - def merge_check(self, head: str, folder: str, prev: Mapping[str, str], files: Mapping[str, str | None], *, - whole_folder: bool = False) -> MergeCheck: - return self._git().merge_check(head, folder, prev, files, whole_folder=whole_folder) - - def delete_branch(self, branch: str, expected: str) -> bool: - return self._git().delete_branch(branch, expected) - - def list_branches(self, prefix: str) -> dict[str, str]: - return self._git().ls_remote(f"{prefix}*") - - def branch_time(self, sha: str) -> int: - return self._git().commit_time(sha) - - def request_of(self, sha: str) -> str | None: - ws = self._git() - with ws._lock: - ws._need(sha) - ids = ws.trailers(sha)["Cmapi-Request-Id"] - return ids[0] if len(ids) == 1 else None - - def cleanup(self, cluster_id: str, request_id: str) -> None: - if self.workspace is not None: - self.workspace.remove(cluster_id, request_id) - - def sweep(self, open_requests: Iterable[tuple[str, str]]): - return self.workspace.sweep(open_requests) if self.workspace is not None else None - - def dispose(self) -> None: - if self.workspace is not None: - self.workspace.dispose() - - # ---- 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"]) - - def find_pr(self, branch: str) -> PrRef | None: - owner = self.repository.split("/")[0] - r = self._call("pr_find", "GET", f"{self._repo()}/pulls", params={"state": "open", "head": f"{owner}:{branch}"}, ok=(200,)) - if r.status_code != 200: - text = self.host_text(r) - raise PlatformRefused(f"find the PR of {branch}: {r.status_code} {text[:200]}", r.status_code, text) - prs = r.json() - if len(prs) > 1: - raise PlatformRefused(f"{len(prs)} open PRs from {branch}: one is expected") - return self._pr_ref(prs[0]) if prs else None - - def open_pr(self, branch: str, head: str, title: str, body: str) -> PrRef: - existing = self.find_pr(branch) - if existing is None: - r = self._call("pr_open", "POST", f"{self._repo()}/pulls", - json={"head": branch, "base": self.default_branch, "title": title, "body": body}, ok=(201,)) - if r.status_code != 201: - existing = self.find_pr(branch) if r.status_code == 422 else None # "A pull request already exists" - if existing is None: - text = self.host_text(r) - raise PlatformRefused(f"open PR from {branch}: {r.status_code} {text}", r.status_code, text) - else: - existing = self._pr_ref(r.json()) - if existing.head_sha != head: - raise HeadMoved(f"PR #{existing.number} is on {existing.head_sha[:8]}, not on the pushed head {head[:8]}") - return existing - - def _pages(self, operation: str, path: str, key: str | None, **params: Any) -> list[Mapping[str, Any]]: - """Every entry of a paginated list, or GitUnavailable: an unread page could hold the answer.""" - return [entry for batch in self._page_batches(operation, path, key, **params) for entry in batch] - - def _page_batches(self, operation: str, path: str, key: str | None, **params: Any) -> Iterable[list[Mapping[str, Any]]]: - """The same list, one page at a time, for a caller that must know how many pages it read. The Link header says only - whether there is a next page. Its URL is not called, because this client sends the token with every request.""" - for page in range(1, self.MAX_PAGES + 1): - r = self._call(operation, "GET", path, params={**params, "per_page": 100, "page": page}, ok=(200,)) - if r.status_code != 200: - raise GitUnavailable(f"{operation}: GET {path} page {page}: {r.status_code} {self.host_text(r, 200)}") - body = r.json() - yield ((body.get(key) or []) if key else body) - if "next" not in r.links: - return - raise GitUnavailable(f"{operation}: GET {path} has more than {self.MAX_PAGES} pages") - - def list_open(self, prefix: str) -> list[PrRef]: - return [self._pr_ref(p) for p in self._pages("pr_list", f"{self._repo()}/pulls", None, state="open") - if p["head"]["ref"].startswith(prefix)] - - def pr_status(self, pr: PrRef, *, ci: bool = True) -> PrStatus: - r = self._call("pr_state", "GET", f"{self._repo()}/pulls/{pr.number}", ok=(200,)) - if r.status_code != 200: - text = self.host_text(r) - raise PlatformRefused(f"PR {pr.number}: {r.status_code} {text[:200]}", r.status_code, text) - p = r.json() - head = (p.get("head") or {}).get("sha") - if p["state"] != "open": # nothing reads a finished PR's checks, and a refused read must not hold back recording its end - merged = bool(p.get("merged")) - return PrStatus(state="merged" if merged else "closed", checks={}, merge_sha=p.get("merge_commit_sha") if merged else None, - head_sha=head) - # CI counts only for the head this request approved (pr.head_sha, the head the PR was opened on). A PR the host reports - # on another head, or on none, gives no CI: the worker fails its cmapi check on the head_sha returned here. - checks = self._actions_checks(pr) if ci and self.external_ci and head and head == pr.head_sha else {} - return PrStatus(state="open", checks=checks, head_sha=head) - - def _actions_checks(self, pr: PrRef) -> dict[str, CheckState]: - """The jobs of the CI workflow's pull_request runs on the approved head, by job name: a job named ci/kyverno is the - check run ci/kyverno that branch protection requires (measured: the job and its check run share their name and id). - The workflow is asked for by its file name, so a job of that name in another workflow says nothing, and by its event, - so a push run does not either. A run is this PR's when it is on the PR's commit and branch in this repository: - head_sha, head_branch and head_repository.full_name are required fields of a run (github/rest-api-description, - workflow-run, fetched 2026-12-01), and a fork's PR on the same commit and branch name carries the fork as its - head_repository. Not pull_requests: it holds only "Pull requests that are open with a head_sha or head_branch that - matches the workflow run", "do not necessarily indicate pull requests that triggered the run" (the same schema), and - was empty on every pull_request run of cmapi-cluster-configs measured 2026-12-01, so requiring it could leave every - request waiting. Two jobs of one name read as the worse. filter=latest reads a re-run's newest attempt. Commit - statuses are not read: the worker's own token can post those.""" - head = pr.head_sha - workflow = f"{self._repo()}/actions/workflows/{quote(self.ci_workflow, safe='')}" - runs = self._pages("ci_runs", f"{workflow}/runs", "workflow_runs", head_sha=head, event="pull_request") - if len(runs) >= self.MAX_RUNS_PER_SHA: - raise IncompleteList(f"{len(runs)} workflow runs on {head[:8]}: GitHub lists at most {self.MAX_RUNS_PER_SHA}") - checks: dict[str, CheckState] = {} - for run in runs: - # The filters are GitHub's; a run of another commit or event says nothing about this PR. - if run.get("head_sha") != head or run.get("event") != "pull_request": - continue - # A fork's PR, or another branch at the same commit, is not this PR. GitHub's names do not tell case apart. - source = ((run.get("head_repository") or {}).get("full_name") or "").lower() - if run.get("head_branch") != pr.branch or source != self.repository.lower(): - continue - path = f"{self._repo()}/actions/runs/{run['id']}" - pages = 0 - for jobs in self._page_batches("ci_jobs", f"{path}/jobs", "jobs", filter="latest"): - pages += 1 - for job in jobs: - checks[job["name"]] = _worse(checks.get(job["name"]), _job_state(job)) - if pages > 1: - # Each page asked for the latest attempt on its own, so a re-run that started between two pages mixes two - # attempts. run_attempt is "1 for first attempt and higher if the workflow was re-run" (github/rest-api- - # description, workflow-run, fetched 2026-12-01). One page is one answer and needs no second read. - latest = self._call("ci_runs", "GET", path, ok=(200,)) - if latest.status_code != 200: - raise GitUnavailable(f"ci_runs: GET {path}: {latest.status_code} {self.host_text(latest, 200)}") - if latest.json().get("run_attempt") != run.get("run_attempt"): - return {} # nothing is known this poll: each context reads as pending, and the next poll reads again - return checks - - def set_check(self, sha: str, context: str, state: CheckState, description: str, target_url: str | None = None) -> None: - body: dict[str, Any] = {"context": context, "state": state, "description": description[:140]} - if target_url: - body["target_url"] = target_url - r = self._call("status_write", "POST", f"{self._repo()}/statuses/{sha}", json=body, ok=(201,)) - if r.status_code != 201: - raise GitUnavailable(f"status {context} on {sha[:8]}: {r.status_code} {self.host_text(r, 200)}") - - def merge(self, pr: PrRef, expected_head: str) -> str: - """PUT .../merge with sha: GitHub merges only if the head is that sha. 409 is HeadMoved, 405 NotMergeable. The branch is - not deleted here: git_cleanup deletes it with a lease.""" - r = self._call("merge", "PUT", f"{self._repo()}/pulls/{pr.number}/merge", ok=(200,), log_fields={"pinned_sha": expected_head, - "pr_number": pr.number, "merge_method": "merge"}, - json={"sha": expected_head, "merge_method": "merge", "commit_title": f"Merge {pr.branch}"}) - if r.status_code == 200: - return r.json()["sha"] - message = self.host_text(r) - if r.status_code == 409: - raise HeadMoved(f"merge PR {pr.number}: the head is not {expected_head[:8]}: {message}", 409, message) - if r.status_code == 405: - said = r.text[:300].lower() # the decision reads the host's own words; only the message is redacted - raise NotMergeable(f"merge PR {pr.number}: {message}", transient="pending" in said or "expected" in said) - raise PlatformRefused(f"merge PR {pr.number}: {r.status_code} {message}", r.status_code, message) - - def comment(self, pr: PrRef, text: str) -> None: - """At most once per text: a retry after a lost answer finds the comment the host kept, and posts nothing (#451). A read - before the write, not a host idempotency key: two writers at the same moment could still both post.""" - if any(c.get("body") == text for c in self._pages("pr_comments", f"{self._repo()}/issues/{pr.number}/comments", None)): - return - r = self._call("pr_comment", "POST", f"{self._repo()}/issues/{pr.number}/comments", json={"body": text}, ok=(201,)) - if r.status_code != 201: - raise PlatformRefused(f"comment on PR {pr.number}: {r.status_code}", r.status_code, self.host_text(r)) - - def close(self, pr: PrRef, comment: str) -> None: - self.comment(pr, comment) - r = self._call("pr_close", "PATCH", f"{self._repo()}/pulls/{pr.number}", json={"state": "closed"}, ok=(200,)) - if r.status_code != 200: - raise PlatformRefused(f"close PR {pr.number}: {r.status_code}", r.status_code, self.host_text(r)) +"""GitHub: the Git layer for every branch, commit and read in the worker (core/git/workspace.py), and REST for the PR (#286). + +The worker writes the request branch with git, pushes it with a lease, and deletes it with a lease. GitHub's REST API opens the +PR, reads its state, merges it pinned to a sha, comments and closes. + +Host CI is on by default (instance.git.hostChecks, #60): the config repository's GitHub Actions run kubeconform and Kyverno, and +pr_status reads their outcome as the workflow jobs ci/kubeconform and ci/kyverno of the PR head, through the Actions API: the +runs of one workflow file (instance.git.ciWorkflow, ci.yml unless set) for the pull_request event, never a job of that name +in another workflow or in a push run. Not the commit statuses: an Actions job reports a check run, never a commit status +(measured on cmapi-cluster-configs, 2026-12-01), and a status can be posted by any token that holds Commit statuses write, the +bot's included. Not the Checks API either: a fine-grained token has no Checks permission (BUG-69, #279), while "Actions" read +covers the runs and jobs endpoints (GitHub, "Permissions required for fine-grained personal access tokens", fetched +2026-12-01). The worker posts one commit status, cmapi/check, and never a ci/* context on GitHub. With hostChecks false it +reads no CI and posts nothing unless instance.git.postStatus is on (the arbitration of #286, row 11). + +The API process has no Git layer: the bot's SSH key is mounted in the worker alone (F2), so plan-time reads of a folder, the +branch head and the log go through the contents, branches and commits endpoints with the bot's token, as before #286 (the +arbitration, row 12: for PR-A). + +The bot account's token: Contents read and write (git fetch and push over HTTPS, and the reads above), Pull requests read and +write, Metadata read; with host CI on (the default), Actions read and Commit statuses read and write; Commit statuses read and +write alone with postStatus. Endpoints as documented by GitHub (2026-11, 2026-12): + + GET /repos/{o}/{r}/pulls?head=&state=open POST /repos/{o}/{r}/pulls GET /repos/{o}/{r}/pulls/{n} + PUT /repos/{o}/{r}/pulls/{n}/merge {sha} PATCH /repos/{o}/{r}/pulls/{n} POST /repos/{o}/{r}/issues/{n}/comments + GET /repos/{o}/{r}/actions/workflows/{file}/runs?head_sha=&event=pull_request + GET /repos/{o}/{r}/actions/runs/{id}/jobs?filter=latest GET /repos/{o}/{r}/actions/runs/{id} + POST /repos/{o}/{r}/statuses/{sha} GET /repos/{o}/{r}/pulls?state=open (list) + The API process, reads only: GET /repos/{o}/{r}/branches/{b}, /contents/{path}?ref= (the folder's tree sha), /commits?sha=, + /git/commits/{sha}, /git/trees/{sha}[?recursive=1] (the folder read_folder reads, and the one a delete lists, #616), + /git/blobs/{sha} (a manifest) +""" +from __future__ import annotations + +import base64 +from typing import Any, Iterable, Mapping +from urllib.parse import quote + +from cmapi.core.git.base import (BranchRequest, CheckState, GitUnavailable, HeadMoved, HostGitProvider, IncompleteList, MergeCheck, + NotMergeable, PlatformRefused, PushResult, manifest_text, refuse_lost_names) +from cmapi.core.ports import PrRef, PrStatus + + +def _worse(a: CheckState | None, b: CheckState) -> CheckState: + """One context reported twice reads as the worse report: a pass from one source never hides the other's failure.""" + return max(a or b, b, key=("success", "pending", "failure").index) + + +def _job_state(job: Mapping[str, Any]) -> CheckState: + """What one workflow job says about a required check (the rule of #87, e6300b8c, on the job that reports the check run). + Unfinished is pending, whatever else the job carries; a null conclusion has not reported an outcome yet, even when status + already says completed. Finished is a pass only on success. GitHub's branch protection also passes skipped and neutral, but + here ci/* is the evidence that the validation ran and passed, and a skipped job validated nothing, so they fail.""" + conclusion = job.get("conclusion") + if job.get("status") != "completed" or conclusion is None: + return "pending" + return "success" if conclusion == "success" else "failure" + + +class GitHubProvider(HostGitProvider): + name = "github" + posts_ci = False # ci/* come from the repository's Actions or from nobody; the worker posts cmapi/check alone (#60) + MAX_PAGES = 100 # 10,000 entries: past this a host is not answering a list, and a partial list must not read as complete + # "This endpoint will return up to 1,000 results for each search when using the following parameters: ... head_sha" (REST + # docs, Workflow runs, fetched 2026-12-01): that many runs on one commit may be a list GitHub cut. + MAX_RUNS_PER_SHA = 1000 + # The file name, under .github/workflows/, of the config repository's workflow whose jobs are the CI: "You can replace + # workflow_id with the workflow file name. For example, you could use main.yaml" (REST docs, List workflow runs for a + # workflow, fetched 2026-12-01). The template's name (examples/cluster-configs/.github/workflows/ci.yml). + CI_WORKFLOW = "ci.yml" + + def __init__(self, api_url: str, repository: str, token: str, *, workspace=None, host_checks: bool = True, + post_status: bool = False, ci_workflow: str | None = None, **kw: Any): + super().__init__(api_url, repository, token, **kw) + self.workspace = workspace + self.ci_workflow = ci_workflow or self.CI_WORKFLOW + self.external_ci = bool(host_checks) + self.post_statuses = bool(host_checks or post_status) + + def _headers(self, token: str) -> dict[str, str]: + return {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28"} + + def _repo(self) -> str: + return f"/repos/{self.repository}" + + def _git(self): + if self.workspace is None: + raise GitUnavailable("this process has no Git layer: only the worker writes branches (core/context.py)") + return self.workspace + + # ---- the Git side: the Git layer in the worker; REST reads in the API process + def branch_head(self, branch: str) -> str | None: + if self.workspace is not None: + return self.workspace.branch_head(branch) + # One path parameter: GitHub asks for a "/" in it as %2F, and "#", "?" and "%" are escaped as data (#638). + r = self._call("branch_head", "GET", f"{self._repo()}/branches/{quote(branch, safe='')}", ok=(200, 404)) + return r.json()["commit"]["sha"] if r.status_code == 200 else None + + def read_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: + """The regular .yaml files directly in path at ref, read from the folder's tree as workspace._folder reads them (#625, + #632). Not from the Contents listing: version 2022-11-28 lists a submodule and a symlink to a file as "file", reads + that symlink as its target's text, lists at most 1,000 entries, and gives no content for a file past 1 MB. A tree + types each entry by its mode, and a blob read holds up to 100 MB. Contents still finds the folder in one request: its + object form carries the folder's tree sha (REST docs, Repository contents and Git blobs, fetched 2026-11-23).""" + if self.workspace is not None: + return self.workspace.read_folder(path, ref) + head = self._folder_head(ref) + directory = path.strip("/") + # A path is data in the URL: "#" or "?" would end it (RFC 3986, section 3.3), and "%41" would read as "A". + r = self._call("read_folder", "GET", f"{self._repo()}/contents/{quote(directory)}", params={"ref": head}, + headers={"Accept": "application/vnd.github.object+json"}, ok=(200, 404)) + if r.status_code == 404: + return {}, head + if r.status_code != 200: # 403 is a refusal or a rate limit (REST docs), never a missing folder + raise GitUnavailable(f"read folder {directory} at {head[:8]}: HTTP {r.status_code}") + found = r.json() + if found["type"] != "dir": # a file, symlink or submodule: git ls-tree of "/" lists nothing either + return {}, head + prefix = f"{directory}/" if directory else "" + manifests = {prefix + e["path"]: e["sha"] for e in self._tree(found["sha"]) + if e["type"] == "blob" and e["mode"] in ("100644", "100755") and e["path"].endswith(".yaml")} + refuse_lost_names(manifests) # a byte that is not UTF-8 came as U+FFFD: no plan can name the file (#626) + return manifest_text({p: self._blob_bytes(sha) for p, sha in manifests.items()}), head + + def _blob_bytes(self, sha: str) -> bytes: + """GET git/blobs/{sha}: "The content in the response will always be Base64 encoded", for blobs up to 100 MB (REST docs, + Git blobs, fetched 2026-11-23). manifest_text reads it as strict UTF-8, as the worker reads a manifest.""" + b = self._call("read_file", "GET", f"{self._repo()}/git/blobs/{sha}") + if b.status_code != 200: + raise GitUnavailable(f"read blob {sha[:8]}: HTTP {b.status_code}") + return base64.b64decode(b.json()["content"]) + + def _tree(self, oid: str, *, recursive: bool = False) -> list[dict[str, Any]]: + """GET git/trees/{oid}: the entries of one tree, or of every tree under it. "If truncated is true in the response then + the number of items in the tree array exceeded our maximum limit" (100,000 entries or 7 MB recursive; REST docs, + 2026-11): IncompleteList, never a short list read as complete.""" + r = self._call("list_folder", "GET", f"{self._repo()}/git/trees/{oid}", params={"recursive": "1"} if recursive else None) + if r.status_code != 200: + raise GitUnavailable(f"read tree {oid[:8]}: HTTP {r.status_code}") + body = r.json() + if body.get("truncated"): + raise IncompleteList(f"the tree {oid[:8]} is truncated: past GitHub's limit for a tree") + return body["tree"] + + def list_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: + """The Git Trees API, not Contents: a tree gives each entry's Git type and mode, and Contents stops at 1,000 entries. + From the commit's root tree (GET git/commits/{sha}), the walk to the folder reads one tree per part, then the folder's + tree with recursive=1.""" + if self.workspace is not None: + return self.workspace.list_folder(path, ref) + head = self._folder_head(ref) + c = self._call("list_folder", "GET", f"{self._repo()}/git/commits/{head}") + if c.status_code != 200: + raise GitUnavailable(f"read commit {head[:8]}: HTTP {c.status_code}") + directory = path.strip("/") + tree = c.json()["tree"]["sha"] + for part in filter(None, directory.split("/")): + entry = next((e for e in self._tree(tree) if e["path"] == part), None) + if entry is None or entry["type"] != "tree": + return {}, head + tree = entry["sha"] + prefix = f"{directory}/" if directory else "" + listed = {prefix + e["path"]: e["type"] for e in self._tree(tree, recursive=True) if e["type"] in ("blob", "commit")} + refuse_lost_names(listed) # a delete removes each path, so it must name each one (#626) + return listed, head + + def log(self, n: int = 20) -> list[str]: + if self.workspace is not None: + # The Git layer's token is in oplog's registry, not in this provider's forms (#424). + from cmapi.core.git.oplog import redact as redact_registered + + return [redact_registered(line) for line in self.workspace.log(n)] + r = self._call("log", "GET", f"{self._repo()}/commits", params={"sha": self.default_branch, "per_page": n}) + return self.commit_lines(r.json()) + + def contains(self, revision: str, sha: str) -> bool: + return self._git().contains(revision, sha) + + def changed_paths(self, head: str) -> set[str]: + return self._git().changed_paths(head) + + def push_request_branch(self, req: BranchRequest) -> PushResult: + return self._git().push_branch(req) + + def recreate_branch(self, req: BranchRequest, base: str, expected: str) -> str: + return self._git().recreate(req, base, expected) + + def merge_check(self, head: str, folder: str, prev: Mapping[str, str], files: Mapping[str, str | None], *, + whole_folder: bool = False) -> MergeCheck: + return self._git().merge_check(head, folder, prev, files, whole_folder=whole_folder) + + def delete_branch(self, branch: str, expected: str) -> bool: + return self._git().delete_branch(branch, expected) + + def list_branches(self, prefix: str) -> dict[str, str]: + return self._git().ls_remote(f"{prefix}*") + + def branch_time(self, sha: str) -> int: + return self._git().commit_time(sha) + + def request_of(self, sha: str) -> str | None: + ws = self._git() + with ws._lock: + ws._need(sha) + ids = ws.trailers(sha)["Cmapi-Request-Id"] + return ids[0] if len(ids) == 1 else None + + def cleanup(self, cluster_id: str, request_id: str) -> None: + if self.workspace is not None: + self.workspace.remove(cluster_id, request_id) + + def sweep(self, open_requests: Iterable[tuple[str, str]]): + return self.workspace.sweep(open_requests) if self.workspace is not None else None + + def dispose(self) -> None: + if self.workspace is not None: + self.workspace.dispose() + + # ---- 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"]) + + def find_pr(self, branch: str) -> PrRef | None: + owner = self.repository.split("/")[0] + r = self._call("pr_find", "GET", f"{self._repo()}/pulls", params={"state": "open", "head": f"{owner}:{branch}"}, ok=(200,)) + if r.status_code != 200: + text = self.host_text(r) + raise PlatformRefused(f"find the PR of {branch}: {r.status_code} {text[:200]}", r.status_code, text) + prs = r.json() + if len(prs) > 1: + raise PlatformRefused(f"{len(prs)} open PRs from {branch}: one is expected") + return self._pr_ref(prs[0]) if prs else None + + def open_pr(self, branch: str, head: str, title: str, body: str) -> PrRef: + existing = self.find_pr(branch) + if existing is None: + r = self._call("pr_open", "POST", f"{self._repo()}/pulls", + json={"head": branch, "base": self.default_branch, "title": title, "body": body}, ok=(201,)) + if r.status_code != 201: + existing = self.find_pr(branch) if r.status_code == 422 else None # "A pull request already exists" + if existing is None: + text = self.host_text(r) + raise PlatformRefused(f"open PR from {branch}: {r.status_code} {text}", r.status_code, text) + else: + existing = self._pr_ref(r.json()) + if existing.head_sha != head: + raise HeadMoved(f"PR #{existing.number} is on {existing.head_sha[:8]}, not on the pushed head {head[:8]}") + return existing + + def _pages(self, operation: str, path: str, key: str | None, **params: Any) -> list[Mapping[str, Any]]: + """Every entry of a paginated list, or GitUnavailable: an unread page could hold the answer.""" + return [entry for batch in self._page_batches(operation, path, key, **params) for entry in batch] + + def _page_batches(self, operation: str, path: str, key: str | None, **params: Any) -> Iterable[list[Mapping[str, Any]]]: + """The same list, one page at a time, for a caller that must know how many pages it read. The Link header says only + whether there is a next page. Its URL is not called, because this client sends the token with every request.""" + for page in range(1, self.MAX_PAGES + 1): + r = self._call(operation, "GET", path, params={**params, "per_page": 100, "page": page}, ok=(200,)) + if r.status_code != 200: + raise GitUnavailable(f"{operation}: GET {path} page {page}: {r.status_code} {self.host_text(r, 200)}") + body = r.json() + yield ((body.get(key) or []) if key else body) + if "next" not in r.links: + return + raise GitUnavailable(f"{operation}: GET {path} has more than {self.MAX_PAGES} pages") + + def list_open(self, prefix: str) -> list[PrRef]: + return [self._pr_ref(p) for p in self._pages("pr_list", f"{self._repo()}/pulls", None, state="open") + if p["head"]["ref"].startswith(prefix)] + + def pr_status(self, pr: PrRef, *, ci: bool = True) -> PrStatus: + r = self._call("pr_state", "GET", f"{self._repo()}/pulls/{pr.number}", ok=(200,)) + if r.status_code != 200: + text = self.host_text(r) + raise PlatformRefused(f"PR {pr.number}: {r.status_code} {text[:200]}", r.status_code, text) + p = r.json() + head = (p.get("head") or {}).get("sha") + if p["state"] != "open": # nothing reads a finished PR's checks, and a refused read must not hold back recording its end + merged = bool(p.get("merged")) + return PrStatus(state="merged" if merged else "closed", checks={}, merge_sha=p.get("merge_commit_sha") if merged else None, + head_sha=head) + # CI counts only for the head this request approved (pr.head_sha, the head the PR was opened on). A PR the host reports + # on another head, or on none, gives no CI: the worker fails its cmapi check on the head_sha returned here. + checks = self._actions_checks(pr) if ci and self.external_ci and head and head == pr.head_sha else {} + return PrStatus(state="open", checks=checks, head_sha=head) + + def _actions_checks(self, pr: PrRef) -> dict[str, CheckState]: + """The jobs of the CI workflow's pull_request runs on the approved head, by job name: a job named ci/kyverno is the + check run ci/kyverno that branch protection requires (measured: the job and its check run share their name and id). + The workflow is asked for by its file name, so a job of that name in another workflow says nothing, and by its event, + so a push run does not either. A run is this PR's when it is on the PR's commit and branch in this repository: + head_sha, head_branch and head_repository.full_name are required fields of a run (github/rest-api-description, + workflow-run, fetched 2026-12-01), and a fork's PR on the same commit and branch name carries the fork as its + head_repository. Not pull_requests: it holds only "Pull requests that are open with a head_sha or head_branch that + matches the workflow run", "do not necessarily indicate pull requests that triggered the run" (the same schema), and + was empty on every pull_request run of cmapi-cluster-configs measured 2026-12-01, so requiring it could leave every + request waiting. Two jobs of one name read as the worse. filter=latest reads a re-run's newest attempt. Commit + statuses are not read: the worker's own token can post those.""" + head = pr.head_sha + workflow = f"{self._repo()}/actions/workflows/{quote(self.ci_workflow, safe='')}" + runs = self._pages("ci_runs", f"{workflow}/runs", "workflow_runs", head_sha=head, event="pull_request") + if len(runs) >= self.MAX_RUNS_PER_SHA: + raise IncompleteList(f"{len(runs)} workflow runs on {head[:8]}: GitHub lists at most {self.MAX_RUNS_PER_SHA}") + checks: dict[str, CheckState] = {} + for run in runs: + # The filters are GitHub's; a run of another commit or event says nothing about this PR. + if run.get("head_sha") != head or run.get("event") != "pull_request": + continue + # A fork's PR, or another branch at the same commit, is not this PR. GitHub's names do not tell case apart. + source = ((run.get("head_repository") or {}).get("full_name") or "").lower() + if run.get("head_branch") != pr.branch or source != self.repository.lower(): + continue + path = f"{self._repo()}/actions/runs/{run['id']}" + pages = 0 + for jobs in self._page_batches("ci_jobs", f"{path}/jobs", "jobs", filter="latest"): + pages += 1 + for job in jobs: + checks[job["name"]] = _worse(checks.get(job["name"]), _job_state(job)) + if pages > 1: + # Each page asked for the latest attempt on its own, so a re-run that started between two pages mixes two + # attempts. run_attempt is "1 for first attempt and higher if the workflow was re-run" (github/rest-api- + # description, workflow-run, fetched 2026-12-01). One page is one answer and needs no second read. + latest = self._call("ci_runs", "GET", path, ok=(200,)) + if latest.status_code != 200: + raise GitUnavailable(f"ci_runs: GET {path}: {latest.status_code} {self.host_text(latest, 200)}") + if latest.json().get("run_attempt") != run.get("run_attempt"): + return {} # nothing is known this poll: each context reads as pending, and the next poll reads again + return checks + + def set_check(self, sha: str, context: str, state: CheckState, description: str, target_url: str | None = None) -> None: + body: dict[str, Any] = {"context": context, "state": state, "description": description[:140]} + if target_url: + body["target_url"] = target_url + r = self._call("status_write", "POST", f"{self._repo()}/statuses/{sha}", json=body, ok=(201,)) + if r.status_code != 201: + raise GitUnavailable(f"status {context} on {sha[:8]}: {r.status_code} {self.host_text(r, 200)}") + + def merge(self, pr: PrRef, expected_head: str) -> str: + """PUT .../merge with sha: GitHub merges only if the head is that sha. 409 is HeadMoved, 405 NotMergeable. The branch is + not deleted here: git_cleanup deletes it with a lease.""" + r = self._call("merge", "PUT", f"{self._repo()}/pulls/{pr.number}/merge", ok=(200,), log_fields={"pinned_sha": expected_head, + "pr_number": pr.number, "merge_method": "merge"}, + json={"sha": expected_head, "merge_method": "merge", "commit_title": f"Merge {pr.branch}"}) + if r.status_code == 200: + return r.json()["sha"] + message = self.host_text(r) + if r.status_code == 409: + raise HeadMoved(f"merge PR {pr.number}: the head is not {expected_head[:8]}: {message}", 409, message) + if r.status_code == 405: + said = r.text[:300].lower() # the decision reads the host's own words; only the message is redacted + raise NotMergeable(f"merge PR {pr.number}: {message}", transient="pending" in said or "expected" in said) + raise PlatformRefused(f"merge PR {pr.number}: {r.status_code} {message}", r.status_code, message) + + def comment(self, pr: PrRef, text: str) -> None: + """At most once per text: a retry after a lost answer finds the comment the host kept, and posts nothing (#451). A read + before the write, not a host idempotency key: two writers at the same moment could still both post.""" + if any(c.get("body") == text for c in self._pages("pr_comments", f"{self._repo()}/issues/{pr.number}/comments", None)): + return + r = self._call("pr_comment", "POST", f"{self._repo()}/issues/{pr.number}/comments", json={"body": text}, ok=(201,)) + if r.status_code != 201: + raise PlatformRefused(f"comment on PR {pr.number}: {r.status_code}", r.status_code, self.host_text(r)) + + def close(self, pr: PrRef, comment: str) -> None: + self.comment(pr, comment) + r = self._call("pr_close", "PATCH", f"{self._repo()}/pulls/{pr.number}", json={"state": "closed"}, ok=(200,)) + if r.status_code != 200: + raise PlatformRefused(f"close PR {pr.number}: {r.status_code}", r.status_code, self.host_text(r)) diff --git a/cmapi/src/cmapi/core/ports.py b/cmapi/src/cmapi/core/ports.py index f32d9e49..9df630b1 100644 --- a/cmapi/src/cmapi/core/ports.py +++ b/cmapi/src/cmapi/core/ports.py @@ -1,231 +1,231 @@ -"""Every extension point and outside dependency of cmapi-core, as typed Protocols. - -Core and plugins depend only on these; adapters implement them and register under -cmapi.adapters. (docs/01, Modularity). An adapter is chosen per instance in instance.yaml, -integrations.yaml, capacity.yaml or plugins.yaml. Each Protocol below says which module owns the -default adapter. The pure-logic modules (tiers, metadata, approvals, lifecycle, expiration, -listquery, render, identity checks) need none of these and are tested without them. -""" -from __future__ import annotations - -from dataclasses import dataclass, field -from datetime import datetime, timedelta -from typing import Any, Literal, Mapping, Protocol, runtime_checkable - -from cmapi.core.identity.claims import Identity -from cmapi.core.identity.directory import DirectoryProvider # noqa: F401 (re-exported) - -# --------------------------------------------------------------------------- shared value types - - -@dataclass(frozen=True) -class Finding: - source: Literal["kyverno", "kubeconform", "cmapi"] - rule: str # the policy's name for Kyverno, the check's name for cmapi, `schema` - path: str - message: str - severity: Literal["error", "warning"] = "error" - # Kyverno's own rule name from its report (#302): `validation` for a ValidatingPolicy, the rule of a hand-written - # ClusterPolicy. None for every other source. - kyverno_rule: str | None = None - - def view(self) -> dict[str, Any]: - """The JSON form of a finding in a plan, a 422 and a stored refusal: camelCase, as the rest of the API.""" - return {"source": self.source, "rule": self.rule, "path": self.path, "message": self.message, - "severity": self.severity, "kyvernoRule": self.kyverno_rule} - - -@dataclass(frozen=True) -class CapacityResult: - status: Literal["fits", "warn", "exceeded", "unknown"] - fresh: bool - binding_resource: str | None = None # cpu or memory, whichever binds - detail: Mapping[str, Any] = field(default_factory=dict) - - -@dataclass(frozen=True) -class PrRef: - number: int - url: str - branch: str - head_sha: str - - -@dataclass(frozen=True) -class PrStatus: - state: Literal["open", "merged", "closed"] - checks: Mapping[str, Literal["pending", "success", "failure"]] - merge_sha: str | None = None - head_sha: str | None = None # the PR's head as the host reports it (#286: merge pins it) - - -@dataclass(frozen=True) -class AppStatus: - cluster_id: str - revision: str - sync: Literal["Synced", "OutOfSync", "Unknown"] - health: str - phase: str | None - revisions: frozenset[str] = frozenset() # status.sync.revisions (multi-source) or {status.sync.revision} - resources: tuple[tuple[str, str, str, str], ...] = () # (kind, namespace, name, status) from status.resources - prune_pending: frozenset[str] = frozenset() # namespaces waiting on Prune=confirm - - -@dataclass(frozen=True) -class PolicyResult: - cluster_id: str - policy: str - rule: str - result: Literal["pass", "fail", "warn", "error", "skip"] - resource: str - namespace: str | None - message: str - - -@dataclass(frozen=True) -class CloudEvent: - id: str - type: str # cmapi.request.synced, cmapi.namespace.expiring, ... - subject: str # / - time: datetime - data: Mapping[str, Any] - - -# --------------------------------------------------------------------------- extension points - - -@runtime_checkable -class Authenticator(Protocol): - """core/auth.py (OIDC against the Keycloak realm, offline JWKS).""" - def authenticate(self, bearer: str) -> Identity: ... - - -@runtime_checkable -class Renderer(Protocol): - """core/render/manifests.py (raw manifests); project_meta.py and Kustomize are alternatives.""" - def render(self, spec: Any, previous: Mapping[str, str] | None = None) -> dict[str, str | None]: ... - def delete(self, cluster_id: str, namespace: str, previous: Mapping[str, str]) -> dict[str, None]: ... - - -@runtime_checkable -class GitProvider(Protocol): - """core/git/ (#286): a Git layer for branches, commits and reads (workspace.py) and a thin platform adapter per host for the - PR (github.py; gitea.py is REST alone). The full contract is core/git/base.py HostGitProvider. Every change is a request - branch and a PR; nothing pushes to the default branch.""" - external_ci: bool - post_statuses: bool - posts_ci: bool - def read_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: ... # files, commit sha - def list_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: ... # {path: blob|commit}, sha - def push_request_branch(self, req: Any) -> Any: ... # BranchRequest -> PushResult - def open_pr(self, branch: str, head: str, title: str, body: str) -> PrRef: ... - def pr_status(self, pr: PrRef, *, ci: bool = True) -> PrStatus: ... - def merge_check(self, head: str, folder: str, prev: Mapping[str, str], files: Mapping[str, str | None], *, - whole_folder: bool = False) -> Any: ... - def merge(self, pr: PrRef, expected_head: str) -> str: ... # merge sha, pinned to expected_head - def comment(self, pr: PrRef, text: str) -> None: ... - def close(self, pr: PrRef, comment: str) -> None: ... - def delete_branch(self, branch: str, expected: str) -> bool: ... - - -@runtime_checkable -class Validator(Protocol): - """core/validate/: the Kyverno CLI bundle plus kubeconform on the rendered files.""" - def validate(self, files: Mapping[str, str], cluster_id: str, environment: str, - previous: Mapping[str, str | None] | None = None, held: list[Finding] | None = None) -> list[Finding]: ... - - -@runtime_checkable -class CapacityBackend(Protocol): - """remote (cmapi-capacity over HTTP, default) or embedded (the worker runs the jobs). - - The holds of open requests live in the cmapi schema, so `reserve_check`, `reserve`, `confirm` and `release` take the - caller's transaction: "Placement, the capacity check inside every plan [...] stay in the API, because they write requests - or reservations" (docs/01). The hold is core/capacity_backend.py's CapacityHold.""" - def check(self, cluster_id: str, environment: str, cpu_delta: float, memory_delta: float, *, session: Any = None, - exclude: str | None = None, exclude_placement: str | None = None, - namespace: str | None = None) -> CapacityResult: ... - def placement(self, placement_id: str) -> Any: ... - def reserve_check(self, session: Any, cluster_id: str, environment: str, hold: Any, *, - placement_id: str | None = None) -> CapacityResult: ... - def reserve(self, session: Any, request_id: str, cluster_id: str, hold: Any, term: timedelta, *, - placement_id: str | None = None) -> None: ... - def confirm(self, session: Any, request_id: str, cluster_id: str, environment: str) -> CapacityResult | None: ... - def release(self, session: Any, request_id: str, why: str) -> int: ... - - -@runtime_checkable -class MetricsSource(Protocol): - """Each cluster's Thanos Querier (default) or an ACM Observability hub. Used by cmapi-capacity only.""" - def query(self, cluster_id: str, promql: str, at: datetime | None = None) -> list[dict[str, Any]]: ... - - -@runtime_checkable -class SyncSignal(Protocol): - """poll (default) or notify (Argo CD Notifications webhook, then confirmed by a read).""" - def status(self, cluster_id: str) -> AppStatus: ... - - -@runtime_checkable -class OperationsEngine(Protocol): - """builtin (worker steps, default), Argo Workflows or Tekton: docs/02's OperationsEngine, synchronous as the rest of cmapi - (core/operations.py). `available` says whether it can take a run, and why not; `submit` starts the run whose operations row - the caller wrote, in the caller's transaction, and returns the run's name on the engine; `cancel` stops it. The built-in - engine keeps its state in that row and its operation_steps, so it needs no `watch`; an Argo or Tekton adapter adds it.""" - name: str - def available(self) -> tuple[bool, str]: ... - def submit(self, session: Any, operation: Any, template: Any) -> str: ... - def cancel(self, session: Any, operation: Any) -> None: ... - - -@runtime_checkable -class EventPublisher(Protocol): - """none (default), signed webhook, Kafka. Fed from the outbox table, so delivery is at least once.""" - def publish(self, event: CloudEvent) -> None: ... - - -@runtime_checkable -class Notifier(Protocol): - """email (default), Slack, Teams. Expiry notices and approval prompts go to the team DL.""" - def send(self, to: list[str], subject: str, body: str, links: Mapping[str, str] | None = None) -> None: ... - - -@runtime_checkable -class ApprovalChannel(Protocol): - """portal (default), email link, argo-events, servicenow, slack/teams. A channel notifies or - relays; the decision is always POST /requests/{id}:approve with an eligible person's identity.""" - name: str - def notify_pending(self, request: Mapping[str, Any], groups: list[str]) -> None: ... - def notify_decision(self, request: Mapping[str, Any], decision: str) -> None: ... - - -# --------------------------------------------------------------------------- readers - - -@runtime_checkable -class KubeReader(Protocol): - """core/clients/kube.py: watch cache per cluster through the read-only cmapi-reader.""" - def namespaces(self, cluster_id: str) -> list[Mapping[str, Any]]: ... - def get(self, cluster_id: str, kind: str, namespace: str | None, name: str) -> Mapping[str, Any] | None: ... - def quota(self, cluster_id: str, namespace: str) -> Mapping[str, Any] | None: ... - - -@runtime_checkable -class PolicyReportReader(Protocol): - """plugins/policies: PolicyReport and ClusterPolicyReport (wgpolicyk8s.io), CEL policy kinds.""" - def results(self, cluster_id: str) -> list[PolicyResult]: ... - def bundle_tag(self, cluster_id: str) -> str | None: ... - - -@runtime_checkable -class AuditLog(Protocol): - """core/audit.py: audit_events rows; never token values.""" - def record(self, actor: Identity, action: str, target: str, detail: Mapping[str, Any]) -> None: ... - - -@runtime_checkable -class Plugin(Protocol): - """Every plugin: name, a router, models, a planner and its read RBAC (docs/01, Adding an offering).""" - name: str - def routes(self) -> Any: ... - def plan(self, request: Mapping[str, Any], caller: Identity) -> Mapping[str, Any]: ... +"""Every extension point and outside dependency of cmapi-core, as typed Protocols. + +Core and plugins depend only on these; adapters implement them and register under +cmapi.adapters. (docs/01, Modularity). An adapter is chosen per instance in instance.yaml, +integrations.yaml, capacity.yaml or plugins.yaml. Each Protocol below says which module owns the +default adapter. The pure-logic modules (tiers, metadata, approvals, lifecycle, expiration, +listquery, render, identity checks) need none of these and are tested without them. +""" +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime, timedelta +from typing import Any, Literal, Mapping, Protocol, runtime_checkable + +from cmapi.core.identity.claims import Identity +from cmapi.core.identity.directory import DirectoryProvider # noqa: F401 (re-exported) + +# --------------------------------------------------------------------------- shared value types + + +@dataclass(frozen=True) +class Finding: + source: Literal["kyverno", "kubeconform", "cmapi"] + rule: str # the policy's name for Kyverno, the check's name for cmapi, `schema` + path: str + message: str + severity: Literal["error", "warning"] = "error" + # Kyverno's own rule name from its report (#302): `validation` for a ValidatingPolicy, the rule of a hand-written + # ClusterPolicy. None for every other source. + kyverno_rule: str | None = None + + def view(self) -> dict[str, Any]: + """The JSON form of a finding in a plan, a 422 and a stored refusal: camelCase, as the rest of the API.""" + return {"source": self.source, "rule": self.rule, "path": self.path, "message": self.message, + "severity": self.severity, "kyvernoRule": self.kyverno_rule} + + +@dataclass(frozen=True) +class CapacityResult: + status: Literal["fits", "warn", "exceeded", "unknown"] + fresh: bool + binding_resource: str | None = None # cpu or memory, whichever binds + detail: Mapping[str, Any] = field(default_factory=dict) + + +@dataclass(frozen=True) +class PrRef: + number: int + url: str + branch: str + head_sha: str + + +@dataclass(frozen=True) +class PrStatus: + state: Literal["open", "merged", "closed"] + checks: Mapping[str, Literal["pending", "success", "failure"]] + merge_sha: str | None = None + head_sha: str | None = None # the PR's head as the host reports it (#286: merge pins it) + + +@dataclass(frozen=True) +class AppStatus: + cluster_id: str + revision: str + sync: Literal["Synced", "OutOfSync", "Unknown"] + health: str + phase: str | None + revisions: frozenset[str] = frozenset() # status.sync.revisions (multi-source) or {status.sync.revision} + resources: tuple[tuple[str, str, str, str], ...] = () # (kind, namespace, name, status) from status.resources + prune_pending: frozenset[str] = frozenset() # namespaces waiting on Prune=confirm + + +@dataclass(frozen=True) +class PolicyResult: + cluster_id: str + policy: str + rule: str + result: Literal["pass", "fail", "warn", "error", "skip"] + resource: str + namespace: str | None + message: str + + +@dataclass(frozen=True) +class CloudEvent: + id: str + type: str # cmapi.request.synced, cmapi.namespace.expiring, ... + subject: str # / + time: datetime + data: Mapping[str, Any] + + +# --------------------------------------------------------------------------- extension points + + +@runtime_checkable +class Authenticator(Protocol): + """core/auth.py (OIDC against the Keycloak realm, offline JWKS).""" + def authenticate(self, bearer: str) -> Identity: ... + + +@runtime_checkable +class Renderer(Protocol): + """core/render/manifests.py (raw manifests); project_meta.py and Kustomize are alternatives.""" + def render(self, spec: Any, previous: Mapping[str, str] | None = None) -> dict[str, str | None]: ... + def delete(self, cluster_id: str, namespace: str, previous: Mapping[str, str]) -> dict[str, None]: ... + + +@runtime_checkable +class GitProvider(Protocol): + """core/git/ (#286): a Git layer for branches, commits and reads (workspace.py) and a thin platform adapter per host for the + PR (github.py; gitea.py is REST alone). The full contract is core/git/base.py HostGitProvider. Every change is a request + branch and a PR; nothing pushes to the default branch.""" + external_ci: bool + post_statuses: bool + posts_ci: bool + def read_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: ... # files, commit sha + def list_folder(self, path: str, ref: str | None = None) -> tuple[dict[str, str], str]: ... # {path: blob|commit}, sha + def push_request_branch(self, req: Any) -> Any: ... # BranchRequest -> PushResult + def open_pr(self, branch: str, head: str, title: str, body: str) -> PrRef: ... + def pr_status(self, pr: PrRef, *, ci: bool = True) -> PrStatus: ... + def merge_check(self, head: str, folder: str, prev: Mapping[str, str], files: Mapping[str, str | None], *, + whole_folder: bool = False) -> Any: ... + def merge(self, pr: PrRef, expected_head: str) -> str: ... # merge sha, pinned to expected_head + def comment(self, pr: PrRef, text: str) -> None: ... + def close(self, pr: PrRef, comment: str) -> None: ... + def delete_branch(self, branch: str, expected: str) -> bool: ... + + +@runtime_checkable +class Validator(Protocol): + """core/validate/: the Kyverno CLI bundle plus kubeconform on the rendered files.""" + def validate(self, files: Mapping[str, str], cluster_id: str, environment: str, + previous: Mapping[str, str | None] | None = None, held: list[Finding] | None = None) -> list[Finding]: ... + + +@runtime_checkable +class CapacityBackend(Protocol): + """remote (cmapi-capacity over HTTP, default) or embedded (the worker runs the jobs). + + The holds of open requests live in the cmapi schema, so `reserve_check`, `reserve`, `confirm` and `release` take the + caller's transaction: "Placement, the capacity check inside every plan [...] stay in the API, because they write requests + or reservations" (docs/01). The hold is core/capacity_backend.py's CapacityHold.""" + def check(self, cluster_id: str, environment: str, cpu_delta: float, memory_delta: float, *, session: Any = None, + exclude: str | None = None, exclude_placement: str | None = None, + namespace: str | None = None) -> CapacityResult: ... + def placement(self, placement_id: str) -> Any: ... + def reserve_check(self, session: Any, cluster_id: str, environment: str, hold: Any, *, + placement_id: str | None = None) -> CapacityResult: ... + def reserve(self, session: Any, request_id: str, cluster_id: str, hold: Any, term: timedelta, *, + placement_id: str | None = None) -> None: ... + def confirm(self, session: Any, request_id: str, cluster_id: str, environment: str) -> CapacityResult | None: ... + def release(self, session: Any, request_id: str, why: str) -> int: ... + + +@runtime_checkable +class MetricsSource(Protocol): + """Each cluster's Thanos Querier (default) or an ACM Observability hub. Used by cmapi-capacity only.""" + def query(self, cluster_id: str, promql: str, at: datetime | None = None) -> list[dict[str, Any]]: ... + + +@runtime_checkable +class SyncSignal(Protocol): + """poll (default) or notify (Argo CD Notifications webhook, then confirmed by a read).""" + def status(self, cluster_id: str) -> AppStatus: ... + + +@runtime_checkable +class OperationsEngine(Protocol): + """builtin (worker steps, default), Argo Workflows or Tekton: docs/02's OperationsEngine, synchronous as the rest of cmapi + (core/operations.py). `available` says whether it can take a run, and why not; `submit` starts the run whose operations row + the caller wrote, in the caller's transaction, and returns the run's name on the engine; `cancel` stops it. The built-in + engine keeps its state in that row and its operation_steps, so it needs no `watch`; an Argo or Tekton adapter adds it.""" + name: str + def available(self) -> tuple[bool, str]: ... + def submit(self, session: Any, operation: Any, template: Any) -> str: ... + def cancel(self, session: Any, operation: Any) -> None: ... + + +@runtime_checkable +class EventPublisher(Protocol): + """none (default), signed webhook, Kafka. Fed from the outbox table, so delivery is at least once.""" + def publish(self, event: CloudEvent) -> None: ... + + +@runtime_checkable +class Notifier(Protocol): + """email (default), Slack, Teams. Expiry notices and approval prompts go to the team DL.""" + def send(self, to: list[str], subject: str, body: str, links: Mapping[str, str] | None = None) -> None: ... + + +@runtime_checkable +class ApprovalChannel(Protocol): + """portal (default), email link, argo-events, servicenow, slack/teams. A channel notifies or + relays; the decision is always POST /requests/{id}:approve with an eligible person's identity.""" + name: str + def notify_pending(self, request: Mapping[str, Any], groups: list[str]) -> None: ... + def notify_decision(self, request: Mapping[str, Any], decision: str) -> None: ... + + +# --------------------------------------------------------------------------- readers + + +@runtime_checkable +class KubeReader(Protocol): + """core/clients/kube.py: watch cache per cluster through the read-only cmapi-reader.""" + def namespaces(self, cluster_id: str) -> list[Mapping[str, Any]]: ... + def get(self, cluster_id: str, kind: str, namespace: str | None, name: str) -> Mapping[str, Any] | None: ... + def quota(self, cluster_id: str, namespace: str) -> Mapping[str, Any] | None: ... + + +@runtime_checkable +class PolicyReportReader(Protocol): + """plugins/policies: PolicyReport and ClusterPolicyReport (wgpolicyk8s.io), CEL policy kinds.""" + def results(self, cluster_id: str) -> list[PolicyResult]: ... + def bundle_tag(self, cluster_id: str) -> str | None: ... + + +@runtime_checkable +class AuditLog(Protocol): + """core/audit.py: audit_events rows; never token values.""" + def record(self, actor: Identity, action: str, target: str, detail: Mapping[str, Any]) -> None: ... + + +@runtime_checkable +class Plugin(Protocol): + """Every plugin: name, a router, models, a planner and its read RBAC (docs/01, Adding an offering).""" + name: str + def routes(self) -> Any: ... + def plan(self, request: Mapping[str, Any], caller: Identity) -> Mapping[str, Any]: ... diff --git a/cmapi/src/cmapi/jobs/apply.py b/cmapi/src/cmapi/jobs/apply.py index 5f367e4e..a7db2714 100644 --- a/cmapi/src/cmapi/jobs/apply.py +++ b/cmapi/src/cmapi/jobs/apply.py @@ -1,170 +1,170 @@ -"""apply: delivery.mode apply, a create or a change whose PR passed its checks (#286; the Atlantis model, Fable's design 1.3). -Apply the PR head's folder, confirm it by a read, and move to applied; the merge job merges after that, so main records only -what succeeded. - - 1. The branch is still at the pinned head, its folder is the plan's files, and the merge check passes. Before any apply a - failure here ends the PR: failed, or superseded for a merge check. Nothing was applied. - 2. apply_started, in its own transaction under the row lock (jobs/delivery.py): from here the cluster may be ahead of main, - so this request can only reach applied or sync_failed, never failed or superseded, and :cancel is refused. - 3. Server-side apply with the deliverer identity, and the removal of the objects the plan drops; a namespace that exists and - is not cmapi-managed is refused before the first write. - 4. confirmed_by_read, the full-plan read (core/sync.py read_plan, #751). Not yet: wait at pollInterval, up to syncTimeout from apply_started. Past it: sync_failed, PR and - branch kept, the lock held; :retry runs this job again. - 5. applied, row.pr.applied_head, and the merge job. - -Also from sync_failed with no merge sha (a :retry of an apply that had not finished). Deletes merge first (the arbitration, -row 4) and never come here. - -A person may merge the PR between the checks and this job, and delete its branch: the branch is then gone or behind main, and -the merge check sees main already holding the plan. Each of those refusals reads the PR first, and a merged PR is adopted -through the merge job's post-merge check, never failed (the arbitration, row 16; #448). -""" -from __future__ import annotations - -from datetime import datetime - -from sqlalchemy.orm import Session - -from cmapi.core.clients.kube import ClusterUnreachable, KubeError -from cmapi.core.context import AppContext -from cmapi.core.db.models import JobRow -from cmapi.core.db.repo import JobRepo, RequestRepo, utcnow -from cmapi.core.errors import Problem -from cmapi.core.git.oplog import Op -from cmapi.core.lifecycle import Event as E, State as S -from cmapi.core.observability import MERGE_CONFLICTS -from cmapi.core.render.manifests import folder -from cmapi.core.sync import ApplyDelivery, ApplyRefused, PruneRefused, confirmed_by_read, scoped_documents -from cmapi.jobs.delivery import (ADOPTION_STALE, APPLY_STARTED, adoption_stored, adoption_writes, apply_started, end_adoption, - end_pr, mark_apply_started, mode_of, planned, pr_of, request_context) - - -def apply(ctx: AppContext, s: Session, job: JobRow) -> None: - repo, jobs = RequestRepo(s), JobRepo(s) - row = repo.get(job.request_id) - serves = row.status == S.PR_OPEN.value or (row.status == S.SYNC_FAILED.value and not row.merge_sha) - if not serves or not row.pr or row.action == "delete" or mode_of(ctx, row.cluster_id) != "apply": - jobs.done(job) - return - with request_context(ctx, row, job): - _apply(ctx, repo, jobs, row, job) - - -def _stop(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow, why: str, started: bool, - event: E = E.PR_FAILED) -> None: - """Before an apply started: the PR ends (failed, or superseded). After: sync_failed, the PR and the branch kept (F1).""" - if started: - if row.status == S.PR_OPEN.value: - repo.move(row, E.SYNC_TIMEOUT, "cmapi-deliverer", f"{why}; the cluster may hold part of {row.pr['head'][:8]}"[:240]) - else: - repo.event(row, "refused", "cmapi-deliverer", why[:300]) - else: - repo.move(row, event, "cmapi-deliverer", why[:240]) - end_pr(ctx, repo, jobs, row, why) - jobs.done(job) - - -def _apply(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow) -> None: - from cmapi.jobs.watch_sync import _deliverer, _live, _managed, _NotYet, _reader_cache, _rules - - head = (job.payload or {}).get("head") or row.pr.get("applied_head") or row.pr["head"] - started = apply_started(repo, row) == head - where = folder(row.cluster_id, row.namespace) - files = planned(row) - previous = row.plan.get("prev") or {} - current = ctx.git.branch_head(row.pr["branch"]) - if current != head: - if _adopt_merged(ctx, repo, jobs, row, job): - return - return _stop(ctx, repo, jobs, row, job, f"the PR head moved from {head[:8]} to {(current or 'nothing')[:8]}", started) - if ctx.git.tree_files(head, where) != files: - return _stop(ctx, repo, jobs, row, job, f"the branch's folder at {head[:8]} is not the approved plan", started) - check = ctx.git.merge_check(head, where, previous, row.plan["files"]) - if not check.ok: - if _adopt_merged(ctx, repo, jobs, row, job): - return - MERGE_CONFLICTS.labels("apply").inc() - why = check.reason(ctx.git.default_branch) - repo.event(row, "merge_check", "worker", why[:300], {"caller": "apply", "main": check.main_sha, "head": head, - "conflict_paths": list(check.conflicts)}) - return _stop(ctx, repo, jobs, row, job, why, started, E.BASE_CHANGED) - try: - client = _deliverer(ctx, row.cluster_id) - d = ApplyDelivery(client) - writes = files - if adoption_stored(row) is not None: - # D16 before cmapi's own write, and each object sent with the uid and resourceVersion the plan read: the API - # server refuses an object that changed between this read and the write (adoption_writes). - found, writes = adoption_writes(ctx, row, files, resuming=started) - if found is not None: - if started: - return _stop(ctx, repo, jobs, row, job, f"{ADOPTION_STALE}: {found.detail}", started) - end_adoption(ctx, repo, jobs, row, found, "cmapi-deliverer") - jobs.done(job) - return - else: - live = d.client.get_object("Namespace", None, row.namespace) - if live is not None and not _managed(live): - return _stop(ctx, repo, jobs, row, job, f"{row.namespace} exists on the cluster and cmapi does not manage it; nothing applied", - started) - # A document outside the request's namespace is refused before apply_started, so the PR ends with nothing applied (#756). - scoped_documents(writes, row.namespace) - if not started: - if not mark_apply_started(ctx, row.request_id, head): - jobs.done(job) # a :cancel won the row first: nothing applied - return - started = True - jobs.fence() - with Op("apply", head_sha=head) as op: - n = d.apply_folder(writes, row.namespace) - pruned = d.prune_objects(row.namespace, files, previous) - cache = _reader_cache(ctx, row.cluster_id) - ok, why = confirmed_by_read(_live(cache.client), row.namespace, files, previous, **_rules(ctx)) - op.set(objects=n, pruned=pruned, confirmed=ok, reason=why) - if not ok: - raise _NotYet(why) - except (ApplyRefused, PruneRefused) as exc: # nothing written, or applied and nothing deleted: waiting cannot fix it - return _stop(ctx, repo, jobs, row, job, str(exc), started) - except KubeError as exc: - if exc.status == 409 and adoption_stored(row) is not None: # a precondition of adoption_writes - return _stop(ctx, repo, jobs, row, job, f"{ADOPTION_STALE}: {str(exc)[:160]}", started) - if exc.status in (400, 403, 409, 422): # the cluster refused the objects: waiting cannot fix it - return _stop(ctx, repo, jobs, row, job, f"the cluster refused the apply: {str(exc)[:160]}", started) - return _wait(ctx, repo, jobs, row, job, f"{type(exc).__name__}: {exc}", started) - except (_NotYet, ClusterUnreachable, Problem) as exc: - return _wait(ctx, repo, jobs, row, job, str(getattr(exc, "detail", None) or exc), started) - repo.move(row, E.APPLIED, "cmapi-deliverer", f"{n} objects from {row.pr['branch']} at {head[:8]}, before the merge, " - f"confirmed by a read: {why}"[:300]) - row.pr = {**row.pr, "applied_head": head} - jobs.done(job) - jobs.enqueue("merge", request_id=row.request_id, cluster_id=row.cluster_id, payload={"head": head}) - - -def _adopt_merged(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow) -> bool: - """A person merged the PR: adopted through the merge job's post-merge check (merged, then watch_sync applies from main), and - True. False while the PR is open or closed unmerged, and the caller's refusal stands.""" - state = ctx.git.pr_status(pr_of(row), ci=False) - if state.state != "merged": - return False - from cmapi.jobs.merge import _merged - - _merged(ctx, repo, jobs, row, job, state.merge_sha or "", adopted=True) - return True - - -def _wait(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow, why: str, started: bool) -> None: - """Not confirmed yet, or the cluster cannot be read: wait at pollInterval, with the reason on the request once. The clock - starts at apply_started (or the job, before it); past syncTimeout the request is sync_failed, never failed. A :retry - restarts it (`since`, routers/requests.py), as for watch_sync: the first apply_started would leave it one read.""" - marks = [e.at for e in repo.events(row.request_id) if e.event == APPLY_STARTED] - since = marks[-1] if marks and started else job.created_at - retried = (job.payload or {}).get("since") - if retried: - since = max(since, datetime.fromisoformat(retried)) - waited = (utcnow() - since).total_seconds() - if waited > ctx.delivery.sync_timeout_seconds: - return _stop(ctx, repo, jobs, row, job, f"not confirmed after {int(waited)} s: {why[:160]}", started) - if job.last_error != why[:2000]: - repo.event(row, "sync_wait", "worker", why[:200]) - jobs.retry(job, why, ctx.delivery.poll_seconds) - job.attempts = 0 # waiting is not a failure +"""apply: delivery.mode apply, a create or a change whose PR passed its checks (#286; the Atlantis model, Fable's design 1.3). +Apply the PR head's folder, confirm it by a read, and move to applied; the merge job merges after that, so main records only +what succeeded. + + 1. The branch is still at the pinned head, its folder is the plan's files, and the merge check passes. Before any apply a + failure here ends the PR: failed, or superseded for a merge check. Nothing was applied. + 2. apply_started, in its own transaction under the row lock (jobs/delivery.py): from here the cluster may be ahead of main, + so this request can only reach applied or sync_failed, never failed or superseded, and :cancel is refused. + 3. Server-side apply with the deliverer identity, and the removal of the objects the plan drops; a namespace that exists and + is not cmapi-managed is refused before the first write. + 4. confirmed_by_read, the full-plan read (core/sync.py read_plan, #751). Not yet: wait at pollInterval, up to syncTimeout from apply_started. Past it: sync_failed, PR and + branch kept, the lock held; :retry runs this job again. + 5. applied, row.pr.applied_head, and the merge job. + +Also from sync_failed with no merge sha (a :retry of an apply that had not finished). Deletes merge first (the arbitration, +row 4) and never come here. + +A person may merge the PR between the checks and this job, and delete its branch: the branch is then gone or behind main, and +the merge check sees main already holding the plan. Each of those refusals reads the PR first, and a merged PR is adopted +through the merge job's post-merge check, never failed (the arbitration, row 16; #448). +""" +from __future__ import annotations + +from datetime import datetime + +from sqlalchemy.orm import Session + +from cmapi.core.clients.kube import ClusterUnreachable, KubeError +from cmapi.core.context import AppContext +from cmapi.core.db.models import JobRow +from cmapi.core.db.repo import JobRepo, RequestRepo, utcnow +from cmapi.core.errors import Problem +from cmapi.core.git.oplog import Op +from cmapi.core.lifecycle import Event as E, State as S +from cmapi.core.observability import MERGE_CONFLICTS +from cmapi.core.render.manifests import folder +from cmapi.core.sync import ApplyDelivery, ApplyRefused, PruneRefused, confirmed_by_read, scoped_documents +from cmapi.jobs.delivery import (ADOPTION_STALE, APPLY_STARTED, adoption_stored, adoption_writes, apply_started, end_adoption, + end_pr, mark_apply_started, mode_of, planned, pr_of, request_context) + + +def apply(ctx: AppContext, s: Session, job: JobRow) -> None: + repo, jobs = RequestRepo(s), JobRepo(s) + row = repo.get(job.request_id) + serves = row.status == S.PR_OPEN.value or (row.status == S.SYNC_FAILED.value and not row.merge_sha) + if not serves or not row.pr or row.action == "delete" or mode_of(ctx, row.cluster_id) != "apply": + jobs.done(job) + return + with request_context(ctx, row, job): + _apply(ctx, repo, jobs, row, job) + + +def _stop(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow, why: str, started: bool, + event: E = E.PR_FAILED) -> None: + """Before an apply started: the PR ends (failed, or superseded). After: sync_failed, the PR and the branch kept (F1).""" + if started: + if row.status == S.PR_OPEN.value: + repo.move(row, E.SYNC_TIMEOUT, "cmapi-deliverer", f"{why}; the cluster may hold part of {row.pr['head'][:8]}"[:240]) + else: + repo.event(row, "refused", "cmapi-deliverer", why[:300]) + else: + repo.move(row, event, "cmapi-deliverer", why[:240]) + end_pr(ctx, repo, jobs, row, why) + jobs.done(job) + + +def _apply(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow) -> None: + from cmapi.jobs.watch_sync import _deliverer, _live, _managed, _NotYet, _reader_cache, _rules + + head = (job.payload or {}).get("head") or row.pr.get("applied_head") or row.pr["head"] + started = apply_started(repo, row) == head + where = folder(row.cluster_id, row.namespace) + files = planned(row) + previous = row.plan.get("prev") or {} + current = ctx.git.branch_head(row.pr["branch"]) + if current != head: + if _adopt_merged(ctx, repo, jobs, row, job): + return + return _stop(ctx, repo, jobs, row, job, f"the PR head moved from {head[:8]} to {(current or 'nothing')[:8]}", started) + if ctx.git.tree_files(head, where) != files: + return _stop(ctx, repo, jobs, row, job, f"the branch's folder at {head[:8]} is not the approved plan", started) + check = ctx.git.merge_check(head, where, previous, row.plan["files"]) + if not check.ok: + if _adopt_merged(ctx, repo, jobs, row, job): + return + MERGE_CONFLICTS.labels("apply").inc() + why = check.reason(ctx.git.default_branch) + repo.event(row, "merge_check", "worker", why[:300], {"caller": "apply", "main": check.main_sha, "head": head, + "conflict_paths": list(check.conflicts)}) + return _stop(ctx, repo, jobs, row, job, why, started, E.BASE_CHANGED) + try: + client = _deliverer(ctx, row.cluster_id) + d = ApplyDelivery(client) + writes = files + if adoption_stored(row) is not None: + # D16 before cmapi's own write, and each object sent with the uid and resourceVersion the plan read: the API + # server refuses an object that changed between this read and the write (adoption_writes). + found, writes = adoption_writes(ctx, row, files, resuming=started) + if found is not None: + if started: + return _stop(ctx, repo, jobs, row, job, f"{ADOPTION_STALE}: {found.detail}", started) + end_adoption(ctx, repo, jobs, row, found, "cmapi-deliverer") + jobs.done(job) + return + else: + live = d.client.get_object("Namespace", None, row.namespace) + if live is not None and not _managed(live): + return _stop(ctx, repo, jobs, row, job, f"{row.namespace} exists on the cluster and cmapi does not manage it; nothing applied", + started) + # A document outside the request's namespace is refused before apply_started, so the PR ends with nothing applied (#756). + scoped_documents(writes, row.namespace) + if not started: + if not mark_apply_started(ctx, row.request_id, head): + jobs.done(job) # a :cancel won the row first: nothing applied + return + started = True + jobs.fence() + with Op("apply", head_sha=head) as op: + n = d.apply_folder(writes, row.namespace) + pruned = d.prune_objects(row.namespace, files, previous) + cache = _reader_cache(ctx, row.cluster_id) + ok, why = confirmed_by_read(_live(cache.client), row.namespace, files, previous, **_rules(ctx)) + op.set(objects=n, pruned=pruned, confirmed=ok, reason=why) + if not ok: + raise _NotYet(why) + except (ApplyRefused, PruneRefused) as exc: # nothing written, or applied and nothing deleted: waiting cannot fix it + return _stop(ctx, repo, jobs, row, job, str(exc), started) + except KubeError as exc: + if exc.status == 409 and adoption_stored(row) is not None: # a precondition of adoption_writes + return _stop(ctx, repo, jobs, row, job, f"{ADOPTION_STALE}: {str(exc)[:160]}", started) + if exc.status in (400, 403, 409, 422): # the cluster refused the objects: waiting cannot fix it + return _stop(ctx, repo, jobs, row, job, f"the cluster refused the apply: {str(exc)[:160]}", started) + return _wait(ctx, repo, jobs, row, job, f"{type(exc).__name__}: {exc}", started) + except (_NotYet, ClusterUnreachable, Problem) as exc: + return _wait(ctx, repo, jobs, row, job, str(getattr(exc, "detail", None) or exc), started) + repo.move(row, E.APPLIED, "cmapi-deliverer", f"{n} objects from {row.pr['branch']} at {head[:8]}, before the merge, " + f"confirmed by a read: {why}"[:300]) + row.pr = {**row.pr, "applied_head": head} + jobs.done(job) + jobs.enqueue("merge", request_id=row.request_id, cluster_id=row.cluster_id, payload={"head": head}) + + +def _adopt_merged(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow) -> bool: + """A person merged the PR: adopted through the merge job's post-merge check (merged, then watch_sync applies from main), and + True. False while the PR is open or closed unmerged, and the caller's refusal stands.""" + state = ctx.git.pr_status(pr_of(row), ci=False) + if state.state != "merged": + return False + from cmapi.jobs.merge import _merged + + _merged(ctx, repo, jobs, row, job, state.merge_sha or "", adopted=True) + return True + + +def _wait(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow, why: str, started: bool) -> None: + """Not confirmed yet, or the cluster cannot be read: wait at pollInterval, with the reason on the request once. The clock + starts at apply_started (or the job, before it); past syncTimeout the request is sync_failed, never failed. A :retry + restarts it (`since`, routers/requests.py), as for watch_sync: the first apply_started would leave it one read.""" + marks = [e.at for e in repo.events(row.request_id) if e.event == APPLY_STARTED] + since = marks[-1] if marks and started else job.created_at + retried = (job.payload or {}).get("since") + if retried: + since = max(since, datetime.fromisoformat(retried)) + waited = (utcnow() - since).total_seconds() + if waited > ctx.delivery.sync_timeout_seconds: + return _stop(ctx, repo, jobs, row, job, f"not confirmed after {int(waited)} s: {why[:160]}", started) + if job.last_error != why[:2000]: + repo.event(row, "sync_wait", "worker", why[:200]) + jobs.retry(job, why, ctx.delivery.poll_seconds) + job.attempts = 0 # waiting is not a failure diff --git a/cmapi/src/cmapi/jobs/merge.py b/cmapi/src/cmapi/jobs/merge.py index b407c35c..7e6abad2 100644 --- a/cmapi/src/cmapi/jobs/merge.py +++ b/cmapi/src/cmapi/jobs/merge.py @@ -1,167 +1,167 @@ -"""merge: the PR's merge through the host API, pinned to a sha (#286; Fable's design 1.2, 1.3, 2.3, 2.4). - - argocd mode, and a delete in apply mode pr_open pinned to the head the checks passed on - apply mode, a create or a change applied, pinned to the applied head (row.pr.applied_head) - merge_failed - -Steps: read the PR first. Merged already (a person, or an earlier attempt that stopped after the host merged): adopted, after -the post-merge check. Closed: before an apply the request is failed; after one, a new PR opens from the same branch, which -the reproducible commit re-creates bit for bit if it is gone, and the request never becomes failed. Then the merge check on a -fresh main, the merge, and the post-merge check: the folder at the merge sha must be the plan's. - -A refusal after an apply is merge_failed (F1): the PR and the branch are kept, the reason goes on the PR as a comment and on -the timeline, and the alert fires. A host or network error is retried with the worker's backoff; after five attempts applied -becomes merge_failed (worker.py). From merge_failed only :retry runs this job again. Never a rollback, never a close.""" -from __future__ import annotations - -from datetime import datetime, timezone - -from sqlalchemy.orm import Session - -from cmapi.core.context import AppContext -from cmapi.core.db.models import JobRow -from cmapi.core.db.repo import JobRepo, RequestRepo -from cmapi.core.git.base import HeadMoved, NotMergeable, NotUtf8, PlatformRefused -from cmapi.core.lifecycle import Event as E, State as S -from cmapi.core.git.workspace import BranchRefused -from cmapi.core.observability import GIT_ORPHANS, LEAD_TIME, MERGE_CONFLICTS -from cmapi.core.ports import PrRef -from cmapi.core.render.manifests import folder -from cmapi.jobs.delivery import body_of, branch_request, end_pr, mode_of, planned, pr_of, request_context, title_of - -AFTER_APPLY = (S.APPLIED.value, S.MERGE_FAILED.value) - - -def merge(ctx: AppContext, s: Session, job: JobRow) -> None: - repo, jobs = RequestRepo(s), JobRepo(s) - row = repo.get(job.request_id) - merge_first = row.status == S.PR_OPEN.value and (mode_of(ctx, row.cluster_id) != "apply" or row.action == "delete") - if not row.pr or not (merge_first or row.status in AFTER_APPLY): - jobs.done(job) - return - with request_context(ctx, row, job): - _merge(ctx, repo, jobs, row, job) - - -def merge_failed(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, why: str, detail: dict | None = None) -> None: - """F1: the cluster holds the change and main does not. The lock, the PR and the branch stay; the reason is on the PR.""" - repo.event(row, "merge_failed", "worker", why[:300], detail or {}) - if row.status == S.APPLIED.value: - repo.move(row, E.MERGE_FAILED, "worker", why[:240]) - jobs.fence() - ctx.git.comment(pr_of(row), f"cmapi: {row.request_id} is applied on the cluster and its merge did not happen: {why}. " - "The PR stays open; :retry merges it.") - - -def _merge(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow) -> None: - after_apply = row.status in AFTER_APPLY - pinned = row.pr.get("applied_head") if after_apply else ((job.payload or {}).get("head") or row.pr["head"]) - pr = pr_of(row) - state = ctx.git.pr_status(pr, ci=False) - if state.state == "merged": - return _merged(ctx, repo, jobs, row, job, state.merge_sha or "", adopted=True) - if state.state == "closed": - if not after_apply: - repo.move(row, E.PR_FAILED, "worker", "the PR was closed") - jobs.done(job) - jobs.enqueue("git_cleanup", request_id=row.request_id, cluster_id=row.cluster_id) - return - try: - pr = _reopen(ctx, repo, jobs, row, pinned) - except BranchRefused as exc: - GIT_ORPHANS.labels("foreign_branch", "refused").inc() - merge_failed(ctx, repo, jobs, row, f"the PR was closed and it cannot open again: {exc}", {"branch": row.pr["branch"]}) - jobs.done(job) - return - check = ctx.git.merge_check(pinned, folder(row.cluster_id, row.namespace), row.plan.get("prev") or {}, row.plan["files"], - whole_folder=row.action == "delete") - if not check.ok: - MERGE_CONFLICTS.labels("merge").inc() - why = check.reason(ctx.git.default_branch) - detail = {"caller": "merge", "main": check.main_sha, "head": pinned, "conflict_paths": list(check.conflicts)} - repo.event(row, "merge_check", "worker", why[:300], detail) - if after_apply: - merge_failed(ctx, repo, jobs, row, why, detail) - else: - repo.move(row, E.BASE_CHANGED, "worker", why[:240]) - end_pr(ctx, repo, jobs, row, why) - jobs.done(job) - return - # The request row, locked until this job commits (Fable's design, 2): a :cancel takes the same lock, so it waits for the - # merge and is then refused, and one that came first is seen here and nothing merges. - before = row.status - repo.s.refresh(row, attribute_names=["status"], with_for_update=True) - if row.status != before: - jobs.done(job) - return - jobs.fence() - try: - sha = ctx.git.merge(pr, pinned) - except (HeadMoved, PlatformRefused) as exc: - why = f"the host refused the merge: {exc}" - if after_apply: - merge_failed(ctx, repo, jobs, row, why, {"http_status": getattr(exc, "status", None)}) - else: - repo.move(row, E.PR_FAILED, "worker", why[:240]) - end_pr(ctx, repo, jobs, row, why) - jobs.done(job) - return - except NotMergeable as exc: - if exc.transient: - raise # the host is still computing: the worker's backoff, then merge_failed - if after_apply: - merge_failed(ctx, repo, jobs, row, f"the host will not merge it: {exc}") - else: - repo.move(row, E.PR_FAILED, "worker", f"the host will not merge it: {exc}"[:240]) - end_pr(ctx, repo, jobs, row, str(exc)) - jobs.done(job) - return - _merged(ctx, repo, jobs, row, job, sha, adopted=False) - - -def _reopen(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, pinned: str) -> PrRef: - """A person closed the PR after the apply: a new PR from the same branch, never failed (Fable 1.3).""" - branch = row.pr["branch"] - jobs.fence() # both the push of a re-created branch and the new PR are external effects - if ctx.git.branch_head(branch) != pinned: - ctx.git.recreate_branch(branch_request(ctx, row), row.pr.get("base") or "", pinned) - new = ctx.git.open_pr(branch, pinned, title_of(row), body_of(row)) - repo.event(row, "pr_reopened", "cmapi-bot", f"#{row.pr['number']} was closed; #{new.number} opened from the same branch", - {"old": row.pr["number"], "new": new.number}) - row.pr = {**row.pr, "number": new.number, "url": new.url, "head": new.head_sha} - return new - - -def _merged(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow, sha: str, adopted: bool) -> None: - """Fable 2.4, a gate on every path that records a merge (this job, a hand merge pr_checks or apply finds): the folder at - the merge sha must be the plan's. Then merged; after an apply also synced, since the read already confirmed it; otherwise - watch_sync. A merge whose folder is not the plan's, or with no sha to read, is merged and then sync_failed, with the lock - held for an operator: nothing is applied from it and a delete never waits for a prune of it (#449).""" - after_apply = row.status in AFTER_APPLY - unreadable: NotUtf8 | None = None - try: - on_main = ctx.git.tree_files(sha, folder(row.cluster_id, row.namespace)) if sha else None - fulfilled = on_main == planned(row) - if fulfilled and row.action == "delete": - # A delete's folder is empty at the merge: no file of any kind, at any depth, is left of it (#616). - fulfilled = not ctx.git.list_folder(folder(row.cluster_id, row.namespace), sha)[0] - except NotUtf8 as exc: - # The merge happened: a folder no plan can hold (#626) is not the plan's. Never retried into failed or merge_failed. - fulfilled, unreadable = False, exc - row.merge_sha = sha or None - how = "adopted: merged on the host" if adopted else "merged" - repo.event(row, "merge_verified", "worker", f"{how} {sha[:8]}; the folder at it {'is' if fulfilled else 'is not'} the plan's", - {"merge_sha": sha, "adopted": adopted}) - repo.move(row, E.MERGED, "cmapi-bot", f"{how} {sha[:8]}") - if not fulfilled: - why = f"the folder at the merge {sha[:8]} is not the approved plan" if sha else "the host gave no merge sha to check" - repo.move(row, E.SYNC_TIMEOUT, "worker", f"{why}: {unreadable}"[:240] if unreadable else why) - elif after_apply: - repo.move(row, E.SYNCED, "cmapi-deliverer", "applied and confirmed by a read before the merge") - approval = "auto" if (row.requirement or {}).get("auto") else "human" - LEAD_TIME.labels(row.plugin, row.action, approval).observe((datetime.now(timezone.utc) - row.created_at).total_seconds()) - else: - jobs.enqueue("watch_sync", request_id=row.request_id, cluster_id=row.cluster_id) - ctx.git.cleanup(row.cluster_id, row.request_id) - jobs.done(job) - jobs.enqueue("git_cleanup", request_id=row.request_id, cluster_id=row.cluster_id) +"""merge: the PR's merge through the host API, pinned to a sha (#286; Fable's design 1.2, 1.3, 2.3, 2.4). + + argocd mode, and a delete in apply mode pr_open pinned to the head the checks passed on + apply mode, a create or a change applied, pinned to the applied head (row.pr.applied_head) + merge_failed + +Steps: read the PR first. Merged already (a person, or an earlier attempt that stopped after the host merged): adopted, after +the post-merge check. Closed: before an apply the request is failed; after one, a new PR opens from the same branch, which +the reproducible commit re-creates bit for bit if it is gone, and the request never becomes failed. Then the merge check on a +fresh main, the merge, and the post-merge check: the folder at the merge sha must be the plan's. + +A refusal after an apply is merge_failed (F1): the PR and the branch are kept, the reason goes on the PR as a comment and on +the timeline, and the alert fires. A host or network error is retried with the worker's backoff; after five attempts applied +becomes merge_failed (worker.py). From merge_failed only :retry runs this job again. Never a rollback, never a close.""" +from __future__ import annotations + +from datetime import datetime, timezone + +from sqlalchemy.orm import Session + +from cmapi.core.context import AppContext +from cmapi.core.db.models import JobRow +from cmapi.core.db.repo import JobRepo, RequestRepo +from cmapi.core.git.base import HeadMoved, NotMergeable, NotUtf8, PlatformRefused +from cmapi.core.lifecycle import Event as E, State as S +from cmapi.core.git.workspace import BranchRefused +from cmapi.core.observability import GIT_ORPHANS, LEAD_TIME, MERGE_CONFLICTS +from cmapi.core.ports import PrRef +from cmapi.core.render.manifests import folder +from cmapi.jobs.delivery import body_of, branch_request, end_pr, mode_of, planned, pr_of, request_context, title_of + +AFTER_APPLY = (S.APPLIED.value, S.MERGE_FAILED.value) + + +def merge(ctx: AppContext, s: Session, job: JobRow) -> None: + repo, jobs = RequestRepo(s), JobRepo(s) + row = repo.get(job.request_id) + merge_first = row.status == S.PR_OPEN.value and (mode_of(ctx, row.cluster_id) != "apply" or row.action == "delete") + if not row.pr or not (merge_first or row.status in AFTER_APPLY): + jobs.done(job) + return + with request_context(ctx, row, job): + _merge(ctx, repo, jobs, row, job) + + +def merge_failed(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, why: str, detail: dict | None = None) -> None: + """F1: the cluster holds the change and main does not. The lock, the PR and the branch stay; the reason is on the PR.""" + repo.event(row, "merge_failed", "worker", why[:300], detail or {}) + if row.status == S.APPLIED.value: + repo.move(row, E.MERGE_FAILED, "worker", why[:240]) + jobs.fence() + ctx.git.comment(pr_of(row), f"cmapi: {row.request_id} is applied on the cluster and its merge did not happen: {why}. " + "The PR stays open; :retry merges it.") + + +def _merge(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow) -> None: + after_apply = row.status in AFTER_APPLY + pinned = row.pr.get("applied_head") if after_apply else ((job.payload or {}).get("head") or row.pr["head"]) + pr = pr_of(row) + state = ctx.git.pr_status(pr, ci=False) + if state.state == "merged": + return _merged(ctx, repo, jobs, row, job, state.merge_sha or "", adopted=True) + if state.state == "closed": + if not after_apply: + repo.move(row, E.PR_FAILED, "worker", "the PR was closed") + jobs.done(job) + jobs.enqueue("git_cleanup", request_id=row.request_id, cluster_id=row.cluster_id) + return + try: + pr = _reopen(ctx, repo, jobs, row, pinned) + except BranchRefused as exc: + GIT_ORPHANS.labels("foreign_branch", "refused").inc() + merge_failed(ctx, repo, jobs, row, f"the PR was closed and it cannot open again: {exc}", {"branch": row.pr["branch"]}) + jobs.done(job) + return + check = ctx.git.merge_check(pinned, folder(row.cluster_id, row.namespace), row.plan.get("prev") or {}, row.plan["files"], + whole_folder=row.action == "delete") + if not check.ok: + MERGE_CONFLICTS.labels("merge").inc() + why = check.reason(ctx.git.default_branch) + detail = {"caller": "merge", "main": check.main_sha, "head": pinned, "conflict_paths": list(check.conflicts)} + repo.event(row, "merge_check", "worker", why[:300], detail) + if after_apply: + merge_failed(ctx, repo, jobs, row, why, detail) + else: + repo.move(row, E.BASE_CHANGED, "worker", why[:240]) + end_pr(ctx, repo, jobs, row, why) + jobs.done(job) + return + # The request row, locked until this job commits (Fable's design, 2): a :cancel takes the same lock, so it waits for the + # merge and is then refused, and one that came first is seen here and nothing merges. + before = row.status + repo.s.refresh(row, attribute_names=["status"], with_for_update=True) + if row.status != before: + jobs.done(job) + return + jobs.fence() + try: + sha = ctx.git.merge(pr, pinned) + except (HeadMoved, PlatformRefused) as exc: + why = f"the host refused the merge: {exc}" + if after_apply: + merge_failed(ctx, repo, jobs, row, why, {"http_status": getattr(exc, "status", None)}) + else: + repo.move(row, E.PR_FAILED, "worker", why[:240]) + end_pr(ctx, repo, jobs, row, why) + jobs.done(job) + return + except NotMergeable as exc: + if exc.transient: + raise # the host is still computing: the worker's backoff, then merge_failed + if after_apply: + merge_failed(ctx, repo, jobs, row, f"the host will not merge it: {exc}") + else: + repo.move(row, E.PR_FAILED, "worker", f"the host will not merge it: {exc}"[:240]) + end_pr(ctx, repo, jobs, row, str(exc)) + jobs.done(job) + return + _merged(ctx, repo, jobs, row, job, sha, adopted=False) + + +def _reopen(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, pinned: str) -> PrRef: + """A person closed the PR after the apply: a new PR from the same branch, never failed (Fable 1.3).""" + branch = row.pr["branch"] + jobs.fence() # both the push of a re-created branch and the new PR are external effects + if ctx.git.branch_head(branch) != pinned: + ctx.git.recreate_branch(branch_request(ctx, row), row.pr.get("base") or "", pinned) + new = ctx.git.open_pr(branch, pinned, title_of(row), body_of(row)) + repo.event(row, "pr_reopened", "cmapi-bot", f"#{row.pr['number']} was closed; #{new.number} opened from the same branch", + {"old": row.pr["number"], "new": new.number}) + row.pr = {**row.pr, "number": new.number, "url": new.url, "head": new.head_sha} + return new + + +def _merged(ctx: AppContext, repo: RequestRepo, jobs: JobRepo, row, job: JobRow, sha: str, adopted: bool) -> None: + """Fable 2.4, a gate on every path that records a merge (this job, a hand merge pr_checks or apply finds): the folder at + the merge sha must be the plan's. Then merged; after an apply also synced, since the read already confirmed it; otherwise + watch_sync. A merge whose folder is not the plan's, or with no sha to read, is merged and then sync_failed, with the lock + held for an operator: nothing is applied from it and a delete never waits for a prune of it (#449).""" + after_apply = row.status in AFTER_APPLY + unreadable: NotUtf8 | None = None + try: + on_main = ctx.git.tree_files(sha, folder(row.cluster_id, row.namespace)) if sha else None + fulfilled = on_main == planned(row) + if fulfilled and row.action == "delete": + # A delete's folder is empty at the merge: no file of any kind, at any depth, is left of it (#616). + fulfilled = not ctx.git.list_folder(folder(row.cluster_id, row.namespace), sha)[0] + except NotUtf8 as exc: + # The merge happened: a folder no plan can hold (#626) is not the plan's. Never retried into failed or merge_failed. + fulfilled, unreadable = False, exc + row.merge_sha = sha or None + how = "adopted: merged on the host" if adopted else "merged" + repo.event(row, "merge_verified", "worker", f"{how} {sha[:8]}; the folder at it {'is' if fulfilled else 'is not'} the plan's", + {"merge_sha": sha, "adopted": adopted}) + repo.move(row, E.MERGED, "cmapi-bot", f"{how} {sha[:8]}") + if not fulfilled: + why = f"the folder at the merge {sha[:8]} is not the approved plan" if sha else "the host gave no merge sha to check" + repo.move(row, E.SYNC_TIMEOUT, "worker", f"{why}: {unreadable}"[:240] if unreadable else why) + elif after_apply: + repo.move(row, E.SYNCED, "cmapi-deliverer", "applied and confirmed by a read before the merge") + approval = "auto" if (row.requirement or {}).get("auto") else "human" + LEAD_TIME.labels(row.plugin, row.action, approval).observe((datetime.now(timezone.utc) - row.created_at).total_seconds()) + else: + jobs.enqueue("watch_sync", request_id=row.request_id, cluster_id=row.cluster_id) + ctx.git.cleanup(row.cluster_id, row.request_id) + jobs.done(job) + jobs.enqueue("git_cleanup", request_id=row.request_id, cluster_id=row.cluster_id) diff --git a/cmapi/tests/service/conftest.py b/cmapi/tests/service/conftest.py index ad068cd3..40e7558f 100644 --- a/cmapi/tests/service/conftest.py +++ b/cmapi/tests/service/conftest.py @@ -1,549 +1,549 @@ -"""Fixtures for the service tests: a real PostgreSQL (CMAPI_TEST_DATABASE_URL, default the throwaway -postgres:16-alpine container on port 55432 named in CRC-BUILD-STATUS.md "Resume"; CI runs the same image -as a service), and fakes for the Git host, the cluster and the validator, so the pipeline, the routers -and the worker jobs run end to end without a cluster. - -The fakes implement the same contracts as the adapters (HostGitProvider, KubeClient) and keep -their state in memory; the tests below drive every lifecycle path through them. -""" -from __future__ import annotations - -import os -import re -import sys -import threading -import time -from contextlib import contextmanager -from datetime import datetime, timedelta, timezone -from pathlib import Path -from typing import Any, Iterator, Mapping - -import jwt -import pytest -from cryptography.hazmat.primitives import serialization -from cryptography.hazmat.primitives.asymmetric import rsa -from fastapi.testclient import TestClient -from sqlalchemy import text - -ROOT = Path(__file__).resolve().parents[2] -EXAMPLES = ROOT.parent / "examples" -sys.path.insert(0, str(ROOT / "src")) - -from cmapi.core.auth import Authenticator, Jwks # noqa: E402 -from cmapi.core.clients.kube import KubeClient, KubeError # noqa: E402 -from cmapi.core.context import build_context # noqa: E402 -from cmapi.core.db import Database # noqa: E402 -from cmapi.core.db.migrate import run as migrate # noqa: E402 -from cmapi.core.git.base import HostGitProvider # noqa: E402 -from cmapi.core.ports import Finding, PrRef, PrStatus # noqa: E402 -from cmapi.core.registry import ImportSource # noqa: E402 -from cmapi.main import create_app # noqa: E402 -from cmapi.core.ratelimit import DEFAULTS as RATE_LIMIT_CLASSES, Limit, RateLimiter # noqa: E402 -from cmapi.settings import Settings # noqa: E402 - -DB_URL = os.environ.get("CMAPI_TEST_DATABASE_URL", "postgresql://cmapi:cmapi@127.0.0.1:55432/cmapi") -ISSUER = "https://keycloak.test/realms/cmapi" -AUDIENCE = "cmapi-nonprod" - -# One session per database (#271). fresh_db truncates the request tables before each test, so a second session on the same -# database deletes this one's rows mid-test, and a test fails with a 404 that is not the code's. A session-level advisory -# lock, held on its own connection until the session ends, turns that into an immediate refusal that names the cause. -SESSION_LOCK_KEY = 0x636D617069 # "cmapi" in ASCII -SESSION_LOCK_EXIT = 75 # EX_TEMPFAIL of sysexits.h, "try again later": pytest's own codes are 0 to 5, and 3 is its internal error -_SESSION_LOCK = pytest.StashKey[Any]() -_SESSION_LOCK_TRIED = pytest.StashKey[bool]() - - -def _hold_the_database(session: pytest.Session) -> None: - import psycopg - - if session.config.stash.get(_SESSION_LOCK_TRIED, False): - return - session.config.stash[_SESSION_LOCK_TRIED] = True - # SQLAlchemy's form (postgresql+psycopg://) works for the app's engine; libpq wants the plain scheme. - conninfo = re.sub(r"^postgres(?:ql)?\+\w+://", "postgresql://", DB_URL) - try: - conn = psycopg.connect(conninfo, autocommit=True, connect_timeout=5) - except psycopg.Error: - # No database, or a URL libpq cannot read (its message quotes the URL, password and all, so it is not shown): the - # tests that need the database fail on their own, as they did before the lock. - return - if not conn.execute("select pg_try_advisory_lock(%s)", (SESSION_LOCK_KEY,)).fetchone()[0]: - where = f"{conn.info.host}:{conn.info.port}/{conn.info.dbname}" # from the connection: never the URL's credentials - conn.close() - pytest.exit(f"another service-test session holds the database {where} (advisory lock {SESSION_LOCK_KEY}): its fixtures " - "truncate the request tables, so two sessions would delete each other's rows. Wait for it to end, or set " - "CMAPI_TEST_DATABASE_URL to a database of your own.", returncode=SESSION_LOCK_EXIT) - session.config.stash[_SESSION_LOCK] = conn - - -def pytest_sessionstart(session: pytest.Session) -> None: - _hold_the_database(session) # before collection, when this file is an initial conftest (pytest tests/service, ...) - - -def pytest_collection_finish(session: pytest.Session) -> None: - # pytest calls pytest_sessionstart only for initial conftests. `pytest tests` from cmapi/ loads this file while collecting, - # after the session started, so the lock is taken here instead: still before any fixture or test runs. - _hold_the_database(session) - - -def pytest_sessionfinish(session: pytest.Session) -> None: - conn = session.config.stash.get(_SESSION_LOCK, None) - if conn is not None: - conn.close() # the advisory lock is the connection's: closing it releases the lock - - -# --------------------------------------------------------------------------- tokens - -class Keys: - def __init__(self): - self.private = rsa.generate_private_key(public_exponent=65537, key_size=2048) - self.kid = "test-kid-1" - pub = self.private.public_key() - self.jwk = {**jwt.algorithms.RSAAlgorithm.to_jwk(pub, as_dict=True), "kid": self.kid, "use": "sig", "alg": "RS256"} - self.pem = self.private.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, - serialization.NoEncryption()) - - def token(self, username: str, *, roles=(), groups=(), employee_id="1001", sub=None, aud=AUDIENCE, iss=ISSUER, - exp_in=300, client="cmapi-portal", extra: Mapping[str, Any] | None = None, kid=None, alg="RS256", - typ: str | None = "at+jwt") -> str: - """`typ` is the JOSE header: an access token of cmapi's realm has at+jwt (RFC 9068). None removes the header type.""" - now = int(time.time()) - claims = {"iss": iss, "aud": [aud, "account"], "sub": sub or f"sub-{username}", "azp": client, "iat": now, - "exp": now + exp_in, "preferred_username": username, "email": f"{username}@ephico2real.com", - "given_name": username.title(), "family_name": "Doe", "groups": list(groups), - "resource_access": {aud: {"roles": list(roles)}}} - if employee_id: - claims["employee_id"] = employee_id - claims.update(extra or {}) - headers = {"kid": kid or self.kid, "typ": typ} # PyJWT deletes a header typ that is None, and writes JWT when the key is absent - if alg == "none": - return jwt.encode(claims, key=None, algorithm="none", headers=headers) - return jwt.encode(claims, self.pem, algorithm=alg, headers=headers) - - -@pytest.fixture(scope="session") -def keys() -> Keys: - return Keys() - - -# --------------------------------------------------------------------------- fakes - -class FakeGit(HostGitProvider): - """An in-memory Git host: branches are dicts of files; a PR is a record with statuses.""" - - def __init__(self): - self.branches: dict[str, dict[str, str]] = {"main": {"README.md": "cluster-configs (test)\n"}} - self.heads: dict[str, str] = {"main": "a" * 40} - self.main_history: list[str] = ["a" * 40] - self.prs: dict[int, dict[str, Any]] = {} - self.statuses: dict[str, dict[str, str]] = {} - self.commits: list[str] = ["aaaaaaaa initial"] - self.based_on: dict[str, dict[str, str]] = {} - self.repository = "cmapi/cluster-configs-test" - self.default_branch = "main" - self.web_url = "https://git.test" - self.down = False - self.owners: dict[str, tuple[str, str]] = {} - self.based_on_sha: dict[str, str] = {} - self.pushes: list[str] = [] - self.submodules: set[str] = set() # paths whose entry is a submodule (a gitlink), for list_folder - - def _check(self): - if self.down: - from cmapi.core.git.base import GitUnavailable - raise GitUnavailable("fake git is down") - - def _sha(self, branch: str) -> str: - import hashlib - h = hashlib.sha1(("".join(sorted(f"{k}={v}" for k, v in self.branches[branch].items()))).encode()).hexdigest() - self.heads[branch] = h - if branch == "main": - self.main_history.append(h) - return h - - def branch_head(self, branch): - self._check() - return self.heads.get(branch) if branch in self.branches else None - - def _branch_of(self, ref): - self._check() - ref = ref or "main" - # Only a branch that still exists: a merged branch is deleted and its head stays in self.heads, and a later head with - # the same content has the same hash here (#154). - branch = ref if ref in self.branches else next((b for b, h in self.heads.items() if h == ref and b in self.branches), None) - if branch is None: - from cmapi.core.git.base import GitUnavailable - raise GitUnavailable(f"no branch {ref}") - return branch - - def read_folder(self, path, ref=None): - branch = self._branch_of(ref) - # The .yaml files directly in the folder, as github.py, gitea.py and workspace.py list one folder, not its subfolders (#578). - prefix = path.rstrip("/") + "/" - files = {p: t for p, t in self.branches[branch].items() - if p.startswith(prefix) and "/" not in p[len(prefix):] and p.endswith(".yaml")} - return files, self.heads[branch] - - def list_folder(self, path, ref=None): - """Every path under the folder, at any depth, as the real listings give it (#616). A path in submodules is one.""" - branch = self._branch_of(ref) - prefix = path.rstrip("/") + "/" - return ({p: ("commit" if p in self.submodules else "blob") for p in self.branches[branch] if p.startswith(prefix)}, - self.heads[branch]) - - def contains(self, revision, sha): - self._check() - history = self.main_history - return revision == sha or (revision in history and sha in history and history.index(sha) <= history.index(revision)) - - def changed_paths(self, head): - self._check() - branch = next(b for b, h in self.heads.items() if h == head and b in self.branches) # as in read_folder (#154) - before, after = self.based_on.get(branch, self.branches[branch]), self.branches[branch] - return {p for p in set(before) | set(after) if before.get(p) != after.get(p)} - - 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 None - - def push_request_branch(self, req): - """The Git layer's contract (#286), in memory: the branch from main with the plan's files. A branch that exists is - adopted when it is this request's with these files, replaced when it is this request's stale attempt, refused otherwise.""" - from cmapi.core.git.base import PushResult - from cmapi.core.git.workspace import BranchRefused, request_branch - - self._check() - branch = request_branch(req.cluster_id, req.request_id) - base = self.heads["main"] - want = dict(self.branches["main"]) - for p, t in req.files.items(): - if t is None: - want.pop(p, None) - else: - want[p] = t - if branch in self.branches: - owner = self.owners.get(branch) - if owner == (req.request_id, req.plan_hash) and self.branches[branch] == want: - return PushResult(self.heads[branch], self.based_on_sha.get(branch, base), "adopted") - if not owner or owner[0] != req.request_id: - raise BranchRefused(f"branch {branch} exists and its head is not cmapi's commit for {req.request_id}") - self.branches[branch] = want - self.based_on[branch] = dict(self.branches["main"]) - self.based_on_sha[branch] = base - self.owners[branch] = (req.request_id, req.plan_hash) - self.pushes.append(branch) - return PushResult(self._sha(branch), base, "created") - - def open_pr(self, branch, head, title, body): - self._check() - if (pr := self.find_pr(branch)) is not None: - return pr - assert branch in self.branches and self.heads[branch] == head, "PR opened on a head that is not the pushed one" - 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) - - def comment(self, pr, text): - self.prs[pr.number].setdefault("comments", []).append(text) - - def delete_branch(self, branch, expected): - if branch not in self.branches: - return True - if self.heads.get(branch) != expected: - return False - del self.branches[branch] - 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() - if p["state"] == "open" and p["branch"].startswith(prefix)] - - def list_branches(self, prefix): - return {b: self.heads[b] for b in self.branches if b.startswith(prefix)} - - def branch_time(self, sha): - return 0 - - def request_of(self, sha): - branch = next((b for b, h in self.heads.items() if h == sha and b in self.branches), None) - return (self.owners.get(branch) or (None,))[0] - - def pr_status(self, pr, *, ci=True): - self._check() - p = self.prs[pr.number] - head = self.heads[pr.branch] if pr.branch in self.heads else pr.head_sha - checks = {k: ("success" if v == "success" else "pending" if v == "pending" else "failure") - for k, v in self.statuses.get(head, {}).items()} - return PrStatus(state=p["state"], checks=checks, merge_sha=p["merge_sha"], head_sha=head) - - def set_check(self, sha, context, state, description, target_url=None): - self._check() - self.statuses.setdefault(sha, {})[context] = state - - def merge(self, pr, expected_head): - self._check() - p = self.prs[pr.number] - assert self.heads[pr.branch] == expected_head, "head moved" - required = self.statuses.get(expected_head, {}) - assert all(required.get(c) == "success" for c in ("ci/kubeconform", "ci/kyverno", "cmapi/check")), "protection refused the merge" - base = self.based_on.get(pr.branch) - if base is None: - self.branches["main"] = dict(self.branches[pr.branch]) - else: - # A merge, as a host makes it: main keeps what it gained since the branch left it, and takes the branch's own - # changes. Copying the branch over main would drop a path added to main before the merge (#616). - merged, branch = dict(self.branches["main"]), self.branches[pr.branch] - for path in set(base) | set(branch): - if base.get(path) != branch.get(path): - if path in branch: - merged[path] = branch[path] - else: - merged.pop(path, None) - self.branches["main"] = merged - merge_sha = self._sha("main") - p["state"], p["merge_sha"] = "merged", merge_sha - self.commits.append(f"{merge_sha[:8]} Merge {pr.branch}") - del self.branches[pr.branch] - return merge_sha - - def close(self, pr, comment): - self.prs[pr.number]["state"] = "closed" - self.prs[pr.number]["comment"] = comment - - def log(self, n=20): - return list(reversed(self.commits))[:n] - - # test helper: a hand edit on the bot branch after approval - def tamper(self, branch: str, path: str, text: str) -> None: - self.branches[branch][path] = text - self._sha(branch) - - -class FakeKube(KubeClient): - """One cluster in memory: namespaces, quotas and limit ranges, applied by the deliverer. - - #302: `served_groups` is what API discovery serves (empty: Kyverno is not installed, as on CRC), `forbidden_kinds` the - kinds whose list answers 403, and `calls` each discovery and list call by kind, so a test can show that no call was made. - A list with `limit` pages by `continue`, as the API server does. - - The watch is silent by default: the suite's tests relist the cache (`_list`) where they need it current. A test that holds a - cache list across a change, and needs the change seen without a relist, sets `live_watch`: then each apply and delete is a - watch event (ADDED, MODIFIED, DELETED) after the resourceVersion the watch gives, as the API server serves one (#751).""" - - def __init__(self, cluster_id="CRC", identity="system:serviceaccount:cmapi-system:cmapi-reader"): - self.cluster_id, self.identity = cluster_id, identity - self.objects: dict[tuple[str, str, str], dict[str, Any]] = {} - self.rv = 1 - self.applied: list[str] = [] - self.unreachable = False - self.served_groups: set[str] = set() - self.forbidden_kinds: set[str] = set() - self.calls: list[str] = [] - self.live_watch = False - self._events: list[tuple[int, str, dict[str, Any]]] = [] # (resourceVersion, kind, event), only with live_watch - self._changed = threading.Condition() - - def close(self): - pass - - def _k(self, kind, ns, name): - return (kind, ns or "", name) - - def version(self): - if self.unreachable: - from cmapi.core.clients.kube import ClusterUnreachable - raise ClusterUnreachable("fake cluster down") - return "v1.35.6-fake" - - def whoami(self): - return self.identity - - def served(self, group_version): - self.calls.append(f"discovery {group_version}") - if self.unreachable: - from cmapi.core.clients.kube import ClusterUnreachable - raise ClusterUnreachable("fake cluster down") - return group_version in self.served_groups - - def list(self, kind, namespace=None, label_selector=None, resource_version=None, *, limit=None, continue_=None): - self.calls.append(kind) - if kind in self.forbidden_kinds: - raise KubeError(403, f"list {kind}", "forbidden") - items = [o for (k, ns, _), o in self.objects.items() if k == kind and (namespace is None or ns == namespace)] - if limit is None: - return {"items": items, "metadata": {"resourceVersion": str(self.rv)}} - items.sort(key=lambda o: (o["metadata"].get("namespace", ""), o["metadata"]["name"])) - start = int(continue_ or 0) - more = start + limit < len(items) - return {"items": items[start:start + limit], - "metadata": {"resourceVersion": str(self.rv), **({"continue": str(start + limit)} if more else {})}} - - def get_object(self, kind, namespace, name): - if kind in ("ServiceAccount", "RoleBinding"): - # The reader's grant: list, not get (deploy/manifests/environments/crc/reader/00-cmapi-reader.yaml, #748). - raise KubeError(403, f"get {kind}", "forbidden: the reader may list ServiceAccounts and RoleBindings, not get them") - return self.objects.get(self._k(kind, namespace, name)) - - def watch(self, kind, resource_version, timeout_seconds=300): - if not self.live_watch: - time.sleep(0.05) - return iter(()) - since = int(resource_version or 0) - - def due(): - return [ev for rv, k, ev in self._events if k == kind and rv > since] - - with self._changed: - self._changed.wait_for(due, timeout=0.05) - return iter(due()) - - def _emit(self, kind: str, kind_of_change: str, obj: dict[str, Any]) -> None: - """One watch event at the current resourceVersion, carried in the object's metadata as the API server sets it.""" - if not self.live_watch: - return - event = {"type": kind_of_change, "object": {**obj, "metadata": {**obj["metadata"], "resourceVersion": str(self.rv)}}} - with self._changed: - self._events.append((self.rv, kind, event)) - self._changed.notify_all() - - def apply(self, doc, field_manager="cmapi-deliverer"): - kind, meta = doc["kind"], doc["metadata"] - key = self._k(kind, meta.get("namespace"), meta["name"]) - obj = dict(doc) - if kind == "ResourceQuota": - obj = {**doc, "status": {"hard": dict(doc["spec"]["hard"]), "used": {k: "0" for k in doc["spec"]["hard"]}}} - if kind == "Namespace": - obj = {**doc, "status": {"phase": "Active"}} - obj["metadata"] = {**doc["metadata"], "creationTimestamp": datetime.now(timezone.utc).isoformat()} - existed = key in self.objects - self.objects[key] = obj - self.rv += 1 - self._emit(kind, "MODIFIED" if existed else "ADDED", obj) - self.applied.append(f"{kind}/{meta.get('namespace', '')}/{meta['name']}") - return obj - - def delete(self, kind, namespace, name): - obj = self.objects.pop(self._k(kind, namespace, name), None) - gone = [] if obj is None else [(kind, obj)] - if kind == "Namespace": - for key in [k for k in self.objects if k[1] == name]: - gone.append((key[0], self.objects.pop(key))) - self.rv += 1 - for k, o in gone: - self._emit(k, "DELETED", o) - - def add_unmanaged_namespace(self, name: str): - self.objects[self._k("Namespace", None, name)] = {"kind": "Namespace", "metadata": {"name": name, "labels": {}}} - - -class FakeValidator: - def __init__(self): - self.findings: list[Finding] = [] - self.calls = 0 - self.previous: list = [] # the previous folder that each call gave (#212: a held value is not refused) - self.held: list[Finding] = [] # the failures that a previous version holds, given to a caller that asks (#248) - - def validate(self, files, cluster_id, environment, previous=None, held=None): - self.calls += 1 - self.previous.append(previous) - if held is not None: - held.extend(self.held) - return list(self.findings) - - -class OneSecret(ImportSource): - def __init__(self, cluster_id="CRC"): - self.cluster_id = cluster_id - - def list(self): - return [{"name": "cmapi-cluster-crc", "labels": {"cmapi.net/secret-type": "cluster", "cmapi.net/cluster-id": self.cluster_id}, - "annotations": {}, "data": {"apiUrl": "https://fake.cluster:6443", "token": "fake-token-1234567890"}}] - - -# --------------------------------------------------------------------------- the app - -@pytest.fixture(scope="session") -def test_config(tmp_path_factory) -> Path: - d = tmp_path_factory.mktemp("config") - for name in ("instance.yaml", "approval-rules.yaml", "authz-roles.yaml", "tiers.yaml", "expiration.yaml"): - (d / name).write_text((EXAMPLES / "instances" / "nonprod" / name).read_text()) - (d / "metadata-keys.yaml").write_text((EXAMPLES / "cluster-configs" / "policies" / "metadata-keys.yaml").read_text()) - (d / "instance.yaml").write_text((d / "instance.yaml").read_text() - .replace("https://sso.ephico2real.com/realms/ephico2real", ISSUER) - .replace("repository: caas/cluster-configs-nonprod", "repository: cmapi/cluster-configs-test")) - (d / "clusters.yaml").write_text("clusters:\n CRC:\n environment: dev\n gitopsPath: clusters/CRC\n" - " labels: {region: us-central}\n simulatedCapacity: {cpu: 64, memory: 256Gi}\n") - (d / "capacity.yaml").write_text("overcommit:\n dev: {cpu: 2.0, memory: 1.25}\n rnd: {cpu: 2.0, memory: 1.25}\n" - "targets:\n dev: {commitment: {warn: 0.85, critical: 0.95}}\n rnd: {commitment: {warn: 0.85, critical: 0.95}}\n") - (d / "integrations.yaml").write_text("delivery:\n mode: apply\n syncTimeout: 30s\nsyncSignal:\n default: poll\n pollInterval: 1s\n") - return d - - -@pytest.fixture(scope="session") -def database() -> Database: - os.environ["CMAPI_DATABASE_URL"] = DB_URL - from cmapi.settings import settings - settings.cache_clear() - migrate(["head"]) - return Database(DB_URL) - - -@pytest.fixture -def fresh_db(database: Database) -> Database: - with database.engine.begin() as c: - # The usage tables of #310, and the operations tables of #26, are truncated where the migrations made them: a run of - # an older src (the before-run of a fix) migrates to its own head, without them. - usage = [t for t in ("analysis_sweeps", "namespace_verdicts", "capacity_snapshots", "capacity_reservations", - "operation_steps", "operations") - if c.execute(text("SELECT to_regclass(:t)"), {"t": t}).scalar() is not None] - c.execute(text("TRUNCATE change_requests, request_events, approvals, jobs, audit_events, admin_switches, " - "approval_notifications, expiration_notices, policy_rejections" - + "".join(f", {t}" for t in usage) + " RESTART IDENTITY CASCADE")) - return database - - -# The rate limits of the suite's worlds (#689): high enough that no test meets them. One test sends hundreds of calls a second -# as one person, which no client does; the instance's own limits are tested in test_rate_limits_689.py, which passes -# instance_rate_limits=True. -UNLIMITED = {kind: Limit(1e9, 10**9) for kind in RATE_LIMIT_CLASSES} - - -@contextmanager -def build_world(config_dir: Path, keys: Keys, monkeypatch, *, instance_rate_limits: bool = False): - """The app on one configuration folder, with fakes wired in: yields (client, ctx, git, kube, validator, keys).""" - git, kube, validator = FakeGit(), FakeKube(), FakeValidator() - monkeypatch.setenv("CMAPI_DATABASE_URL", DB_URL) - s = Settings(config_dir=config_dir, database_url=DB_URL, git_provider="gitea", git_url="https://git.test/api/v1", - git_token="t", cursor_key="k", link_key="l", metrics_port=0, imports_dir=None, - kube_token_file=Path("/nonexistent"), kube_ca_file=Path("/nonexistent")) - import cmapi.core.context as context_mod - monkeypatch.setattr(context_mod, "make_provider", lambda *a, **k: git) - monkeypatch.setattr(context_mod, "CliValidator", lambda *a, **k: validator) - ctx = build_context(s, start_registry=False, import_source=OneSecret()) - ctx.registry.client_factory = lambda *a, **k: kube - ctx.registry.start_caches = True - ctx.registry.refresh() - assert ctx.registry.clusters["CRC"].status == "connected", ctx.registry.clusters["CRC"].findings - ctx.registry.cache("CRC").wait_ready(5) - ctx.registry.clusters["CRC"].nodes.wait_ready(5) # #302: the node watch's first list, so no test races it - ctx.deliverer_factory = lambda cid: kube - ctx.auth = Authenticator(ISSUER, AUDIENCE, Jwks(ISSUER, "https://keycloak.test/certs", fetch=lambda url: [keys.jwk])) - if not instance_rate_limits: - ctx.limiter = RateLimiter(limits=dict(UNLIMITED)) - app = create_app(s, ctx) - try: - with TestClient(app) as client: - yield client, ctx, git, kube, validator, keys - finally: - ctx.registry.stop() - - -@pytest.fixture -def world(test_config: Path, fresh_db: Database, keys: Keys, monkeypatch): - """The app with fakes wired in: returns (client, ctx, git, kube, validator, keys).""" - with build_world(test_config, keys, monkeypatch) as w: - yield w +"""Fixtures for the service tests: a real PostgreSQL (CMAPI_TEST_DATABASE_URL, default the throwaway +postgres:16-alpine container on port 55432 named in CRC-BUILD-STATUS.md "Resume"; CI runs the same image +as a service), and fakes for the Git host, the cluster and the validator, so the pipeline, the routers +and the worker jobs run end to end without a cluster. + +The fakes implement the same contracts as the adapters (HostGitProvider, KubeClient) and keep +their state in memory; the tests below drive every lifecycle path through them. +""" +from __future__ import annotations + +import os +import re +import sys +import threading +import time +from contextlib import contextmanager +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Any, Iterator, Mapping + +import jwt +import pytest +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa +from fastapi.testclient import TestClient +from sqlalchemy import text + +ROOT = Path(__file__).resolve().parents[2] +EXAMPLES = ROOT.parent / "examples" +sys.path.insert(0, str(ROOT / "src")) + +from cmapi.core.auth import Authenticator, Jwks # noqa: E402 +from cmapi.core.clients.kube import KubeClient, KubeError # noqa: E402 +from cmapi.core.context import build_context # noqa: E402 +from cmapi.core.db import Database # noqa: E402 +from cmapi.core.db.migrate import run as migrate # noqa: E402 +from cmapi.core.git.base import HostGitProvider # noqa: E402 +from cmapi.core.ports import Finding, PrRef, PrStatus # noqa: E402 +from cmapi.core.registry import ImportSource # noqa: E402 +from cmapi.main import create_app # noqa: E402 +from cmapi.core.ratelimit import DEFAULTS as RATE_LIMIT_CLASSES, Limit, RateLimiter # noqa: E402 +from cmapi.settings import Settings # noqa: E402 + +DB_URL = os.environ.get("CMAPI_TEST_DATABASE_URL", "postgresql://cmapi:cmapi@127.0.0.1:55432/cmapi") +ISSUER = "https://keycloak.test/realms/cmapi" +AUDIENCE = "cmapi-nonprod" + +# One session per database (#271). fresh_db truncates the request tables before each test, so a second session on the same +# database deletes this one's rows mid-test, and a test fails with a 404 that is not the code's. A session-level advisory +# lock, held on its own connection until the session ends, turns that into an immediate refusal that names the cause. +SESSION_LOCK_KEY = 0x636D617069 # "cmapi" in ASCII +SESSION_LOCK_EXIT = 75 # EX_TEMPFAIL of sysexits.h, "try again later": pytest's own codes are 0 to 5, and 3 is its internal error +_SESSION_LOCK = pytest.StashKey[Any]() +_SESSION_LOCK_TRIED = pytest.StashKey[bool]() + + +def _hold_the_database(session: pytest.Session) -> None: + import psycopg + + if session.config.stash.get(_SESSION_LOCK_TRIED, False): + return + session.config.stash[_SESSION_LOCK_TRIED] = True + # SQLAlchemy's form (postgresql+psycopg://) works for the app's engine; libpq wants the plain scheme. + conninfo = re.sub(r"^postgres(?:ql)?\+\w+://", "postgresql://", DB_URL) + try: + conn = psycopg.connect(conninfo, autocommit=True, connect_timeout=5) + except psycopg.Error: + # No database, or a URL libpq cannot read (its message quotes the URL, password and all, so it is not shown): the + # tests that need the database fail on their own, as they did before the lock. + return + if not conn.execute("select pg_try_advisory_lock(%s)", (SESSION_LOCK_KEY,)).fetchone()[0]: + where = f"{conn.info.host}:{conn.info.port}/{conn.info.dbname}" # from the connection: never the URL's credentials + conn.close() + pytest.exit(f"another service-test session holds the database {where} (advisory lock {SESSION_LOCK_KEY}): its fixtures " + "truncate the request tables, so two sessions would delete each other's rows. Wait for it to end, or set " + "CMAPI_TEST_DATABASE_URL to a database of your own.", returncode=SESSION_LOCK_EXIT) + session.config.stash[_SESSION_LOCK] = conn + + +def pytest_sessionstart(session: pytest.Session) -> None: + _hold_the_database(session) # before collection, when this file is an initial conftest (pytest tests/service, ...) + + +def pytest_collection_finish(session: pytest.Session) -> None: + # pytest calls pytest_sessionstart only for initial conftests. `pytest tests` from cmapi/ loads this file while collecting, + # after the session started, so the lock is taken here instead: still before any fixture or test runs. + _hold_the_database(session) + + +def pytest_sessionfinish(session: pytest.Session) -> None: + conn = session.config.stash.get(_SESSION_LOCK, None) + if conn is not None: + conn.close() # the advisory lock is the connection's: closing it releases the lock + + +# --------------------------------------------------------------------------- tokens + +class Keys: + def __init__(self): + self.private = rsa.generate_private_key(public_exponent=65537, key_size=2048) + self.kid = "test-kid-1" + pub = self.private.public_key() + self.jwk = {**jwt.algorithms.RSAAlgorithm.to_jwk(pub, as_dict=True), "kid": self.kid, "use": "sig", "alg": "RS256"} + self.pem = self.private.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, + serialization.NoEncryption()) + + def token(self, username: str, *, roles=(), groups=(), employee_id="1001", sub=None, aud=AUDIENCE, iss=ISSUER, + exp_in=300, client="cmapi-portal", extra: Mapping[str, Any] | None = None, kid=None, alg="RS256", + typ: str | None = "at+jwt") -> str: + """`typ` is the JOSE header: an access token of cmapi's realm has at+jwt (RFC 9068). None removes the header type.""" + now = int(time.time()) + claims = {"iss": iss, "aud": [aud, "account"], "sub": sub or f"sub-{username}", "azp": client, "iat": now, + "exp": now + exp_in, "preferred_username": username, "email": f"{username}@ephico2real.com", + "given_name": username.title(), "family_name": "Doe", "groups": list(groups), + "resource_access": {aud: {"roles": list(roles)}}} + if employee_id: + claims["employee_id"] = employee_id + claims.update(extra or {}) + headers = {"kid": kid or self.kid, "typ": typ} # PyJWT deletes a header typ that is None, and writes JWT when the key is absent + if alg == "none": + return jwt.encode(claims, key=None, algorithm="none", headers=headers) + return jwt.encode(claims, self.pem, algorithm=alg, headers=headers) + + +@pytest.fixture(scope="session") +def keys() -> Keys: + return Keys() + + +# --------------------------------------------------------------------------- fakes + +class FakeGit(HostGitProvider): + """An in-memory Git host: branches are dicts of files; a PR is a record with statuses.""" + + def __init__(self): + self.branches: dict[str, dict[str, str]] = {"main": {"README.md": "cluster-configs (test)\n"}} + self.heads: dict[str, str] = {"main": "a" * 40} + self.main_history: list[str] = ["a" * 40] + self.prs: dict[int, dict[str, Any]] = {} + self.statuses: dict[str, dict[str, str]] = {} + self.commits: list[str] = ["aaaaaaaa initial"] + self.based_on: dict[str, dict[str, str]] = {} + self.repository = "cmapi/cluster-configs-test" + self.default_branch = "main" + self.web_url = "https://git.test" + self.down = False + self.owners: dict[str, tuple[str, str]] = {} + self.based_on_sha: dict[str, str] = {} + self.pushes: list[str] = [] + self.submodules: set[str] = set() # paths whose entry is a submodule (a gitlink), for list_folder + + def _check(self): + if self.down: + from cmapi.core.git.base import GitUnavailable + raise GitUnavailable("fake git is down") + + def _sha(self, branch: str) -> str: + import hashlib + h = hashlib.sha1(("".join(sorted(f"{k}={v}" for k, v in self.branches[branch].items()))).encode()).hexdigest() + self.heads[branch] = h + if branch == "main": + self.main_history.append(h) + return h + + def branch_head(self, branch): + self._check() + return self.heads.get(branch) if branch in self.branches else None + + def _branch_of(self, ref): + self._check() + ref = ref or "main" + # Only a branch that still exists: a merged branch is deleted and its head stays in self.heads, and a later head with + # the same content has the same hash here (#154). + branch = ref if ref in self.branches else next((b for b, h in self.heads.items() if h == ref and b in self.branches), None) + if branch is None: + from cmapi.core.git.base import GitUnavailable + raise GitUnavailable(f"no branch {ref}") + return branch + + def read_folder(self, path, ref=None): + branch = self._branch_of(ref) + # The .yaml files directly in the folder, as github.py, gitea.py and workspace.py list one folder, not its subfolders (#578). + prefix = path.rstrip("/") + "/" + files = {p: t for p, t in self.branches[branch].items() + if p.startswith(prefix) and "/" not in p[len(prefix):] and p.endswith(".yaml")} + return files, self.heads[branch] + + def list_folder(self, path, ref=None): + """Every path under the folder, at any depth, as the real listings give it (#616). A path in submodules is one.""" + branch = self._branch_of(ref) + prefix = path.rstrip("/") + "/" + return ({p: ("commit" if p in self.submodules else "blob") for p in self.branches[branch] if p.startswith(prefix)}, + self.heads[branch]) + + def contains(self, revision, sha): + self._check() + history = self.main_history + return revision == sha or (revision in history and sha in history and history.index(sha) <= history.index(revision)) + + def changed_paths(self, head): + self._check() + branch = next(b for b, h in self.heads.items() if h == head and b in self.branches) # as in read_folder (#154) + before, after = self.based_on.get(branch, self.branches[branch]), self.branches[branch] + return {p for p in set(before) | set(after) if before.get(p) != after.get(p)} + + 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 None + + def push_request_branch(self, req): + """The Git layer's contract (#286), in memory: the branch from main with the plan's files. A branch that exists is + adopted when it is this request's with these files, replaced when it is this request's stale attempt, refused otherwise.""" + from cmapi.core.git.base import PushResult + from cmapi.core.git.workspace import BranchRefused, request_branch + + self._check() + branch = request_branch(req.cluster_id, req.request_id) + base = self.heads["main"] + want = dict(self.branches["main"]) + for p, t in req.files.items(): + if t is None: + want.pop(p, None) + else: + want[p] = t + if branch in self.branches: + owner = self.owners.get(branch) + if owner == (req.request_id, req.plan_hash) and self.branches[branch] == want: + return PushResult(self.heads[branch], self.based_on_sha.get(branch, base), "adopted") + if not owner or owner[0] != req.request_id: + raise BranchRefused(f"branch {branch} exists and its head is not cmapi's commit for {req.request_id}") + self.branches[branch] = want + self.based_on[branch] = dict(self.branches["main"]) + self.based_on_sha[branch] = base + self.owners[branch] = (req.request_id, req.plan_hash) + self.pushes.append(branch) + return PushResult(self._sha(branch), base, "created") + + def open_pr(self, branch, head, title, body): + self._check() + if (pr := self.find_pr(branch)) is not None: + return pr + assert branch in self.branches and self.heads[branch] == head, "PR opened on a head that is not the pushed one" + 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) + + def comment(self, pr, text): + self.prs[pr.number].setdefault("comments", []).append(text) + + def delete_branch(self, branch, expected): + if branch not in self.branches: + return True + if self.heads.get(branch) != expected: + return False + del self.branches[branch] + 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() + if p["state"] == "open" and p["branch"].startswith(prefix)] + + def list_branches(self, prefix): + return {b: self.heads[b] for b in self.branches if b.startswith(prefix)} + + def branch_time(self, sha): + return 0 + + def request_of(self, sha): + branch = next((b for b, h in self.heads.items() if h == sha and b in self.branches), None) + return (self.owners.get(branch) or (None,))[0] + + def pr_status(self, pr, *, ci=True): + self._check() + p = self.prs[pr.number] + head = self.heads[pr.branch] if pr.branch in self.heads else pr.head_sha + checks = {k: ("success" if v == "success" else "pending" if v == "pending" else "failure") + for k, v in self.statuses.get(head, {}).items()} + return PrStatus(state=p["state"], checks=checks, merge_sha=p["merge_sha"], head_sha=head) + + def set_check(self, sha, context, state, description, target_url=None): + self._check() + self.statuses.setdefault(sha, {})[context] = state + + def merge(self, pr, expected_head): + self._check() + p = self.prs[pr.number] + assert self.heads[pr.branch] == expected_head, "head moved" + required = self.statuses.get(expected_head, {}) + assert all(required.get(c) == "success" for c in ("ci/kubeconform", "ci/kyverno", "cmapi/check")), "protection refused the merge" + base = self.based_on.get(pr.branch) + if base is None: + self.branches["main"] = dict(self.branches[pr.branch]) + else: + # A merge, as a host makes it: main keeps what it gained since the branch left it, and takes the branch's own + # changes. Copying the branch over main would drop a path added to main before the merge (#616). + merged, branch = dict(self.branches["main"]), self.branches[pr.branch] + for path in set(base) | set(branch): + if base.get(path) != branch.get(path): + if path in branch: + merged[path] = branch[path] + else: + merged.pop(path, None) + self.branches["main"] = merged + merge_sha = self._sha("main") + p["state"], p["merge_sha"] = "merged", merge_sha + self.commits.append(f"{merge_sha[:8]} Merge {pr.branch}") + del self.branches[pr.branch] + return merge_sha + + def close(self, pr, comment): + self.prs[pr.number]["state"] = "closed" + self.prs[pr.number]["comment"] = comment + + def log(self, n=20): + return list(reversed(self.commits))[:n] + + # test helper: a hand edit on the bot branch after approval + def tamper(self, branch: str, path: str, text: str) -> None: + self.branches[branch][path] = text + self._sha(branch) + + +class FakeKube(KubeClient): + """One cluster in memory: namespaces, quotas and limit ranges, applied by the deliverer. + + #302: `served_groups` is what API discovery serves (empty: Kyverno is not installed, as on CRC), `forbidden_kinds` the + kinds whose list answers 403, and `calls` each discovery and list call by kind, so a test can show that no call was made. + A list with `limit` pages by `continue`, as the API server does. + + The watch is silent by default: the suite's tests relist the cache (`_list`) where they need it current. A test that holds a + cache list across a change, and needs the change seen without a relist, sets `live_watch`: then each apply and delete is a + watch event (ADDED, MODIFIED, DELETED) after the resourceVersion the watch gives, as the API server serves one (#751).""" + + def __init__(self, cluster_id="CRC", identity="system:serviceaccount:cmapi-system:cmapi-reader"): + self.cluster_id, self.identity = cluster_id, identity + self.objects: dict[tuple[str, str, str], dict[str, Any]] = {} + self.rv = 1 + self.applied: list[str] = [] + self.unreachable = False + self.served_groups: set[str] = set() + self.forbidden_kinds: set[str] = set() + self.calls: list[str] = [] + self.live_watch = False + self._events: list[tuple[int, str, dict[str, Any]]] = [] # (resourceVersion, kind, event), only with live_watch + self._changed = threading.Condition() + + def close(self): + pass + + def _k(self, kind, ns, name): + return (kind, ns or "", name) + + def version(self): + if self.unreachable: + from cmapi.core.clients.kube import ClusterUnreachable + raise ClusterUnreachable("fake cluster down") + return "v1.35.6-fake" + + def whoami(self): + return self.identity + + def served(self, group_version): + self.calls.append(f"discovery {group_version}") + if self.unreachable: + from cmapi.core.clients.kube import ClusterUnreachable + raise ClusterUnreachable("fake cluster down") + return group_version in self.served_groups + + def list(self, kind, namespace=None, label_selector=None, resource_version=None, *, limit=None, continue_=None): + self.calls.append(kind) + if kind in self.forbidden_kinds: + raise KubeError(403, f"list {kind}", "forbidden") + items = [o for (k, ns, _), o in self.objects.items() if k == kind and (namespace is None or ns == namespace)] + if limit is None: + return {"items": items, "metadata": {"resourceVersion": str(self.rv)}} + items.sort(key=lambda o: (o["metadata"].get("namespace", ""), o["metadata"]["name"])) + start = int(continue_ or 0) + more = start + limit < len(items) + return {"items": items[start:start + limit], + "metadata": {"resourceVersion": str(self.rv), **({"continue": str(start + limit)} if more else {})}} + + def get_object(self, kind, namespace, name): + if kind in ("ServiceAccount", "RoleBinding"): + # The reader's grant: list, not get (deploy/manifests/environments/crc/reader/00-cmapi-reader.yaml, #748). + raise KubeError(403, f"get {kind}", "forbidden: the reader may list ServiceAccounts and RoleBindings, not get them") + return self.objects.get(self._k(kind, namespace, name)) + + def watch(self, kind, resource_version, timeout_seconds=300): + if not self.live_watch: + time.sleep(0.05) + return iter(()) + since = int(resource_version or 0) + + def due(): + return [ev for rv, k, ev in self._events if k == kind and rv > since] + + with self._changed: + self._changed.wait_for(due, timeout=0.05) + return iter(due()) + + def _emit(self, kind: str, kind_of_change: str, obj: dict[str, Any]) -> None: + """One watch event at the current resourceVersion, carried in the object's metadata as the API server sets it.""" + if not self.live_watch: + return + event = {"type": kind_of_change, "object": {**obj, "metadata": {**obj["metadata"], "resourceVersion": str(self.rv)}}} + with self._changed: + self._events.append((self.rv, kind, event)) + self._changed.notify_all() + + def apply(self, doc, field_manager="cmapi-deliverer"): + kind, meta = doc["kind"], doc["metadata"] + key = self._k(kind, meta.get("namespace"), meta["name"]) + obj = dict(doc) + if kind == "ResourceQuota": + obj = {**doc, "status": {"hard": dict(doc["spec"]["hard"]), "used": {k: "0" for k in doc["spec"]["hard"]}}} + if kind == "Namespace": + obj = {**doc, "status": {"phase": "Active"}} + obj["metadata"] = {**doc["metadata"], "creationTimestamp": datetime.now(timezone.utc).isoformat()} + existed = key in self.objects + self.objects[key] = obj + self.rv += 1 + self._emit(kind, "MODIFIED" if existed else "ADDED", obj) + self.applied.append(f"{kind}/{meta.get('namespace', '')}/{meta['name']}") + return obj + + def delete(self, kind, namespace, name): + obj = self.objects.pop(self._k(kind, namespace, name), None) + gone = [] if obj is None else [(kind, obj)] + if kind == "Namespace": + for key in [k for k in self.objects if k[1] == name]: + gone.append((key[0], self.objects.pop(key))) + self.rv += 1 + for k, o in gone: + self._emit(k, "DELETED", o) + + def add_unmanaged_namespace(self, name: str): + self.objects[self._k("Namespace", None, name)] = {"kind": "Namespace", "metadata": {"name": name, "labels": {}}} + + +class FakeValidator: + def __init__(self): + self.findings: list[Finding] = [] + self.calls = 0 + self.previous: list = [] # the previous folder that each call gave (#212: a held value is not refused) + self.held: list[Finding] = [] # the failures that a previous version holds, given to a caller that asks (#248) + + def validate(self, files, cluster_id, environment, previous=None, held=None): + self.calls += 1 + self.previous.append(previous) + if held is not None: + held.extend(self.held) + return list(self.findings) + + +class OneSecret(ImportSource): + def __init__(self, cluster_id="CRC"): + self.cluster_id = cluster_id + + def list(self): + return [{"name": "cmapi-cluster-crc", "labels": {"cmapi.net/secret-type": "cluster", "cmapi.net/cluster-id": self.cluster_id}, + "annotations": {}, "data": {"apiUrl": "https://fake.cluster:6443", "token": "fake-token-1234567890"}}] + + +# --------------------------------------------------------------------------- the app + +@pytest.fixture(scope="session") +def test_config(tmp_path_factory) -> Path: + d = tmp_path_factory.mktemp("config") + for name in ("instance.yaml", "approval-rules.yaml", "authz-roles.yaml", "tiers.yaml", "expiration.yaml"): + (d / name).write_text((EXAMPLES / "instances" / "nonprod" / name).read_text()) + (d / "metadata-keys.yaml").write_text((EXAMPLES / "cluster-configs" / "policies" / "metadata-keys.yaml").read_text()) + (d / "instance.yaml").write_text((d / "instance.yaml").read_text() + .replace("https://sso.ephico2real.com/realms/ephico2real", ISSUER) + .replace("repository: caas/cluster-configs-nonprod", "repository: cmapi/cluster-configs-test")) + (d / "clusters.yaml").write_text("clusters:\n CRC:\n environment: dev\n gitopsPath: clusters/CRC\n" + " labels: {region: us-central}\n simulatedCapacity: {cpu: 64, memory: 256Gi}\n") + (d / "capacity.yaml").write_text("overcommit:\n dev: {cpu: 2.0, memory: 1.25}\n rnd: {cpu: 2.0, memory: 1.25}\n" + "targets:\n dev: {commitment: {warn: 0.85, critical: 0.95}}\n rnd: {commitment: {warn: 0.85, critical: 0.95}}\n") + (d / "integrations.yaml").write_text("delivery:\n mode: apply\n syncTimeout: 30s\nsyncSignal:\n default: poll\n pollInterval: 1s\n") + return d + + +@pytest.fixture(scope="session") +def database() -> Database: + os.environ["CMAPI_DATABASE_URL"] = DB_URL + from cmapi.settings import settings + settings.cache_clear() + migrate(["head"]) + return Database(DB_URL) + + +@pytest.fixture +def fresh_db(database: Database) -> Database: + with database.engine.begin() as c: + # The usage tables of #310, and the operations tables of #26, are truncated where the migrations made them: a run of + # an older src (the before-run of a fix) migrates to its own head, without them. + usage = [t for t in ("analysis_sweeps", "namespace_verdicts", "capacity_snapshots", "capacity_reservations", + "operation_steps", "operations") + if c.execute(text("SELECT to_regclass(:t)"), {"t": t}).scalar() is not None] + c.execute(text("TRUNCATE change_requests, request_events, approvals, jobs, audit_events, admin_switches, " + "approval_notifications, expiration_notices, policy_rejections" + + "".join(f", {t}" for t in usage) + " RESTART IDENTITY CASCADE")) + return database + + +# The rate limits of the suite's worlds (#689): high enough that no test meets them. One test sends hundreds of calls a second +# as one person, which no client does; the instance's own limits are tested in test_rate_limits_689.py, which passes +# instance_rate_limits=True. +UNLIMITED = {kind: Limit(1e9, 10**9) for kind in RATE_LIMIT_CLASSES} + + +@contextmanager +def build_world(config_dir: Path, keys: Keys, monkeypatch, *, instance_rate_limits: bool = False): + """The app on one configuration folder, with fakes wired in: yields (client, ctx, git, kube, validator, keys).""" + git, kube, validator = FakeGit(), FakeKube(), FakeValidator() + monkeypatch.setenv("CMAPI_DATABASE_URL", DB_URL) + s = Settings(config_dir=config_dir, database_url=DB_URL, git_provider="gitea", git_url="https://git.test/api/v1", + git_token="t", cursor_key="k", link_key="l", metrics_port=0, imports_dir=None, + kube_token_file=Path("/nonexistent"), kube_ca_file=Path("/nonexistent")) + import cmapi.core.context as context_mod + monkeypatch.setattr(context_mod, "make_provider", lambda *a, **k: git) + monkeypatch.setattr(context_mod, "CliValidator", lambda *a, **k: validator) + ctx = build_context(s, start_registry=False, import_source=OneSecret()) + ctx.registry.client_factory = lambda *a, **k: kube + ctx.registry.start_caches = True + ctx.registry.refresh() + assert ctx.registry.clusters["CRC"].status == "connected", ctx.registry.clusters["CRC"].findings + ctx.registry.cache("CRC").wait_ready(5) + ctx.registry.clusters["CRC"].nodes.wait_ready(5) # #302: the node watch's first list, so no test races it + ctx.deliverer_factory = lambda cid: kube + ctx.auth = Authenticator(ISSUER, AUDIENCE, Jwks(ISSUER, "https://keycloak.test/certs", fetch=lambda url: [keys.jwk])) + if not instance_rate_limits: + ctx.limiter = RateLimiter(limits=dict(UNLIMITED)) + app = create_app(s, ctx) + try: + with TestClient(app) as client: + yield client, ctx, git, kube, validator, keys + finally: + ctx.registry.stop() + + +@pytest.fixture +def world(test_config: Path, fresh_db: Database, keys: Keys, monkeypatch): + """The app with fakes wired in: returns (client, ctx, git, kube, validator, keys).""" + with build_world(test_config, keys, monkeypatch) as w: + yield w diff --git a/cmapi/tests/service/test_github_actions_ci.py b/cmapi/tests/service/test_github_actions_ci.py index 40c43a62..ed774ad4 100644 --- a/cmapi/tests/service/test_github_actions_ci.py +++ b/cmapi/tests/service/test_github_actions_ci.py @@ -1,340 +1,340 @@ -"""GitHub's PR adapter reads host CI from the config repository's Actions: the workflow jobs of the PR head, by name, through -the Actions API (#60). Not the commit statuses, which the bot's own token can post, and not the Checks API, which a -fine-grained token cannot call (BUG-69, #279). Host CI is on by default. The provider runs on a MockTransport shaped by GitHub's -REST docs, "Workflow runs" and "Workflow jobs" (fetched 2026-12-01), and by the answers measured on cmapi-cluster-configs that -day (run 45649310281: jobs ci/kubeconform and ci/kyverno, each the check run of the same name and id, app github-actions).""" -from __future__ import annotations - -import httpx -import pytest - -from cmapi.core.git.base import GitUnavailable, IncompleteList -from cmapi.core.git.github import GitHubProvider -from cmapi.core.ports import PrRef -from cmapi.jobs.pr_checks import CONTEXT_KUBECONFORM, CONTEXT_KYVERNO - -SHA = "c" * 40 -API = "https://github.test" -PR = PrRef(7, "https://github.test/o/r/pull/7", "cmapi/CRC/r1", SHA) -RUNS = "/repos/o/r/actions/runs" -RUN_LOOKUP = "/repos/o/r/actions/workflows/ci.yml/runs" - - -def run_of(run_id=1, **fields): - """One pull_request run of this PR as GitHub lists it. pull_requests is empty, as measured on cmapi-cluster-configs.""" - return {"id": run_id, "run_attempt": 1, "head_sha": SHA, "event": "pull_request", "head_branch": PR.branch, - "head_repository": {"full_name": "o/r"}, "pull_requests": [], **fields} - - -def job(name, conclusion="success", status="completed"): - return {"name": name, "status": status, "conclusion": conclusion, "head_sha": SHA} - - -def paged(request, key, items): - per_page, page = min(int(request.url.params.get("per_page", 30)), 100), int(request.url.params.get("page", 1)) - chunk = items[(page - 1) * per_page:page * per_page] - headers = {} - if page * per_page < len(items): - headers["Link"] = f'<{API}{request.url.path}?per_page={per_page}&page={page + 1}>; rel="next"' - return httpx.Response(200, json={"total_count": len(items), key: chunk}, headers=headers) - - -def provider(runs=None, *, seen=None, pr=None, on_runs=None, on_jobs=None, **kw): - """runs: {run id: [jobs]} on SHA.""" - runs = {1: [job(CONTEXT_KUBECONFORM), job(CONTEXT_KYVERNO)]} if runs is None else runs - - def handle(request): - if seen is not None: - seen.append(request) - path = request.url.path - assert "check-runs" not in path and "check-suites" not in path, "the Checks API is never called" - assert "/status" not in path, "a commit status is never read as CI: the bot's token can post one (#60)" - if path == "/repos/o/r/pulls/7": - return httpx.Response(200, json=pr or {"state": "open", "merged": False, "head": {"sha": SHA, "ref": PR.branch}}) - if path in (RUN_LOOKUP, RUNS): - if on_runs: - return on_runs(request) - assert request.url.params["head_sha"] == SHA - return paged(request, "workflow_runs", [run_of(i) for i in runs]) - if path.startswith(RUNS + "/") and path.endswith("/jobs"): - if on_jobs: - return on_jobs(request) - assert request.url.params["filter"] == "latest", "a re-run's newest attempt alone" - return paged(request, "jobs", runs[int(path.split("/")[-2])]) - if path.startswith(RUNS + "/") and path.split("/")[-1].isdigit(): - return httpx.Response(200, json={"run_attempt": 1}) - return httpx.Response(404, json={"message": f"not routed: {path}"}) - git = GitHubProvider(API, "o/r", "token", **kw) - git._client = httpx.Client(base_url=API, transport=httpx.MockTransport(handle)) - return git - - -def checks(**kw): - return dict(provider(**kw).pr_status(PR).checks) - - -def test_state_only_read_skips_the_actions_api(): - seen = [] - - status = provider(seen=seen).pr_status(PR, ci=False) - - assert status.state == "open" and status.checks == {} - assert [r.url.path for r in seen] == ["/repos/o/r/pulls/7"] - - -def test_host_ci_is_on_by_default_and_the_worker_posts_cmapi_check_alone(): - git = GitHubProvider(API, "o/r", "token") - assert (git.external_ci, git.post_statuses, git.posts_ci) == (True, True, False) - - -def test_host_ci_off_reads_nothing_and_posts_nothing(): - seen = [] - git = provider(seen=seen, host_checks=False) - assert git.pr_status(PR).checks == {} and not git.external_ci and not git.post_statuses and not git.posts_ci - assert [r.url.path for r in seen] == ["/repos/o/r/pulls/7"] - - -def test_post_status_without_host_ci_still_posts_no_ci_context(): - git = GitHubProvider(API, "o/r", "token", host_checks=False, post_status=True) - assert git.post_statuses and not git.posts_ci and not git.external_ci - - -def test_the_two_jobs_of_the_workflow_read_as_the_two_ci_contexts(): - assert checks() == {CONTEXT_KUBECONFORM: "success", CONTEXT_KYVERNO: "success"} - - -@pytest.mark.parametrize("status,conclusion,expected", [ - ("completed", "success", "success"), - ("completed", "failure", "failure"), - ("completed", "cancelled", "failure"), - ("completed", "timed_out", "failure"), - ("completed", "action_required", "failure"), - ("completed", "skipped", "failure"), # validated nothing: not a pass here, though branch protection passes it - ("completed", "neutral", "failure"), - ("completed", None, "pending"), # completed before its conclusion is there (#87, e6300b8c) - ("queued", None, "pending"), - ("in_progress", None, "pending"), - ("waiting", None, "pending"), - ("requested", None, "pending"), - ("pending", None, "pending"), - ("in_progress", "success", "pending"), # unfinished, whatever the conclusion field says -]) -def test_each_job_state_reads_as_a_check_state(status, conclusion, expected): - assert checks(runs={1: [job(CONTEXT_KYVERNO, conclusion, status)]}) == {CONTEXT_KYVERNO: expected} - - -@pytest.mark.parametrize("other", ["success", "failure"]) -def test_one_name_in_two_runs_of_the_ci_workflow_reads_as_the_worse(other): - got = checks(runs={1: [job(CONTEXT_KYVERNO, "failure")], 2: [job(CONTEXT_KYVERNO, other)]}) - assert got == {CONTEXT_KYVERNO: "failure"} - - -def test_a_name_that_no_job_carries_is_not_invented(): - assert checks(runs={1: [job(CONTEXT_KUBECONFORM)]}) == {CONTEXT_KUBECONFORM: "success"} - assert checks(runs={}) == {} - - -def test_a_run_of_another_commit_says_nothing_about_this_one(): - def runs(request): - return paged(request, "workflow_runs", [run_of(head_sha="d" * 40)]) - - def jobs(request): - raise AssertionError("the jobs of another commit's run are not read") - assert checks(on_runs=runs, on_jobs=jobs) == {} - - -def test_it_asks_for_the_runs_of_the_pr_head_and_the_latest_attempt_of_each_job(): - seen = [] - provider(seen=seen).pr_status(PR) - runs = [r for r in seen if r.url.path == RUN_LOOKUP] - jobs = [r for r in seen if r.url.path.endswith("/jobs")] - assert [r.url.params["head_sha"] for r in runs] == [SHA] - assert [(r.url.path, r.url.params["filter"]) for r in jobs] == [(f"{RUNS}/1/jobs", "latest")] - - -def test_a_failure_on_a_later_page_of_jobs_counts(): - got = checks(runs={1: [job(f"other-{i}") for i in range(150)] + [job(CONTEXT_KYVERNO, "failure")]}) - assert len(got) == 151 and got[CONTEXT_KYVERNO] == "failure" - - -def test_a_run_on_a_later_page_of_runs_is_read(): - runs = {i: [] for i in range(1, 151)} - runs[150] = [job(CONTEXT_KYVERNO, "failure")] - assert checks(runs=runs) == {CONTEXT_KYVERNO: "failure"} - - -def test_as_many_runs_as_github_can_list_for_one_commit_is_not_read_as_complete(): - """"This endpoint will return up to 1,000 results for each search when using ... head_sha" (REST docs, 2026-12-01).""" - with pytest.raises(IncompleteList, match="1000"): - provider(runs={i: [] for i in range(1, 1001)}).pr_status(PR) - - -def test_the_next_link_is_a_signal_and_is_never_followed_to_another_host(): - """The Authorization header goes with every request on this client, so a URL from a response is never called.""" - seen = [] - - def evil(request): - if request.url.params.get("page", "1") == "1": - return httpx.Response(200, json={"workflow_runs": []}, headers={"Link": '; rel="next"'}) - return httpx.Response(200, json={"workflow_runs": []}) - provider(on_runs=evil, seen=seen).pr_status(PR) - assert {r.url.host for r in seen} == {"github.test"} - - -def test_a_host_that_never_stops_paging_is_an_error_not_a_partial_read(): - calls = [] - - def endless(request): - calls.append(request) - return httpx.Response(200, json={"jobs": [job(CONTEXT_KYVERNO)]}, headers={"Link": f'<{API}/x?page=9>; rel="next"'}) - with pytest.raises(GitUnavailable, match="pages"): - provider(on_jobs=endless).pr_status(PR) - assert len(calls) == GitHubProvider.MAX_PAGES - - -@pytest.mark.parametrize("which", ["runs", "jobs"]) -@pytest.mark.parametrize("code", [401, 403, 404, 422]) -def test_a_refused_read_raises_instead_of_reading_as_no_ci(code, which): - """403 is what a token without Actions read gets ("Resource not accessible by personal access token", #279): the request - records it at each attempt and fails, never a wait read as CI that has not reported.""" - refuse = lambda r: httpx.Response(code, json={"message": "Resource not accessible by personal access token"}) # noqa: E731 - with pytest.raises(GitUnavailable, match=f"{code}.*Resource not accessible"): - provider(**{f"on_{which}": refuse}).pr_status(PR) - - -@pytest.mark.parametrize("code", [429, 502]) -def test_a_5xx_or_429_is_retryable(code): - with pytest.raises(GitUnavailable): - provider(on_runs=lambda r: httpx.Response(code, text="busy")).pr_status(PR) - - -def test_a_refused_later_page_of_runs_raises(): - def runs(request): - if request.url.params.get("page", "1") == "1": - return httpx.Response(200, json={"workflow_runs": [{"id": 1, "head_sha": SHA}]}, - headers={"Link": f'<{API}{request.url.path}?page=2>; rel="next"'}) - return httpx.Response(403, json={"message": "Resource not accessible"}) - with pytest.raises(GitUnavailable, match="403"): - provider(on_runs=runs).pr_status(PR) - - -@pytest.mark.parametrize("pr,state,merge_sha", [ - ({"state": "closed", "merged": True, "merge_commit_sha": "d" * 40, "head": {"sha": SHA}}, "merged", "d" * 40), - ({"state": "closed", "merged": False, "merge_commit_sha": "e" * 40, "head": {"sha": SHA}}, "closed", None), -]) -def test_a_finished_pr_needs_no_read_of_its_ci(pr, state, merge_sha): - got = provider(pr=pr, on_runs=lambda r: httpx.Response(403, json={"message": "no"})).pr_status(PR) - assert (got.state, got.merge_sha, dict(got.checks), got.head_sha) == (state, merge_sha, {}, SHA) - - -def test_ci_run_lookup_identifies_the_workflow_event_and_head(): - seen = [] - provider(runs={}, seen=seen).pr_status(PR) - request, = [r for r in seen if "/actions/" in r.url.path] - assert request.url.path == "/repos/o/r/actions/workflows/ci.yml/runs" - assert dict(request.url.params) == {"head_sha": SHA, "event": "pull_request", "per_page": "100", "page": "1"} - - -@pytest.mark.parametrize("fields", [ - {"event": "push"}, - {"head_branch": "cmapi/CRC/r2"}, # another branch at the same commit - {"head_branch": None}, - {"head_repository": {"full_name": "fork/r"}}, # a fork's PR on the same commit and branch name - {"head_repository": None}, # the fork was deleted - {"head_repository": {"full_name": "fork/r"}, "pull_requests": [{"number": PR.number}]}, -], ids=["push", "another-branch", "no-branch", "fork", "no-repository", "fork-listing-this-pr"]) -def test_a_run_that_is_not_this_pull_requests_is_not_inspected(fields): - def jobs(request): - pytest.fail("requested the jobs of a run that is not this PR's") - - got = checks(on_runs=lambda request: httpx.Response(200, json={"total_count": 1, "workflow_runs": [run_of(**fields)]}), - on_jobs=jobs) - assert got == {} - - -@pytest.mark.parametrize("pull_requests", [[], None, [{"number": 8}]], ids=["empty", "null", "another-number"]) -def test_this_prs_run_is_credited_whatever_pull_requests_holds(pull_requests): - """pull_requests lists open PRs that match by head_sha or head_branch, "not necessarily" the one that triggered the run - (github/rest-api-description, fetched 2026-12-01), and it was [] on every pull_request run measured on - cmapi-cluster-configs that day. The run's repository, branch, commit, event and workflow identify it.""" - got = checks(on_runs=lambda request: httpx.Response(200, json={ - "total_count": 1, "workflow_runs": [run_of(pull_requests=pull_requests)]})) - assert got == {CONTEXT_KUBECONFORM: "success", CONTEXT_KYVERNO: "success"} - - -def test_the_repository_name_is_compared_without_case(): - got = checks(on_runs=lambda request: httpx.Response(200, json={ - "total_count": 1, "workflow_runs": [run_of(head_repository={"full_name": "O/R"})]})) - assert got == {CONTEXT_KUBECONFORM: "success", CONTEXT_KYVERNO: "success"} - - -@pytest.mark.parametrize("observed", ["d" * 40, None]) -def test_ci_lookup_requires_the_open_pr_to_report_the_approved_head(observed): - def runs(request): - pytest.fail("requested CI without a matching approved head") - - state = provider(pr={"state": "open", "head": {"sha": observed}}, on_runs=runs).pr_status(PR) - assert state.head_sha == observed - assert state.checks == {} - - -def test_a_rerun_during_job_pagination_discards_the_read(): - seen_pages = [] - - def handle(request): - path = request.url.path - if path.endswith("/pulls/7"): - return httpx.Response(200, json={"state": "open", "head": {"sha": SHA}}) - if path.endswith("/runs"): - return paged(request, "workflow_runs", [run_of()]) - if path.endswith("/1/jobs"): - seen_pages.append(int(request.url.params["page"])) - return paged(request, "jobs", [job(f"lint-{i}") for i in range(101)]) - assert path == RUNS + "/1" - return httpx.Response(200, json={"id": 1, "run_attempt": 2}) - - git = GitHubProvider(API, "o/r", "token") - git._client = httpx.Client(base_url=API, transport=httpx.MockTransport(handle)) - assert git.pr_status(PR).checks == {} - assert seen_pages == [1, 2] - - -def test_a_list_answer_without_its_key_reads_as_empty(): - assert checks(on_runs=lambda request: httpx.Response(200, json={"total_count": 0})) == {} - - -def test_the_ci_workflow_file_is_ci_yml_unless_configured(): - from cmapi.core.git import make_provider - - assert GitHubProvider(API, "o/r", "token").ci_workflow == "ci.yml" - assert make_provider("github", API, "o/r", "token").ci_workflow == "ci.yml" - assert make_provider("github", API, "o/r", "token", ci_workflow="validate.yaml").ci_workflow == "validate.yaml" - seen = [] - - def handle(request): - seen.append(request.url.path) - if request.url.path == "/repos/o/r/pulls/7": - return httpx.Response(200, json={"state": "open", "merged": False, "head": {"sha": SHA, "ref": PR.branch}}) - if request.url.path == "/repos/o/r/actions/workflows/validate.yaml/runs": - return httpx.Response(200, json={"total_count": 1, "workflow_runs": [run_of(5)]}) - if request.url.path == RUNS + "/5/jobs": - return httpx.Response(200, json={"total_count": 1, "jobs": [job(CONTEXT_KYVERNO)]}) - return httpx.Response(404, json={"message": "Not Found"}) - - git = GitHubProvider(API, "o/r", "token", ci_workflow="validate.yaml") - git._client = httpx.Client(base_url=API, transport=httpx.MockTransport(handle)) - assert dict(git.pr_status(PR).checks) == {CONTEXT_KYVERNO: "success"} - assert "/repos/o/r/actions/workflows/validate.yaml/runs" in seen and RUN_LOOKUP not in seen - - -@pytest.mark.parametrize("value,ok", [("ci.yml", True), ("validate.yaml", True), (None, True), - (".github/workflows/ci.yml", False), ("ci", False), ("../ci.yml", False), - ("ci.yml?event=push", False), ("", False), (7, False), (True, False)]) -def test_the_configured_ci_workflow_is_a_file_name(value, ok): - """GET .../actions/workflows/{workflow_id}/runs takes "the workflow file name" (REST docs, fetched 2026-12-01): one path - segment. A path, or text that would change the URL, stops the start.""" - from cmapi.core.config import _git_problems - - problems = _git_problems({} if value is None else {"ciWorkflow": value}) - assert (problems == []) is ok, problems - assert ok or "git.ciWorkflow" in problems[0] +"""GitHub's PR adapter reads host CI from the config repository's Actions: the workflow jobs of the PR head, by name, through +the Actions API (#60). Not the commit statuses, which the bot's own token can post, and not the Checks API, which a +fine-grained token cannot call (BUG-69, #279). Host CI is on by default. The provider runs on a MockTransport shaped by GitHub's +REST docs, "Workflow runs" and "Workflow jobs" (fetched 2026-12-01), and by the answers measured on cmapi-cluster-configs that +day (run 45649310281: jobs ci/kubeconform and ci/kyverno, each the check run of the same name and id, app github-actions).""" +from __future__ import annotations + +import httpx +import pytest + +from cmapi.core.git.base import GitUnavailable, IncompleteList +from cmapi.core.git.github import GitHubProvider +from cmapi.core.ports import PrRef +from cmapi.jobs.pr_checks import CONTEXT_KUBECONFORM, CONTEXT_KYVERNO + +SHA = "c" * 40 +API = "https://github.test" +PR = PrRef(7, "https://github.test/o/r/pull/7", "cmapi/CRC/r1", SHA) +RUNS = "/repos/o/r/actions/runs" +RUN_LOOKUP = "/repos/o/r/actions/workflows/ci.yml/runs" + + +def run_of(run_id=1, **fields): + """One pull_request run of this PR as GitHub lists it. pull_requests is empty, as measured on cmapi-cluster-configs.""" + return {"id": run_id, "run_attempt": 1, "head_sha": SHA, "event": "pull_request", "head_branch": PR.branch, + "head_repository": {"full_name": "o/r"}, "pull_requests": [], **fields} + + +def job(name, conclusion="success", status="completed"): + return {"name": name, "status": status, "conclusion": conclusion, "head_sha": SHA} + + +def paged(request, key, items): + per_page, page = min(int(request.url.params.get("per_page", 30)), 100), int(request.url.params.get("page", 1)) + chunk = items[(page - 1) * per_page:page * per_page] + headers = {} + if page * per_page < len(items): + headers["Link"] = f'<{API}{request.url.path}?per_page={per_page}&page={page + 1}>; rel="next"' + return httpx.Response(200, json={"total_count": len(items), key: chunk}, headers=headers) + + +def provider(runs=None, *, seen=None, pr=None, on_runs=None, on_jobs=None, **kw): + """runs: {run id: [jobs]} on SHA.""" + runs = {1: [job(CONTEXT_KUBECONFORM), job(CONTEXT_KYVERNO)]} if runs is None else runs + + def handle(request): + if seen is not None: + seen.append(request) + path = request.url.path + assert "check-runs" not in path and "check-suites" not in path, "the Checks API is never called" + assert "/status" not in path, "a commit status is never read as CI: the bot's token can post one (#60)" + if path == "/repos/o/r/pulls/7": + return httpx.Response(200, json=pr or {"state": "open", "merged": False, "head": {"sha": SHA, "ref": PR.branch}}) + if path in (RUN_LOOKUP, RUNS): + if on_runs: + return on_runs(request) + assert request.url.params["head_sha"] == SHA + return paged(request, "workflow_runs", [run_of(i) for i in runs]) + if path.startswith(RUNS + "/") and path.endswith("/jobs"): + if on_jobs: + return on_jobs(request) + assert request.url.params["filter"] == "latest", "a re-run's newest attempt alone" + return paged(request, "jobs", runs[int(path.split("/")[-2])]) + if path.startswith(RUNS + "/") and path.split("/")[-1].isdigit(): + return httpx.Response(200, json={"run_attempt": 1}) + return httpx.Response(404, json={"message": f"not routed: {path}"}) + git = GitHubProvider(API, "o/r", "token", **kw) + git._client = httpx.Client(base_url=API, transport=httpx.MockTransport(handle)) + return git + + +def checks(**kw): + return dict(provider(**kw).pr_status(PR).checks) + + +def test_state_only_read_skips_the_actions_api(): + seen = [] + + status = provider(seen=seen).pr_status(PR, ci=False) + + assert status.state == "open" and status.checks == {} + assert [r.url.path for r in seen] == ["/repos/o/r/pulls/7"] + + +def test_host_ci_is_on_by_default_and_the_worker_posts_cmapi_check_alone(): + git = GitHubProvider(API, "o/r", "token") + assert (git.external_ci, git.post_statuses, git.posts_ci) == (True, True, False) + + +def test_host_ci_off_reads_nothing_and_posts_nothing(): + seen = [] + git = provider(seen=seen, host_checks=False) + assert git.pr_status(PR).checks == {} and not git.external_ci and not git.post_statuses and not git.posts_ci + assert [r.url.path for r in seen] == ["/repos/o/r/pulls/7"] + + +def test_post_status_without_host_ci_still_posts_no_ci_context(): + git = GitHubProvider(API, "o/r", "token", host_checks=False, post_status=True) + assert git.post_statuses and not git.posts_ci and not git.external_ci + + +def test_the_two_jobs_of_the_workflow_read_as_the_two_ci_contexts(): + assert checks() == {CONTEXT_KUBECONFORM: "success", CONTEXT_KYVERNO: "success"} + + +@pytest.mark.parametrize("status,conclusion,expected", [ + ("completed", "success", "success"), + ("completed", "failure", "failure"), + ("completed", "cancelled", "failure"), + ("completed", "timed_out", "failure"), + ("completed", "action_required", "failure"), + ("completed", "skipped", "failure"), # validated nothing: not a pass here, though branch protection passes it + ("completed", "neutral", "failure"), + ("completed", None, "pending"), # completed before its conclusion is there (#87, e6300b8c) + ("queued", None, "pending"), + ("in_progress", None, "pending"), + ("waiting", None, "pending"), + ("requested", None, "pending"), + ("pending", None, "pending"), + ("in_progress", "success", "pending"), # unfinished, whatever the conclusion field says +]) +def test_each_job_state_reads_as_a_check_state(status, conclusion, expected): + assert checks(runs={1: [job(CONTEXT_KYVERNO, conclusion, status)]}) == {CONTEXT_KYVERNO: expected} + + +@pytest.mark.parametrize("other", ["success", "failure"]) +def test_one_name_in_two_runs_of_the_ci_workflow_reads_as_the_worse(other): + got = checks(runs={1: [job(CONTEXT_KYVERNO, "failure")], 2: [job(CONTEXT_KYVERNO, other)]}) + assert got == {CONTEXT_KYVERNO: "failure"} + + +def test_a_name_that_no_job_carries_is_not_invented(): + assert checks(runs={1: [job(CONTEXT_KUBECONFORM)]}) == {CONTEXT_KUBECONFORM: "success"} + assert checks(runs={}) == {} + + +def test_a_run_of_another_commit_says_nothing_about_this_one(): + def runs(request): + return paged(request, "workflow_runs", [run_of(head_sha="d" * 40)]) + + def jobs(request): + raise AssertionError("the jobs of another commit's run are not read") + assert checks(on_runs=runs, on_jobs=jobs) == {} + + +def test_it_asks_for_the_runs_of_the_pr_head_and_the_latest_attempt_of_each_job(): + seen = [] + provider(seen=seen).pr_status(PR) + runs = [r for r in seen if r.url.path == RUN_LOOKUP] + jobs = [r for r in seen if r.url.path.endswith("/jobs")] + assert [r.url.params["head_sha"] for r in runs] == [SHA] + assert [(r.url.path, r.url.params["filter"]) for r in jobs] == [(f"{RUNS}/1/jobs", "latest")] + + +def test_a_failure_on_a_later_page_of_jobs_counts(): + got = checks(runs={1: [job(f"other-{i}") for i in range(150)] + [job(CONTEXT_KYVERNO, "failure")]}) + assert len(got) == 151 and got[CONTEXT_KYVERNO] == "failure" + + +def test_a_run_on_a_later_page_of_runs_is_read(): + runs = {i: [] for i in range(1, 151)} + runs[150] = [job(CONTEXT_KYVERNO, "failure")] + assert checks(runs=runs) == {CONTEXT_KYVERNO: "failure"} + + +def test_as_many_runs_as_github_can_list_for_one_commit_is_not_read_as_complete(): + """"This endpoint will return up to 1,000 results for each search when using ... head_sha" (REST docs, 2026-12-01).""" + with pytest.raises(IncompleteList, match="1000"): + provider(runs={i: [] for i in range(1, 1001)}).pr_status(PR) + + +def test_the_next_link_is_a_signal_and_is_never_followed_to_another_host(): + """The Authorization header goes with every request on this client, so a URL from a response is never called.""" + seen = [] + + def evil(request): + if request.url.params.get("page", "1") == "1": + return httpx.Response(200, json={"workflow_runs": []}, headers={"Link": '; rel="next"'}) + return httpx.Response(200, json={"workflow_runs": []}) + provider(on_runs=evil, seen=seen).pr_status(PR) + assert {r.url.host for r in seen} == {"github.test"} + + +def test_a_host_that_never_stops_paging_is_an_error_not_a_partial_read(): + calls = [] + + def endless(request): + calls.append(request) + return httpx.Response(200, json={"jobs": [job(CONTEXT_KYVERNO)]}, headers={"Link": f'<{API}/x?page=9>; rel="next"'}) + with pytest.raises(GitUnavailable, match="pages"): + provider(on_jobs=endless).pr_status(PR) + assert len(calls) == GitHubProvider.MAX_PAGES + + +@pytest.mark.parametrize("which", ["runs", "jobs"]) +@pytest.mark.parametrize("code", [401, 403, 404, 422]) +def test_a_refused_read_raises_instead_of_reading_as_no_ci(code, which): + """403 is what a token without Actions read gets ("Resource not accessible by personal access token", #279): the request + records it at each attempt and fails, never a wait read as CI that has not reported.""" + refuse = lambda r: httpx.Response(code, json={"message": "Resource not accessible by personal access token"}) # noqa: E731 + with pytest.raises(GitUnavailable, match=f"{code}.*Resource not accessible"): + provider(**{f"on_{which}": refuse}).pr_status(PR) + + +@pytest.mark.parametrize("code", [429, 502]) +def test_a_5xx_or_429_is_retryable(code): + with pytest.raises(GitUnavailable): + provider(on_runs=lambda r: httpx.Response(code, text="busy")).pr_status(PR) + + +def test_a_refused_later_page_of_runs_raises(): + def runs(request): + if request.url.params.get("page", "1") == "1": + return httpx.Response(200, json={"workflow_runs": [{"id": 1, "head_sha": SHA}]}, + headers={"Link": f'<{API}{request.url.path}?page=2>; rel="next"'}) + return httpx.Response(403, json={"message": "Resource not accessible"}) + with pytest.raises(GitUnavailable, match="403"): + provider(on_runs=runs).pr_status(PR) + + +@pytest.mark.parametrize("pr,state,merge_sha", [ + ({"state": "closed", "merged": True, "merge_commit_sha": "d" * 40, "head": {"sha": SHA}}, "merged", "d" * 40), + ({"state": "closed", "merged": False, "merge_commit_sha": "e" * 40, "head": {"sha": SHA}}, "closed", None), +]) +def test_a_finished_pr_needs_no_read_of_its_ci(pr, state, merge_sha): + got = provider(pr=pr, on_runs=lambda r: httpx.Response(403, json={"message": "no"})).pr_status(PR) + assert (got.state, got.merge_sha, dict(got.checks), got.head_sha) == (state, merge_sha, {}, SHA) + + +def test_ci_run_lookup_identifies_the_workflow_event_and_head(): + seen = [] + provider(runs={}, seen=seen).pr_status(PR) + request, = [r for r in seen if "/actions/" in r.url.path] + assert request.url.path == "/repos/o/r/actions/workflows/ci.yml/runs" + assert dict(request.url.params) == {"head_sha": SHA, "event": "pull_request", "per_page": "100", "page": "1"} + + +@pytest.mark.parametrize("fields", [ + {"event": "push"}, + {"head_branch": "cmapi/CRC/r2"}, # another branch at the same commit + {"head_branch": None}, + {"head_repository": {"full_name": "fork/r"}}, # a fork's PR on the same commit and branch name + {"head_repository": None}, # the fork was deleted + {"head_repository": {"full_name": "fork/r"}, "pull_requests": [{"number": PR.number}]}, +], ids=["push", "another-branch", "no-branch", "fork", "no-repository", "fork-listing-this-pr"]) +def test_a_run_that_is_not_this_pull_requests_is_not_inspected(fields): + def jobs(request): + pytest.fail("requested the jobs of a run that is not this PR's") + + got = checks(on_runs=lambda request: httpx.Response(200, json={"total_count": 1, "workflow_runs": [run_of(**fields)]}), + on_jobs=jobs) + assert got == {} + + +@pytest.mark.parametrize("pull_requests", [[], None, [{"number": 8}]], ids=["empty", "null", "another-number"]) +def test_this_prs_run_is_credited_whatever_pull_requests_holds(pull_requests): + """pull_requests lists open PRs that match by head_sha or head_branch, "not necessarily" the one that triggered the run + (github/rest-api-description, fetched 2026-12-01), and it was [] on every pull_request run measured on + cmapi-cluster-configs that day. The run's repository, branch, commit, event and workflow identify it.""" + got = checks(on_runs=lambda request: httpx.Response(200, json={ + "total_count": 1, "workflow_runs": [run_of(pull_requests=pull_requests)]})) + assert got == {CONTEXT_KUBECONFORM: "success", CONTEXT_KYVERNO: "success"} + + +def test_the_repository_name_is_compared_without_case(): + got = checks(on_runs=lambda request: httpx.Response(200, json={ + "total_count": 1, "workflow_runs": [run_of(head_repository={"full_name": "O/R"})]})) + assert got == {CONTEXT_KUBECONFORM: "success", CONTEXT_KYVERNO: "success"} + + +@pytest.mark.parametrize("observed", ["d" * 40, None]) +def test_ci_lookup_requires_the_open_pr_to_report_the_approved_head(observed): + def runs(request): + pytest.fail("requested CI without a matching approved head") + + state = provider(pr={"state": "open", "head": {"sha": observed}}, on_runs=runs).pr_status(PR) + assert state.head_sha == observed + assert state.checks == {} + + +def test_a_rerun_during_job_pagination_discards_the_read(): + seen_pages = [] + + def handle(request): + path = request.url.path + if path.endswith("/pulls/7"): + return httpx.Response(200, json={"state": "open", "head": {"sha": SHA}}) + if path.endswith("/runs"): + return paged(request, "workflow_runs", [run_of()]) + if path.endswith("/1/jobs"): + seen_pages.append(int(request.url.params["page"])) + return paged(request, "jobs", [job(f"lint-{i}") for i in range(101)]) + assert path == RUNS + "/1" + return httpx.Response(200, json={"id": 1, "run_attempt": 2}) + + git = GitHubProvider(API, "o/r", "token") + git._client = httpx.Client(base_url=API, transport=httpx.MockTransport(handle)) + assert git.pr_status(PR).checks == {} + assert seen_pages == [1, 2] + + +def test_a_list_answer_without_its_key_reads_as_empty(): + assert checks(on_runs=lambda request: httpx.Response(200, json={"total_count": 0})) == {} + + +def test_the_ci_workflow_file_is_ci_yml_unless_configured(): + from cmapi.core.git import make_provider + + assert GitHubProvider(API, "o/r", "token").ci_workflow == "ci.yml" + assert make_provider("github", API, "o/r", "token").ci_workflow == "ci.yml" + assert make_provider("github", API, "o/r", "token", ci_workflow="validate.yaml").ci_workflow == "validate.yaml" + seen = [] + + def handle(request): + seen.append(request.url.path) + if request.url.path == "/repos/o/r/pulls/7": + return httpx.Response(200, json={"state": "open", "merged": False, "head": {"sha": SHA, "ref": PR.branch}}) + if request.url.path == "/repos/o/r/actions/workflows/validate.yaml/runs": + return httpx.Response(200, json={"total_count": 1, "workflow_runs": [run_of(5)]}) + if request.url.path == RUNS + "/5/jobs": + return httpx.Response(200, json={"total_count": 1, "jobs": [job(CONTEXT_KYVERNO)]}) + return httpx.Response(404, json={"message": "Not Found"}) + + git = GitHubProvider(API, "o/r", "token", ci_workflow="validate.yaml") + git._client = httpx.Client(base_url=API, transport=httpx.MockTransport(handle)) + assert dict(git.pr_status(PR).checks) == {CONTEXT_KYVERNO: "success"} + assert "/repos/o/r/actions/workflows/validate.yaml/runs" in seen and RUN_LOOKUP not in seen + + +@pytest.mark.parametrize("value,ok", [("ci.yml", True), ("validate.yaml", True), (None, True), + (".github/workflows/ci.yml", False), ("ci", False), ("../ci.yml", False), + ("ci.yml?event=push", False), ("", False), (7, False), (True, False)]) +def test_the_configured_ci_workflow_is_a_file_name(value, ok): + """GET .../actions/workflows/{workflow_id}/runs takes "the workflow file name" (REST docs, fetched 2026-12-01): one path + segment. A path, or text that would change the URL, stops the start.""" + from cmapi.core.config import _git_problems + + problems = _git_problems({} if value is None else {"ciWorkflow": value}) + assert (problems == []) is ok, problems + assert ok or "git.ciWorkflow" in problems[0] From a002f37183ae093050558e7bc12185fde8f45ae1 Mon Sep 17 00:00:00 2001 From: Arthur Araujo da Silva <164519555+BlackYuriJDU@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:17:16 +0000 Subject: [PATCH 3/3] chore: remove build metadata committed by mistake cmapi.egg-info is generated by an editable install and does not belong in the repository. Remove it from the previous commit. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_012fbGqictriLD4EWAf37sNa --- cmapi/src/cmapi.egg-info/PKG-INFO | 22 --- cmapi/src/cmapi.egg-info/SOURCES.txt | 164 ------------------ cmapi/src/cmapi.egg-info/dependency_links.txt | 1 - cmapi/src/cmapi.egg-info/entry_points.txt | 5 - cmapi/src/cmapi.egg-info/requires.txt | 18 -- cmapi/src/cmapi.egg-info/top_level.txt | 1 - 6 files changed, 211 deletions(-) delete mode 100644 cmapi/src/cmapi.egg-info/PKG-INFO delete mode 100644 cmapi/src/cmapi.egg-info/SOURCES.txt delete mode 100644 cmapi/src/cmapi.egg-info/dependency_links.txt delete mode 100644 cmapi/src/cmapi.egg-info/entry_points.txt delete mode 100644 cmapi/src/cmapi.egg-info/requires.txt delete mode 100644 cmapi/src/cmapi.egg-info/top_level.txt diff --git a/cmapi/src/cmapi.egg-info/PKG-INFO b/cmapi/src/cmapi.egg-info/PKG-INFO deleted file mode 100644 index 88ad8078..00000000 --- a/cmapi/src/cmapi.egg-info/PKG-INFO +++ /dev/null @@ -1,22 +0,0 @@ -Metadata-Version: 2.4 -Name: cmapi -Version: 0.2.0 -Summary: cmapi: one API and portal for namespaces across OpenShift clusters, with every write a pull request -Requires-Python: >=3.12 -Requires-Dist: fastapi==0.162.2 -Requires-Dist: starlette==1.10.0 -Requires-Dist: uvicorn[standard]==0.32.1 -Requires-Dist: pydantic==2.14.2 -Requires-Dist: pydantic-settings==2.16.2 -Requires-Dist: sqlalchemy==2.1.8 -Requires-Dist: psycopg[binary]==3.3.8 -Requires-Dist: alembic==1.20.1 -Requires-Dist: httpx==0.28.1 -Requires-Dist: pyjwt[crypto]==2.15.1 -Requires-Dist: pyyaml==6.0.2 -Requires-Dist: google-re2==1.1.20251105 -Requires-Dist: prometheus-client==0.24.1 -Requires-Dist: structlog==26.1.0 -Provides-Extra: test -Requires-Dist: pytest==9.2.0; extra == "test" -Requires-Dist: jsonschema==4.26.0; extra == "test" diff --git a/cmapi/src/cmapi.egg-info/SOURCES.txt b/cmapi/src/cmapi.egg-info/SOURCES.txt deleted file mode 100644 index 3fecec99..00000000 --- a/cmapi/src/cmapi.egg-info/SOURCES.txt +++ /dev/null @@ -1,164 +0,0 @@ -pyproject.toml -src/cmapi/__init__.py -src/cmapi/main.py -src/cmapi/settings.py -src/cmapi/worker.py -src/cmapi.egg-info/PKG-INFO -src/cmapi.egg-info/SOURCES.txt -src/cmapi.egg-info/dependency_links.txt -src/cmapi.egg-info/entry_points.txt -src/cmapi.egg-info/requires.txt -src/cmapi.egg-info/top_level.txt -src/cmapi/capacity/__init__.py -src/cmapi/capacity/snapshots.py -src/cmapi/capacity/sweep.py -src/cmapi/capacity/thanos.py -src/cmapi/capacity/usage.py -src/cmapi/capacity/verdicts.py -src/cmapi/contract/__init__.py -src/cmapi/contract/changelog.json -src/cmapi/contract/samples.json -src/cmapi/core/__init__.py -src/cmapi/core/adoption.py -src/cmapi/core/approvals.py -src/cmapi/core/auth.py -src/cmapi/core/authz.py -src/cmapi/core/bodylimit.py -src/cmapi/core/capacity.py -src/cmapi/core/capacity_backend.py -src/cmapi/core/capacity_ledger.py -src/cmapi/core/changelog.py -src/cmapi/core/channels.py -src/cmapi/core/cluster_tokens.py -src/cmapi/core/clustertls.py -src/cmapi/core/config.py -src/cmapi/core/configfile.py -src/cmapi/core/context.py -src/cmapi/core/cors.py -src/cmapi/core/docs.py -src/cmapi/core/errors.py -src/cmapi/core/etag.py -src/cmapi/core/expression.py -src/cmapi/core/giturl.py -src/cmapi/core/http_settings.py -src/cmapi/core/kpi.py -src/cmapi/core/kube_yaml.py -src/cmapi/core/lifecycle.py -src/cmapi/core/listquery.py -src/cmapi/core/metadata.py -src/cmapi/core/models.py -src/cmapi/core/naming.py -src/cmapi/core/observability.py -src/cmapi/core/operations.py -src/cmapi/core/pipeline.py -src/cmapi/core/placement.py -src/cmapi/core/plan_read.py -src/cmapi/core/plugins.py -src/cmapi/core/policy.py -src/cmapi/core/policybundle.py -src/cmapi/core/policygen.py -src/cmapi/core/ports.py -src/cmapi/core/problem_docs.py -src/cmapi/core/ratelimit.py -src/cmapi/core/registry.py -src/cmapi/core/rejections.py -src/cmapi/core/sync.py -src/cmapi/core/tiers.py -src/cmapi/core/views.py -src/cmapi/core/clients/__init__.py -src/cmapi/core/clients/kube.py -src/cmapi/core/clients/nodes.py -src/cmapi/core/clients/policyreports.py -src/cmapi/core/clients/redact.py -src/cmapi/core/clients/trust.py -src/cmapi/core/db/__init__.py -src/cmapi/core/db/alembic.ini -src/cmapi/core/db/migrate.py -src/cmapi/core/db/models.py -src/cmapi/core/db/repo.py -src/cmapi/core/db/migrations/env.py -src/cmapi/core/db/migrations/versions/0001_cmapi_schema.py -src/cmapi/core/db/migrations/versions/0002_one_approval_per_person.py -src/cmapi/core/db/migrations/versions/0003_job_lease_generation.py -src/cmapi/core/db/migrations/versions/0004_approval_counted_for.py -src/cmapi/core/db/migrations/versions/0005_applied_and_merge_failed_hold_the_lock.py -src/cmapi/core/db/migrations/versions/0006_policy_rejections.py -src/cmapi/core/db/migrations/versions/0007_request_event_clock_timestamp.py -src/cmapi/core/db/migrations/versions/0008_idempotency_key_of_the_caller.py -src/cmapi/core/db/migrations/versions/0009_idempotency_key_of_the_caller_only.py -src/cmapi/core/db/migrations/versions/0010_usage_verdicts.py -src/cmapi/core/db/migrations/versions/0011_capacity_reservations.py -src/cmapi/core/db/migrations/versions/0012_capacity_snapshots_and_placements.py -src/cmapi/core/db/migrations/versions/0013_operations.py -src/cmapi/core/db/migrations/versions/0014_approval_decision.py -src/cmapi/core/git/__init__.py -src/cmapi/core/git/base.py -src/cmapi/core/git/gitea.py -src/cmapi/core/git/github.py -src/cmapi/core/git/oplog.py -src/cmapi/core/git/transport.py -src/cmapi/core/git/workspace.py -src/cmapi/core/identity/__init__.py -src/cmapi/core/identity/checks.py -src/cmapi/core/identity/claims.py -src/cmapi/core/identity/directory.py -src/cmapi/core/identity/keycloak_admin.py -src/cmapi/core/render/__init__.py -src/cmapi/core/render/manifests.py -src/cmapi/core/validate/__init__.py -src/cmapi/jobs/__init__.py -src/cmapi/jobs/apply.py -src/cmapi/jobs/approval_timeout.py -src/cmapi/jobs/capacity_snapshot.py -src/cmapi/jobs/channel_notify.py -src/cmapi/jobs/delivery.py -src/cmapi/jobs/expire_check.py -src/cmapi/jobs/git_cleanup.py -src/cmapi/jobs/git_reconcile.py -src/cmapi/jobs/merge.py -src/cmapi/jobs/open_pr.py -src/cmapi/jobs/pr_checks.py -src/cmapi/jobs/push_branch.py -src/cmapi/jobs/rejections_prune.py -src/cmapi/jobs/token_renew.py -src/cmapi/jobs/usage_sweep.py -src/cmapi/jobs/watch_sync.py -src/cmapi/ops/__init__.py -src/cmapi/ops/templates/cluster-onboard.yaml -src/cmapi/ops/templates/rebuild-verify.yaml -src/cmapi/ops/templates/reconcile.yaml -src/cmapi/ops/templates/tiers-rerender.yaml -src/cmapi/plugins/__init__.py -src/cmapi/plugins/adoption/__init__.py -src/cmapi/plugins/adoption/router.py -src/cmapi/plugins/capacity/__init__.py -src/cmapi/plugins/capacity/placement.py -src/cmapi/plugins/capacity/router.py -src/cmapi/plugins/directory/__init__.py -src/cmapi/plugins/expiration/__init__.py -src/cmapi/plugins/expiration/router.py -src/cmapi/plugins/expiration/rules.py -src/cmapi/plugins/namespaces/__init__.py -src/cmapi/plugins/namespaces/router.py -src/cmapi/plugins/namespaces/state.py -src/cmapi/plugins/policies/__init__.py -src/cmapi/plugins/policies/router.py -src/cmapi/plugins/quotas/__init__.py -src/cmapi/plugins/tiers/__init__.py -src/cmapi/routers/__init__.py -src/cmapi/routers/admin.py -src/cmapi/routers/health.py -src/cmapi/routers/me.py -src/cmapi/routers/operations.py -src/cmapi/routers/requests.py -src/cmapi/tools/__init__.py -src/cmapi/tools/docs_assets.py -src/cmapi/tools/git_bootstrap.py -src/cmapi/tools/openapi.py -src/cmapi/tools/policies.py -src/cmapi/tools/realm_sync.py -src/cmapi/tools/reference_instance/approval-rules.yaml -src/cmapi/tools/reference_instance/authz-roles.yaml -src/cmapi/tools/reference_instance/expiration.yaml -src/cmapi/tools/reference_instance/instance.yaml -src/cmapi/tools/reference_instance/tiers.yaml \ No newline at end of file diff --git a/cmapi/src/cmapi.egg-info/dependency_links.txt b/cmapi/src/cmapi.egg-info/dependency_links.txt deleted file mode 100644 index 8b137891..00000000 --- a/cmapi/src/cmapi.egg-info/dependency_links.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/cmapi/src/cmapi.egg-info/entry_points.txt b/cmapi/src/cmapi.egg-info/entry_points.txt deleted file mode 100644 index 51c4ab29..00000000 --- a/cmapi/src/cmapi.egg-info/entry_points.txt +++ /dev/null @@ -1,5 +0,0 @@ -[console_scripts] -cmapi-api = cmapi.main:run -cmapi-migrate = cmapi.core.db.migrate:run -cmapi-tools = cmapi.tools:run -cmapi-worker = cmapi.worker:run diff --git a/cmapi/src/cmapi.egg-info/requires.txt b/cmapi/src/cmapi.egg-info/requires.txt deleted file mode 100644 index 668fb87f..00000000 --- a/cmapi/src/cmapi.egg-info/requires.txt +++ /dev/null @@ -1,18 +0,0 @@ -fastapi==0.162.2 -starlette==1.10.0 -uvicorn[standard]==0.32.1 -pydantic==2.14.2 -pydantic-settings==2.16.2 -sqlalchemy==2.1.8 -psycopg[binary]==3.3.8 -alembic==1.20.1 -httpx==0.28.1 -pyjwt[crypto]==2.15.1 -pyyaml==6.0.2 -google-re2==1.1.20251105 -prometheus-client==0.24.1 -structlog==26.1.0 - -[test] -pytest==9.2.0 -jsonschema==4.26.0 diff --git a/cmapi/src/cmapi.egg-info/top_level.txt b/cmapi/src/cmapi.egg-info/top_level.txt deleted file mode 100644 index ae4a906f..00000000 --- a/cmapi/src/cmapi.egg-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -cmapi