diff --git a/cmapi/src/cmapi/core/approvals.py b/cmapi/src/cmapi/core/approvals.py index 5b876163..8bf73091 100644 --- a/cmapi/src/cmapi/core/approvals.py +++ b/cmapi/src/cmapi/core/approvals.py @@ -115,6 +115,10 @@ def __init__(self, raw: Mapping[str, Any], allowed_environments: set[str] | None def load(cls, path: str | Path, allowed_environments: set[str] | None = None) -> "ApprovalRules": return cls(read_config(path, "approval-rules.yaml"), allowed_environments) + def requester_clients(self) -> set[str]: + """The service clients that the auto-approval policies name (requester.clients).""" + return {c for p in self.policies for c in (p.get("requester") or {}).get("clients") or []} + def tier_names(self) -> set[str]: return {t for p in self.policies for t in p.get("match", {}).get("tiers", [])} @@ -321,7 +325,9 @@ class ApprovalLedger: requirement: Requirement requester_sub: str # the person the request is for (Requester.sub) operation_starter_sub: str | None = None + # The owners of the service client that filed it (identity.clientOwners, #789): by sub, and by a group of the token. client_owner_subs: frozenset[str] = frozenset() + client_owner_groups: frozenset[str] = frozenset() entries: list[dict[str, Any]] = field(default_factory=list) def _seats(self) -> list[str]: @@ -404,7 +410,8 @@ def _eligible(self, person: Identity, verb: str, permitted: bool | None, entry: if person.sub in {e["sub"] for e in self.entries}: raise Problem.conflict("already-approved", "This person already approved the request" + ("" if verb == "approve" else ", and a person decides a request once")) - if person.sub in self.client_owner_subs or person.sub == self.operation_starter_sub: + if person.sub in self.client_owner_subs or self.client_owner_groups & person.groups \ + or person.sub == self.operation_starter_sub: raise Problem.conflict("self-approval", f"The operation starter or client owner cannot {verb}") if person.sub == self.requester_sub and not self.requirement.self_approval: raise Problem.conflict("self-approval", f"Requesters cannot {verb} their own request here" diff --git a/cmapi/src/cmapi/core/config.py b/cmapi/src/cmapi/core/config.py index df0d610c..df19d6e8 100644 --- a/cmapi/src/cmapi/core/config.py +++ b/cmapi/src/cmapi/core/config.py @@ -10,7 +10,8 @@ - the tier catalog covers exactly the served environments (expiration.yaml may leave a non-prod environment out: expiry is then refused there, the same as prod); - metadata-keys.yaml has emailDomains when any governed key uses email-in-domains; -- instance.yaml's identity.groupPath can name a group; +- instance.yaml's identity.groupPath can name a group, and identity.clientOwners maps each client ID to a list of usernames + and group paths (core/identity/owners.py, #789); - plugins.yaml, when the instance has one, names only plugins of this build, and its overrides for this instance name only served environments (core/plugins.py); - instance.yaml's git.url is a URL the Git layer may use, git.hostChecks is a boolean, git.username one line (#286), @@ -44,6 +45,7 @@ from cmapi.core.errors import Problem from cmapi.core.giturl import GitConfigError, parse_remote from cmapi.core.http_settings import DEFAULT_MAX_REQUEST_BODY_BYTES, parse_http +from cmapi.core.identity.owners import ClientOwners from cmapi.core.metadata import MetadataKeys from cmapi.core.plugins import PluginSwitch from cmapi.core.policy import PolicySettings @@ -70,6 +72,7 @@ class InstanceConfig: max_request_body_bytes: int = DEFAULT_MAX_REQUEST_BODY_BYTES # instance.yaml `http.maxRequestBodyBytes` (#683) rate_limits: dict[str, Limit] = field(default_factory=lambda: dict(DEFAULT_RATE_LIMITS)) # `http.rateLimits` (#689) adoption: AdoptionSettings = field(default_factory=AdoptionSettings) # adoption.yaml, optional (story #26) + client_owners: ClientOwners = field(default_factory=ClientOwners) # instance.yaml `identity.clientOwners` (#789) def environment_not_served(cfg: InstanceConfig, env: str) -> Problem: @@ -111,7 +114,8 @@ def build(name: str, fn): problems.append(f"{name}: {exc}") return None - template = (me.get("identity") or {}).get("groupPath", DEFAULT_GROUP_PATH) + identity = me.get("identity") or {} + template = identity.get("groupPath", DEFAULT_GROUP_PATH) try: check_group_path(template) except ValueError as exc: @@ -171,6 +175,8 @@ def build(name: str, fn): http = me.get("http") rate_limits, rate_problems = parse_rate_limits(http.get("rateLimits") if isinstance(http, Mapping) else None) problems.extend(rate_problems) + client_owners, owner_problems = ClientOwners.parse(identity.get("clientOwners")) + problems.extend(owner_problems) try: cluster_tokens = TokenPolicy().override(me.get("clusterTokens", {})) except ValueError as exc: @@ -178,7 +184,7 @@ def build(name: str, fn): if problems: raise ConfigError(problems) return InstanceConfig(me["name"], allowed, inst, approvals, roles, tiers, expiration, metadata, plugins, hashes, policy, - cluster_tls, cluster_tokens, max_request_body_bytes, rate_limits, adoption) + cluster_tls, cluster_tokens, max_request_body_bytes, rate_limits, adoption, client_owners) def _directory_problems(directory: Any) -> list[str]: diff --git a/cmapi/src/cmapi/core/context.py b/cmapi/src/cmapi/core/context.py index 157d90f7..73d49ab2 100644 --- a/cmapi/src/cmapi/core/context.py +++ b/cmapi/src/cmapi/core/context.py @@ -18,11 +18,11 @@ from cmapi.core.clients.nodes import NodeCache from cmapi.core.clients.policyreports import ReportCache from cmapi.core.config import InstanceConfig, load_instance -from cmapi.core.configfile import read_config +from cmapi.core.configfile import ConfigError, read_config from cmapi.core.db import Database from cmapi.core.db.repo import DbKeyStore, SwitchRepo from cmapi.core.git import HostGitProvider, make_provider -from cmapi.core.identity.directory import CachedDirectory +from cmapi.core.identity.directory import CachedDirectory, DirectoryUnavailable from cmapi.core.identity.keycloak_admin import KeycloakAdminDirectory, split_issuer from cmapi.core.listquery import Lister, Sorts, severity from cmapi.core.observability import AUTO_PAUSED, CONFIG_INFO, POLICY_MODE, VALIDATOR_WAIT @@ -97,15 +97,37 @@ def _yaml(path: Path) -> dict[str, Any]: def _http_for_directory(verify: str | bool): + """The directory's HTTP call (KeycloakAdminDirectory's `http`). A Keycloak that cannot be reached, or that answers 200 + with a body that is not JSON, is DirectoryUnavailable, which every caller turns into 503 idp-unavailable or serves from + the cache (#798). httpx's errors are not OSError, which is all the adapter catches: "RequestError: Base class for all + exceptions that may occur when issuing a .request()" (https://www.python-httpx.org/exceptions/). Only a 200 has a body + the adapter reads; a gateway's 502 or 503 is an HTML page, and reading it as JSON raised before the status was seen.""" def http(method: str, url: str, headers: dict[str, str], form: dict[str, str] | None): - r = httpx.request(method, url, headers=headers, data=form, timeout=10, verify=verify) - return r.status_code, (r.json() if r.content else None) + try: + r = httpx.request(method, url, headers=headers, data=form, timeout=10, verify=verify) + except httpx.RequestError as exc: + raise DirectoryUnavailable(f"{type(exc).__name__}: {exc}") from exc + if r.status_code != 200: + return r.status_code, None + try: + return r.status_code, r.json() + except ValueError as exc: # json.JSONDecodeError: an empty or non-JSON 200 + raise DirectoryUnavailable(f"the answer is not JSON: {exc}") from exc return http def build_context(settings: Settings, *, start_registry: bool = True, import_source: ImportSource | None = None) -> AppContext: cfg = load_instance(settings.config_dir, settings.metadata_keys_path) inst = cfg.raw_instance["instance"] + ident = inst.get("identity") or {} + has_directory = ident.get("directory", "keycloak") == "keycloak" and bool(settings.directory_client_secret) + named = cfg.client_owners.usernames() + if named and not has_directory: + # A username is compared by its sub, which only the directory gives: without one every request of these clients + # would be refused, so the start stops instead (#789). + raise ConfigError([f"instance.yaml: identity.clientOwners names usernames ({', '.join(sorted(named))}), and cmapi has " + "no directory to resolve them: set CMAPI_DIRECTORY_CLIENT_SECRET with identity.directory keycloak, " + "or name groups only"]) issuer, audience = inst["auth"]["issuer"], inst["auth"]["audience"] jwks_url = settings.oidc_jwks_url or f"{issuer}/protocol/openid-connect/certs" db = Database(settings.database_url, settings.database_pool_size) @@ -179,8 +201,7 @@ def nodes_for(st: ClusterState, client: KubeClient) -> NodeCache: usage = usage_source(capacity_cfg, registry) directory = None - ident = inst.get("identity") or {} - if ident.get("directory", "keycloak") == "keycloak" and settings.directory_client_secret: + if has_directory: base, realm = split_issuer(issuer) # the realm's name, decoded once from the issuer (#640) directory = CachedDirectory(KeycloakAdminDirectory(settings.keycloak_admin_url or base, realm, ident.get("adminClient", "cmapi-directory"), diff --git a/cmapi/src/cmapi/core/db/repo.py b/cmapi/src/cmapi/core/db/repo.py index cb6f7055..456fdc07 100644 --- a/cmapi/src/cmapi/core/db/repo.py +++ b/cmapi/src/cmapi/core/db/repo.py @@ -149,6 +149,12 @@ def auto_approvals_today(self, team: str) -> int: ChangeRequestRow.team == team, ChangeRequestRow.created_at >= start, ChangeRequestRow.requirement["auto"].astext.like("auto:%"))) or 0 + def clients_that_filed_for_others(self) -> list[str]: + """Each service client that has filed a request for another person (onBehalfOf): what the start names when the + client has no entry in identity.clientOwners (#789).""" + return sorted(self.s.scalars(select(ChangeRequestRow.requester_client).distinct().where( + ChangeRequestRow.requester_kind == "service", ChangeRequestRow.requester.has_key("submittedByClient")))) + def in_states(self, states: Iterable[str]) -> list[ChangeRequestRow]: return list(self.s.scalars(select(ChangeRequestRow).where(ChangeRequestRow.status.in_(list(states))))) @@ -244,11 +250,15 @@ def ledger(self, row: ChangeRequestRow) -> ApprovalLedger | None: req = requirement_from_json(row.requirement) if req is None or not req.slots: return None - # Who filed it for someone else is a second identity on the request: under a no-self-approval - # rule that identity may not approve it either. - submitter = (row.requester or {}).get("submittedBySub") + # Who filed it for someone else is a second identity on the request, and the owners of the service client that + # filed it are a third (#789, stored when it was filed): under a no-self-approval rule none of them may decide it. + # An operation's step holds two snapshots, its sender's and its starter's client's, and the ledger refuses both. + record = row.requester or {} + owners = [] if req.self_approval else [record[k] for k in ("clientOwners", "starterClientOwners") if record.get(k)] ledger = ApprovalLedger(req, requester_sub=row.requester_sub, - operation_starter_sub=None if req.self_approval else submitter) + operation_starter_sub=None if req.self_approval else record.get("submittedBySub"), + client_owner_subs=frozenset(sub for o in owners for sub in o.get("subs", ())), + client_owner_groups=frozenset(group for o in owners for group in o.get("groups", ()))) for a in self.approvals(row.request_id): ledger.entries.append({"sub": a.approver_sub, "username": a.username, "groups": frozenset(a.groups), "comment": a.comment, "relayedBy": a.relayed_by, "at": a.at}) diff --git a/cmapi/src/cmapi/core/identity/checks.py b/cmapi/src/cmapi/core/identity/checks.py index ff8ca987..71f2b825 100644 --- a/cmapi/src/cmapi/core/identity/checks.py +++ b/cmapi/src/cmapi/core/identity/checks.py @@ -10,6 +10,9 @@ (identity.automationRoles, default [cmapi-onboarding]). An AI agent or a script signs in as the service client cmapi-automation, with client credentials. An automation caller may also send onBehalfOf. - Every request records whether it was automated (a service client or an automation account). +- A request a service client sends records the owners of that client (identity.clientOwners, core/identity/owners.py; #789), + whom the approval ledger refuses as approvers unless the rule has selfApproval: true. A step of an operation that a + service client started records that client's owners too: the workflow client sends it, and delegation lowers no check. - Email-valued governed keys (cmapi.net/team-dl) must be an address in one of emailDomains from metadata-keys.yaml. Format only: DLs are never looked up. """ @@ -22,6 +25,11 @@ from cmapi.core.errors import Problem from cmapi.core.identity.claims import Identity, Person, is_reserved from cmapi.core.identity.directory import CachedDirectory, DirectoryProvider +from cmapi.core.identity.owners import OwnerSnapshot + +# What the request's record holds for the approval ledger only: stable identifiers, not part of the public contract. They stay in +# the row and out of every response (public_record). +PRIVATE_RECORD_KEYS = frozenset({"submittedBySub", "clientOwners", "starterClientOwners"}) _LOCAL = re.compile(r"^[A-Za-z0-9!#$%&'*+/=?^_`{|}~.-]+$") @@ -40,6 +48,9 @@ class Requester: person: Identity | Person caller: Identity automated: bool = False + client_owners: OwnerSnapshot | None = None # the owners of the service client that sent it, when it has an entry + # An operation's step, started by a service client with an entry: that client's owners, beside the sender's (#789). + starter_client_owners: OwnerSnapshot | None = None @property def username(self) -> str: @@ -63,9 +74,18 @@ def record(self) -> dict: rec["submittedBySub"] = self.caller.sub if self.caller.kind == "service": rec["submittedByClient"] = self.caller.client_id + if self.client_owners is not None: + rec["clientOwners"] = self.client_owners.record() + if self.starter_client_owners is not None: + rec["starterClientOwners"] = self.starter_client_owners.record() return rec +def public_record(record: dict) -> dict: + """A request's requester record as a response shows it: without PRIVATE_RECORD_KEYS.""" + return {k: v for k, v in record.items() if k not in PRIVATE_RECORD_KEYS} + + def resolve_requester(caller: Identity, on_behalf_of: str | None, directory: DirectoryProvider | CachedDirectory | None, require_employee_id: bool = True, require_on_behalf_of: bool = False, diff --git a/cmapi/src/cmapi/core/identity/keycloak_admin.py b/cmapi/src/cmapi/core/identity/keycloak_admin.py index a6f1efa3..ba279fad 100644 --- a/cmapi/src/cmapi/core/identity/keycloak_admin.py +++ b/cmapi/src/cmapi/core/identity/keycloak_admin.py @@ -99,9 +99,11 @@ def _users(self, params: dict[str, str]) -> list[dict[str, Any]]: if status == 401: # token revoked early: one fresh try self._token = None status, body = self._call("GET", url, {"Authorization": f"Bearer {self._bearer()}"}, None) - if status >= 500 or status in (401, 403): + # Keycloak answers a search that finds nobody with 200 and an empty list. Any other status (a gateway's 502, a 429, + # a 404 for a wrong realm) is no answer about the user, so it is never read as "no such user" (#789, #798). + if status != 200: raise DirectoryUnavailable(f"admin API answered {status}") - return body if status == 200 else [] + return body def _person(self, u: dict[str, Any]) -> Person: attrs = u.get("attributes") or {} diff --git a/cmapi/src/cmapi/core/identity/owners.py b/cmapi/src/cmapi/core/identity/owners.py new file mode 100644 index 00000000..866d4a5d --- /dev/null +++ b/cmapi/src/cmapi/core/identity/owners.py @@ -0,0 +1,151 @@ +"""instance.yaml `identity.clientOwners`: the people who own each service client (#789). + +docs/01, "Approval of record": an approver is "not an owner of the svc client that asked". Keycloak keeps no owner of a +client (its ClientRepresentation has only free `attributes`), so the instance says who they are, in Git with the rest of its +configuration (the owner's decision on #789, 2026-12-01): + + identity: + clientOwners: + svc-payments-ci: [jane, /cmapi/team-payments] + +An entry is a username, or a Keycloak group by its full path, as the token's `groups` claim carries it (docs/15). A group +starts with `/`; a username never holds one, because Keycloak's default user profile refuses `/` in a username +(UsernameProhibitedCharactersValidator). An empty list says that the client has no owners. + +Owners are compared by `sub`, as every other self-approval check is (core/approvals.py). A username is resolved to its `sub` +through the DirectoryProvider when the client files a request, and the request stores the result with `submittedBySub` +(Requester.record), as it stores its requirement and group path: a later change of the configuration does not move who may +decide a request already filed. A group is compared with the approver's token when they decide. + +A username the directory does not know is never dropped: the request is refused with 500 internal-error, since the fault is +the instance's configuration and not the request (OWASP Secure Coding Practices, Access control: "Access controls should fail +securely"; "Deny all access if the application cannot access its security configuration information"). The log line +`client_owner_unknown`, with the answer's request ID, names the client and the username; the API's start warns of it first +(main.py, `check_client_owners`). This module only reads and resolves; the pipeline and the start log and answer. +""" +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from typing import Any, Mapping + +from cmapi.core.identity.directory import CachedDirectory, DirectoryProvider, DirectoryUnavailable + +# White space and control characters: no Keycloak username holds them (the default user profile's +# username-prohibited-characters refuses \s and \p{Cntrl}), and a group path is checked for control characters only, since a +# Keycloak group's name may hold a space. +_SPACE_OR_CONTROL = re.compile(r"[\s\x00-\x1f\x7f]") +_CONTROL = re.compile(r"[\x00-\x1f\x7f]") + + +def is_group(entry: str) -> bool: + return entry.startswith("/") + + +@dataclass(frozen=True) +class OwnerSnapshot: + """The owners of the client that filed one request, as they were when it filed it.""" + client: str + subs: tuple[str, ...] + groups: tuple[str, ...] + + def record(self) -> dict[str, Any]: + return {"client": self.client, "subs": list(self.subs), "groups": list(self.groups)} + + +class OwnerUnknown(LookupError): + """identity.clientOwners names a username that the directory does not know, or there is no directory to ask.""" + + def __init__(self, client_id: str, username: str, directory: bool): + super().__init__(f"identity.clientOwners.{client_id} names {username}, " + + ("who is not a user of the directory" if directory else "and cmapi has no directory")) + self.client_id, self.username, self.directory = client_id, username, directory + + +@dataclass(frozen=True) +class StartFindings: + """What check_at_start found: clients it knows of without an entry, usernames the directory does not know, and why it + could not ask the directory, if it could not.""" + unowned: list[str] + unknown: list[OwnerUnknown] + unchecked: str | None = None + + +@dataclass(frozen=True) +class ClientOwners: + by_client: Mapping[str, tuple[str, ...]] = field(default_factory=dict) + + @classmethod + def parse(cls, raw: Any) -> tuple["ClientOwners", list[str]]: + """The setting and the problems that stop the start; an absent setting is no entry for any client.""" + where = "instance.identity.clientOwners" + if raw is None: + return cls(), [] + if not isinstance(raw, Mapping): + return cls(), [f"{where} must be a mapping of a client ID to a list of usernames and group paths"] + problems: list[str] = [] + owners: dict[str, tuple[str, ...]] = {} + for client, entries in raw.items(): + if not isinstance(client, str) or not client.strip() or client != client.strip(): + problems.append(f"{where}: {client!r} is not a client ID") + continue + if not isinstance(entries, list): + problems.append(f"{where}.{client} must be a list of usernames and group paths") + continue + for e in entries: + if not isinstance(e, str) or not e: + problems.append(f"{where}.{client}: {e!r} is not a username or a group path") + elif is_group(e) and (len(e) == 1 or _CONTROL.search(e)): + problems.append(f"{where}.{client}: {e!r} is not a Keycloak group path such as /cmapi/team-payments") + elif not is_group(e) and _SPACE_OR_CONTROL.search(e): + problems.append(f"{where}.{client}: {e!r} is not a username: a username holds no white space, and a " + "group path starts with /") + owners[client] = tuple(e for e in entries if isinstance(e, str)) + return cls(owners), problems + + def configured(self, client_id: str) -> bool: + return client_id in self.by_client + + def usernames(self) -> dict[str, list[str]]: + """client ID -> the usernames of its entry, for each client whose entry names one.""" + named = {c: [e for e in entries if not is_group(e)] for c, entries in self.by_client.items()} + return {c: names for c, names in named.items() if names} + + def resolve(self, client_id: str, directory: DirectoryProvider | CachedDirectory | None) -> OwnerSnapshot | None: + """The owners of the client now, each username as its `sub`; None when the client has no entry. + + Raises DirectoryUnavailable when the directory cannot be reached and has no cached answer (CachedDirectory), and + OwnerUnknown for a username it does not know, or when there is no directory: the request is refused, never filed + without that owner.""" + entries = self.by_client.get(client_id) + if entries is None: + return None + subs: list[str] = [] + for name in (e for e in entries if not is_group(e)): + person = directory.get_user(name) if directory is not None else None + if person is None or not person.sub: + raise OwnerUnknown(client_id, name, directory is not None) + subs.append(person.sub) + return OwnerSnapshot(client_id, tuple(dict.fromkeys(subs)), tuple(dict.fromkeys(e for e in entries if is_group(e)))) + + +def check_at_start(owners: ClientOwners, directory: DirectoryProvider | CachedDirectory | None, + known_clients: set[str]) -> StartFindings: + """What the API's start can know about identity.clientOwners (the owner's decision on #789); main.py logs it. + + A service client is known before it calls only when the configuration names it (an auto-approval policy's + requester.clients) or it has filed a request for another person before (change_requests): each of them without an entry + is `unowned`. Any other client is named the first time it sends onBehalfOf (Pipeline.with_client_owners). Each username + is looked up once: `unknown` holds each one the directory does not know, whose client's requests are refused until the + entry is fixed; `unchecked` says why the directory could not be asked, and the check then waits for the first request.""" + unowned = sorted(c for c in known_clients if not owners.configured(c)) + unknown: list[OwnerUnknown] = [] + for client_id, names in sorted(owners.usernames().items()): + for name in names: + try: + person = directory.get_user(name) if directory is not None else None + except DirectoryUnavailable as exc: + return StartFindings(unowned, unknown, str(exc)[:200]) + if person is None or not person.sub: + unknown.append(OwnerUnknown(client_id, name, directory is not None)) + return StartFindings(unowned, unknown) diff --git a/cmapi/src/cmapi/core/pipeline.py b/cmapi/src/cmapi/core/pipeline.py index f4e7e024..6bf5bf8f 100644 --- a/cmapi/src/cmapi/core/pipeline.py +++ b/cmapi/src/cmapi/core/pipeline.py @@ -30,12 +30,14 @@ from cmapi.core.config import InstanceConfig, environment_not_served from cmapi.core.db.models import ChangeRequestRow from cmapi.core.db.repo import JobRepo, RequestRepo, fingerprint, hold_term, requirement_to_json +from cmapi.core.docs import PROBLEMS from cmapi.core.errors import Problem from cmapi.core.etag import if_match_tags from cmapi.core.git.base import GitUnavailable, HostGitProvider, NotUtf8 -from cmapi.core.identity.checks import Requester, resolve_requester +from cmapi.core.identity.checks import Requester, public_record, resolve_requester from cmapi.core.identity.claims import EXPIRY_NAME, Identity, label_value_of -from cmapi.core.identity.directory import CachedDirectory +from cmapi.core.identity.directory import CachedDirectory, DirectoryUnavailable +from cmapi.core.identity.owners import OwnerUnknown from cmapi.core.lifecycle import Event as E from cmapi.core.naming import check_name, check_not_unmanaged, is_label from cmapi.core.observability import (AUTO_APPROVALS, AUTO_FALLBACKS, CHANGE_REQUESTS, ENV_NOT_SERVED, PLUGIN_DISABLED, @@ -91,7 +93,7 @@ def hash(self) -> str: def view(self) -> dict[str, Any]: r = self.requirement return {"changes": self.changes, "planHash": self.hash, "etag": self.etag, - "requester": {k: v for k, v in self.requester.record().items() if k != "submittedBySub"}, + "requester": public_record(self.requester.record()), "capacity": {"status": self.capacity.status, "fresh": self.capacity.fresh, "bindingResource": self.capacity.binding_resource, **dict(self.capacity.detail)}, "approval": approval_view(r, None), @@ -188,12 +190,43 @@ def __init__(self, cfg: InstanceConfig, registry: ClusterRegistry, git: HostGitP self.renderer = ManifestRenderer(cfg.tiers, cfg.metadata) self.auto_paused = auto_paused self.identity = cfg.raw_instance["instance"].get("identity", {}) + self._unowned_named: set[str] = set() # the clients without owners that this process has logged (#789) # ---- who def requester_for(self, who: Identity, on_behalf_of: str | None) -> Requester: - return resolve_requester(who, on_behalf_of, self.directory, self.identity.get("requireEmployeeId", True), - self.identity.get("requireOnBehalfOf", False), - self.identity.get("automationRoles", ["cmapi-onboarding"])) + try: + requester = resolve_requester(who, on_behalf_of, self.directory, self.identity.get("requireEmployeeId", True), + self.identity.get("requireOnBehalfOf", False), + self.identity.get("automationRoles", ["cmapi-onboarding"])) + except DirectoryUnavailable as exc: + raise directory_unavailable(exc) from exc + return self.with_client_owners(requester, warn=bool(on_behalf_of)) + + def with_client_owners(self, requester: Requester, *, warn: bool = False) -> Requester: + """The requester with the owners of the service client that sends it (identity.clientOwners, #789), resolved now and + stored with the request: the ledger refuses them as approvers unless the rule has selfApproval: true. + + warn: a client without an entry that names another person (onBehalfOf) keeps the rule from before #789, no owners, + and is logged once in each process (`client_without_owners`), as the start logs the clients it knows of + (main.py, check_client_owners).""" + caller = requester.caller + if caller.kind != "service": + return requester + if not self.cfg.client_owners.configured(caller.client_id): + if warn and caller.client_id not in self._unowned_named: + self._unowned_named.add(caller.client_id) + log.warning("client_without_owners", client_ids=[caller.client_id], detail=UNOWNED_DETAIL) + return requester + try: + owners = self.cfg.client_owners.resolve(caller.client_id, self.directory) + except DirectoryUnavailable as exc: + raise directory_unavailable(exc) from exc + except OwnerUnknown as exc: + # The instance's configuration is at fault, not the request: internal-error, and the cause in this log line, + # which carries the answer's request ID (OWASP Secure Coding Practices: "Access controls should fail securely"). + log.error("client_owner_unknown", client_id=exc.client_id, username=exc.username, directory=exc.directory) + raise Problem(500, "internal-error", PROBLEMS["internal-error"][1]) from exc + return replace(requester, client_owners=owners) def environment_of(self, cluster_id: str) -> str: st = self.registry.get(cluster_id) @@ -296,7 +329,12 @@ def _plan_namespace(self, who: Identity, cluster_id: str, body: Mapping[str, Any check_name(ns, self.reserved) check_not_unmanaged(ns, cache.namespace(ns)) direct = self.requester_for(who, body.get("onBehalfOf")) - requester = Requester(direct.person, submitted_by, automated=True) if submitted_by else direct + requester = direct + if submitted_by: + # The starter's own request would refuse the owners of the starter's client, so the step's request refuses + # them too, beside the owners of the client that sends it: delegation lowers no check (ApprovalRules.decide). + requester = self.with_client_owners(Requester(direct.person, submitted_by, automated=True, + starter_client_owners=direct.client_owners)) if action == "create": # The label is only written at create; refuse here, not as a 422 from the API server at apply. The refusal is # explicit: a ValueError that escapes a route is the service's fault, 500 internal-error (#648). @@ -1123,6 +1161,15 @@ def refuse_held_keys(ns: str, added: Mapping[str, Mapping[str, str]], live: Mapp keys=held) +UNOWNED_DETAIL = ("no entry in identity.clientOwners: no person is refused as the owner of these clients; any other client is " + "named when it first sends onBehalfOf") + + +def directory_unavailable(exc: DirectoryUnavailable) -> Problem: + """Keycloak down and the name not cached: 503 idp-unavailable, the answer GET /directory/users gives.""" + return Problem(503, "idp-unavailable", f"Directory unavailable: {exc}", extra={"retryAfter": 30}) + + def count_refusal(problem: Problem) -> None: """cmapi_validation_failures_total{source}: one for each error of a policy-violation, and one for each other refusal of CMAPI_REFUSALS. Before #302 only the validator's errors were counted, and cmapi's own refusals, raised first, were not.""" diff --git a/cmapi/src/cmapi/core/views.py b/cmapi/src/cmapi/core/views.py index a0b37675..c8e98570 100644 --- a/cmapi/src/cmapi/core/views.py +++ b/cmapi/src/cmapi/core/views.py @@ -5,6 +5,7 @@ from cmapi.core.db.models import ChangeRequestRow from cmapi.core.db.repo import RequestRepo, requirement_from_json +from cmapi.core.identity.checks import public_record from cmapi.core.pipeline import approval_view from cmapi.core.render.manifests import diff_files @@ -22,9 +23,9 @@ def request_view(repo: RequestRepo, row: ChangeRequestRow, *, with_events: bool "requestId": row.request_id, "instance": row.instance, "clusterId": row.cluster_id, "namespace": row.namespace, "env": row.env, "plugin": row.plugin, "action": row.action, "reason": row.reason, "justification": row.justification, "status": row.status, "planHash": row.plan_hash, "baseSha": row.base_sha, - # submittedBySub is a stable identifier the ledger needs (self-approval through onBehalfOf); it is not - # part of the public contract, so it stays in the row and out of the response. - "approval": approval_view(req, ledger), "requester": {k: v for k, v in row.requester.items() if k != "submittedBySub"}, + # submittedBySub and clientOwners are what the ledger needs (self-approval through onBehalfOf, #789); they are not + # part of the public contract, so they stay in the row and out of the response. + "approval": approval_view(req, ledger), "requester": public_record(row.requester), "pr": None if not pr else {"number": pr["number"], "url": pr["url"], "branch": pr["branch"], "head": pr["head"][:8]}, "mergeSha": row.merge_sha and row.merge_sha[:8], "files": diff_files(plan.get("prev", {}), plan.get("files", {})), diff --git a/cmapi/src/cmapi/main.py b/cmapi/src/cmapi/main.py index 740d871d..ceec2a9d 100644 --- a/cmapi/src/cmapi/main.py +++ b/cmapi/src/cmapi/main.py @@ -19,6 +19,7 @@ from fastapi.responses import HTMLResponse, JSONResponse, Response from fastapi.routing import APIRoute from fastapi.staticfiles import StaticFiles +from sqlalchemy.exc import SQLAlchemyError from starlette.datastructures import Headers from starlette.exceptions import HTTPException from starlette.requests import ClientDisconnect @@ -31,6 +32,8 @@ from cmapi.core.bodylimit import RequestBodyLimitMiddleware from cmapi.core.config import InstanceConfig from cmapi.core.context import AppContext, build_context +from cmapi.core.db.repo import RequestRepo +from cmapi.core.identity.owners import check_at_start from cmapi.core.changelog import changelog_html from cmapi.core.cors import EXPOSED_HEADERS, MAX_AGE, METHODS, REQUEST_HEADERS, OriginVaryCORSMiddleware, allowed_origins from cmapi.core.docs import PROBLEMS, URL_VARIABLE, InstanceFacts, api_routes, build_openapi, check_documented, plugin_routers @@ -41,6 +44,7 @@ from cmapi.core.models import NUL_REFUSED, SURROGATE_CODE from cmapi.core.problem_docs import problem_html, problems_index_html from cmapi.core.observability import configure_logging, instrument, log, start_metrics +from cmapi.core.pipeline import UNOWNED_DETAIL from cmapi.core.tiers import TierError from cmapi.routers import EXAMPLE_CLUSTER, admin, health, me, operations, rate_limit, requests, webhooks from cmapi.settings import Settings, settings @@ -172,6 +176,25 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: await self.app(scope, receive, send) +def check_client_owners(ctx: AppContext) -> None: + """The start's warnings about identity.clientOwners (#789): the service clients it knows of without an entry, and each + username the directory does not know (core/identity/owners.py, check_at_start). A database that cannot be read leaves + the clients that filed before out of the warning, and the start goes on.""" + known = set(ctx.cfg.approvals.requester_clients()) + try: + with ctx.db.session() as s: + known |= set(RequestRepo(s).clients_that_filed_for_others()) + except SQLAlchemyError as exc: + log.warning("client_owners_unchecked", error=f"{type(exc).__name__}: {str(exc)[:200]}") + found = check_at_start(ctx.cfg.client_owners, ctx.directory, known) + if found.unowned: + log.warning("client_without_owners", client_ids=found.unowned, detail=UNOWNED_DETAIL) + for unknown in found.unknown: + log.error("client_owner_unknown", client_id=unknown.client_id, username=unknown.username, directory=unknown.directory) + if found.unchecked: + log.warning("client_owners_unchecked", error=found.unchecked) + + def instance_facts(cfg: InstanceConfig, cluster_environments: Mapping[str, str] | None = None) -> InstanceFacts: """The create example's target and the expiry rules of the API document (#479). cluster_environments: the writable clusters of clusters.yaml. The target is CRC when it is one of them, else the first of them, with its environment, @@ -245,6 +268,7 @@ async def lifespan(app: FastAPI): log.info("startup", instance=ctx.cfg.name, issuer=issuer, audience=ctx.audience, version=__version__, commit=os.environ.get("CMAPI_GIT_COMMIT", "unknown"), clusters=ctx.registry.status_map(), plugins=list(ctx.cfg.plugins.enabled), plugins_file=ctx.cfg.plugins.configured) + check_client_owners(ctx) yield ctx.shutdown() diff --git a/cmapi/src/cmapi/tools/reference_instance/instance.yaml b/cmapi/src/cmapi/tools/reference_instance/instance.yaml index 59c06ae5..0d4be1da 100644 --- a/cmapi/src/cmapi/tools/reference_instance/instance.yaml +++ b/cmapi/src/cmapi/tools/reference_instance/instance.yaml @@ -27,6 +27,7 @@ instance: requireOnBehalfOf: false # bots (service-account clients) may request in their own name automationRoles: [cmapi-onboarding] # callers with these roles need no employee ID (cmapi-automation) groupPath: /cmapi/app-cmapi-rbac-{name} # the token's group for an approving group in approval-rules.yaml; a site with its own directory sets its own (docs/11) + # clientOwners: {svc-payments-ci: [jane, /cmapi/team-payments]} # who owns a service client: never decides what it sends (docs/18, #789) # email domains for the team DL: emailDomains in cluster-configs/policies/metadata-keys.yaml git: repository: cmapi/cluster-configs-test diff --git a/cmapi/tests/core/test_client_owners_789.py b/cmapi/tests/core/test_client_owners_789.py new file mode 100644 index 00000000..4d8e0aa1 --- /dev/null +++ b/cmapi/tests/core/test_client_owners_789.py @@ -0,0 +1,138 @@ +"""#789: instance.yaml identity.clientOwners, read at the start, and the ledger's refusal of a client's owners.""" +import shutil + +import pytest + +from cmapi.core.approvals import ApprovalLedger, Requirement, Slot +from cmapi.core.config import ConfigError, load_instance +from cmapi.core.errors import Problem +from cmapi.core.identity.checks import Requester, public_record, resolve_requester +from cmapi.core.identity.claims import Person +from cmapi.core.identity.directory import DirectoryUnavailable, InMemoryDirectory +from cmapi.core.identity.keycloak_admin import KeycloakAdminDirectory +from cmapi.core.identity.owners import ClientOwners, OwnerSnapshot, OwnerUnknown, check_at_start +from conftest import EX, person + +PLATFORM = "/cmapi/app-cmapi-rbac-approver-platform" +APPROVER = dict(roles={"cmapi-approver"}) + + +def ledger(**owners) -> ApprovalLedger: + requirement = Requirement(rule="dev/create", slots=(Slot("approver-platform", 1, "create"),), self_approval=False, + timeout_hours=24, reasons=()) + return ApprovalLedger(requirement, requester_sub="sub-jane", **owners) + + +@pytest.mark.parametrize("raw,problem", [ + ("svc-ci", "must be a mapping"), + ({"svc-ci": "jane"}, "svc-ci must be a list"), + ({"svc-ci": [""]}, "'' is not a username or a group path"), + ({"svc-ci": [7]}, "7 is not a username or a group path"), + ({"svc-ci": ["jane doe"]}, "'jane doe' is not a username"), + ({"svc-ci": ["/"]}, "'/' is not a Keycloak group path"), + ({"svc-ci": ["/team\x00"]}, "is not a Keycloak group path"), + ({" svc-ci": ["jane"]}, "' svc-ci' is not a client ID"), +]) +def test_a_value_that_names_no_owner_stops_the_start(raw, problem): + _, problems = ClientOwners.parse(raw) + assert len(problems) == 1 and problem in problems[0], problems + + +def test_usernames_groups_and_an_empty_entry_are_read(): + owners, problems = ClientOwners.parse({"svc-ci": ["jane", "/cmapi/Team Payments"], "svc-none": []}) + assert problems == [] + assert owners.configured("svc-none") and not owners.configured("svc-other") + assert owners.usernames() == {"svc-ci": ["jane"]} + assert ClientOwners.parse(None) == (ClientOwners(), []) + + +def test_resolve_gives_each_username_as_its_sub_and_keeps_the_groups(): + owners, _ = ClientOwners.parse({"svc-ci": ["jane", "jane", "/g"]}) + directory = InMemoryDirectory([Person("jane", "jane@ephico2real.com", sub="sub-jane")]) + assert owners.resolve("svc-ci", directory) == OwnerSnapshot("svc-ci", ("sub-jane",), ("/g",)) + assert owners.resolve("svc-other", directory) is None + + +def test_an_unknown_username_or_no_directory_is_refused_never_dropped(): + owners, _ = ClientOwners.parse({"svc-ci": ["jane"]}) + for directory in (InMemoryDirectory([]), None): + with pytest.raises(OwnerUnknown) as e: + owners.resolve("svc-ci", directory) + assert (e.value.client_id, e.value.username, e.value.directory) == ("svc-ci", "jane", directory is not None) + down = InMemoryDirectory([]) + down.down = True + with pytest.raises(DirectoryUnavailable): + owners.resolve("svc-ci", down) + + +def test_the_start_check_names_unowned_clients_and_unknown_usernames(): + owners, _ = ClientOwners.parse({"svc-ci": ["jane", "jnae", "/g"], "svc-none": []}) + directory = InMemoryDirectory([Person("jane", "jane@ephico2real.com", sub="sub-jane")]) + found = check_at_start(owners, directory, {"svc-ci", "svc-none", "svc-bot"}) + assert found.unowned == ["svc-bot"] and [u.username for u in found.unknown] == ["jnae"] and found.unchecked is None + directory.down = True + assert check_at_start(owners, directory, set()).unchecked == "directory down" + + +def test_the_instance_file_is_read_and_a_bad_value_stops_the_start(tmp_path): + d = tmp_path / "nonprod" + shutil.copytree(EX / "instances" / "nonprod", d) + keys = EX / "cluster-configs/policies/metadata-keys.yaml" + lines = (d / "instance.yaml").read_text().splitlines(keepends=True) + at = next(i for i, line in enumerate(lines) if line.startswith(" groupPath: ")) + good = lines[:at + 1] + [" clientOwners: {svc-payments-ci: [jane, /cmapi/team-payments]}\n"] + lines[at + 1:] + (d / "instance.yaml").write_text("".join(good)) + assert load_instance(d, keys).client_owners.by_client == {"svc-payments-ci": ("jane", "/cmapi/team-payments")} + bad = lines[:at + 1] + [" clientOwners: {svc-payments-ci: [jane doe]}\n"] + lines[at + 1:] + (d / "instance.yaml").write_text("".join(bad)) + with pytest.raises(ConfigError, match="identity.clientOwners.svc-payments-ci: 'jane doe' is not a username"): + load_instance(d, keys) + + +def test_the_ledger_refuses_an_owner_by_sub_or_by_a_group_of_the_token(): + by_group = person("bob", groups={PLATFORM, "/cmapi/team-payments"}, **APPROVER) + by_sub = person("kim", groups={PLATFORM}, **APPROVER) + led = ledger(client_owner_subs=frozenset({"sub-kim"}), client_owner_groups=frozenset({"/cmapi/team-payments"})) + for who in (by_group, by_sub): + for decide in (led.approve, lambda w: led.reject(w)): + with pytest.raises(Problem) as e: + decide(who) + assert e.value.code == "self-approval" + assert led.approve(person("amy", groups={PLATFORM}, **APPROVER)) + + +def test_the_record_stores_the_owners_and_the_response_leaves_them_out(): + directory = InMemoryDirectory([Person("jane", "jane@ephico2real.com", sub="sub-jane")]) + svc = person("svc-ci", kind="service", client="svc-ci") + requester = resolve_requester(svc, "jane", directory) + owned = type(requester)(requester.person, requester.caller, requester.automated, + OwnerSnapshot("svc-ci", ("sub-kim",), ("/g",))) + record = owned.record() + assert record["clientOwners"] == {"client": "svc-ci", "subs": ["sub-kim"], "groups": ["/g"]} + assert "clientOwners" not in requester.record() + assert set(public_record(record)) == {"requester", "automated", "submittedBy", "submittedByClient"} + + +def test_an_operations_step_records_its_starters_owners_and_the_response_leaves_them_out(): + """A step of an operation that a service client started: the record holds the owners of both clients (#789).""" + starter = person("svc-ci", kind="service", client="svc-ci") + workflows = person("svc-cmapi-workflows", kind="service", client="svc-cmapi-workflows") + record = Requester(starter, workflows, True, OwnerSnapshot("svc-cmapi-workflows", (), ("/ops",)), + OwnerSnapshot("svc-ci", ("sub-kim",), ())).record() + assert record["clientOwners"] == {"client": "svc-cmapi-workflows", "subs": [], "groups": ["/ops"]} + assert record["starterClientOwners"] == {"client": "svc-ci", "subs": ["sub-kim"], "groups": []} + assert set(public_record(record)) == {"requester", "automated", "submittedBy", "submittedByClient"} + + +@pytest.mark.parametrize("status", [302, 400, 404, 429, 502]) +def test_an_answer_that_is_not_200_is_never_read_as_no_such_user(status): + """Keycloak answers a search that finds nobody with 200 and []. Before the fix a 302, 400, 404 or 429 was read as an + empty list: the owner was `client_owner_unknown` (500) and an onBehalfOf name `unknown-user` (422), with Keycloak + having said nothing about either.""" + def http(method, url, headers, form): + return (200, {"access_token": "t", "expires_in": 300}) if url.endswith("/token") else (status, None) + keycloak = KeycloakAdminDirectory("https://sso.ephico2real.com", "ephico2real", "cmapi-directory", "s", http) + owners, _ = ClientOwners.parse({"svc-ci": ["kim"]}) + with pytest.raises(DirectoryUnavailable, match=str(status)): + owners.resolve("svc-ci", keycloak) + assert check_at_start(owners, keycloak, set()).unchecked == f"admin API answered {status}" diff --git a/cmapi/tests/service/test_client_owners_789.py b/cmapi/tests/service/test_client_owners_789.py new file mode 100644 index 00000000..ab7c0010 --- /dev/null +++ b/cmapi/tests/service/test_client_owners_789.py @@ -0,0 +1,274 @@ +"""#789: an owner of a service client cannot approve or reject what that client filed. + +docs/01, "Approval of record": the approver is "not an owner of the svc client that asked". instance.yaml +`identity.clientOwners` names the owners (the owner's decision on #789, 2026-12-01): a username, compared by the `sub` that the +directory gives when the client files, or a group of the approver's token. Before the fix `RequestRepo.ledger` gave the +ledger no owners, so an owner in an approving group approved (200) and rejected (200) what the client filed for jane. +""" +from __future__ import annotations + +import shutil + +import httpx +import pytest +import structlog +from sqlalchemy import func, select + +import cmapi.core.pipeline as pipeline_module +import cmapi.main as main_module +from cmapi.core.configfile import ConfigError +from cmapi.core.db.models import ChangeRequestRow +from cmapi.core.context import _http_for_directory +from cmapi.core.db.repo import JobRepo, RequestRepo +from cmapi.core.identity.claims import Identity, Person +from cmapi.core.identity.directory import CachedDirectory, InMemoryDirectory +from cmapi.core.identity.keycloak_admin import KeycloakAdminDirectory +from cmapi.core.identity.owners import ClientOwners +from cmapi.core.operations import WORKFLOWS_CLIENT +from cmapi.main import check_client_owners +from conftest import build_world +from test_flow import auth +from test_reject_decision_779_780 import BIG, PLATFORM, pending, recorded, status +from test_review_c_authz import strict + +SVC_USER = "service-account-svc-payments-ci" +SVC = dict(roles=["cmapi-requester"], client="svc-payments-ci", employee_id=None) +TEAM = "/cmapi/team-payments" +KIM = dict(roles=["cmapi-approver"], groups=[PLATFORM], sub="sub-kim") # an owner of svc-payments-ci by username +BOB = dict(roles=["cmapi-approver"], groups=[PLATFORM, TEAM], sub="sub-bob") # an owner by the group TEAM +AMY = dict(roles=["cmapi-approver"], groups=[PLATFORM], sub="sub-amy") # an approver who owns nothing + + +def people(ctx, *, down: bool = False) -> InMemoryDirectory: + directory = InMemoryDirectory([Person(username="jane", email="jane@ephico2real.com", sub="sub-jane"), + Person(username="kim", email="kim@ephico2real.com", sub="sub-kim")]) + directory.down = down + ctx.directory = ctx.pipeline.directory = CachedDirectory(directory) + return directory + + +def owned(ctx, *entries: str) -> None: + ctx.cfg.client_owners, problems = ClientOwners.parse({"svc-payments-ci": list(entries)}) + assert problems == [] + + +def for_jane(client, keys, namespace: str) -> str: + """svc-payments-ci files a request for jane (onBehalfOf) that needs one approval of approver-platform.""" + return pending(client, keys, namespace=namespace, who=(SVC_USER, SVC), onBehalfOf="jane") + + +def stored(ctx, rid: str) -> dict: + with ctx.db.session() as s: + return s.scalars(select(ChangeRequestRow.requester).where(ChangeRequestRow.request_id == rid)).one() + + +@pytest.fixture +def owner_log(monkeypatch) -> list[dict]: + """What pipeline.py and main.py log, on a logger of their own (the reason is test_jwks_skip_bad_key_656.auth_log's).""" + capture = structlog.testing.LogCapture() + logger = structlog.wrap_logger(structlog.ReturnLogger(), wrapper_class=structlog.BoundLogger, processors=[capture], + cache_logger_on_first_use=False) + monkeypatch.setattr(main_module, "log", logger) + monkeypatch.setattr(pipeline_module, "log", logger) + return capture.entries + + +DECISIONS = {"approve": ({}, "approved"), "reject": ({"comment": "no"}, "rejected")} + + +@pytest.mark.parametrize("verb", list(DECISIONS)) +@pytest.mark.parametrize("owner,name,who", [("kim", "kim", KIM), (TEAM, "bob", BOB)], ids=["by-username", "by-group"]) +def test_an_owner_of_the_client_cannot_approve_or_reject_what_it_filed_for_someone(world, owner, name, who, verb): + """#789's proof. Before the fix: :approve answered 200 (the request became approved), and :reject 200 (rejected).""" + client, ctx, git, kube, validator, keys = world + strict(ctx) + people(ctx) + owned(ctx, owner) + rid = for_jane(client, keys, "payments-batch") + assert stored(ctx, rid)["clientOwners"] == {"client": "svc-payments-ci", "subs": ["sub-kim"] if owner == "kim" else [], + "groups": [TEAM] if owner == TEAM else []} + body, decided = DECISIONS[verb] + before = recorded(ctx, rid) + r = client.post(f"/api/v1/requests/{rid}:{verb}", json=body, headers=auth(keys, name, **who)) + assert (r.status_code, r.json().get("code")) == (409, "self-approval"), r.text + assert "client owner" in r.json()["detail"] + assert recorded(ctx, rid) == before and status(client, keys, rid) == "pending_approval" + # The refusal is the owner's only: an approver of the same group who owns nothing decides it. + r = client.post(f"/api/v1/requests/{rid}:{verb}", json=body, headers=auth(keys, "amy", **AMY)) + assert r.json()["status"] == decided, r.text + + +def test_the_owners_stay_out_of_every_response(world): + """clientOwners is the ledger's, like submittedBySub: neither the plan's answer nor the request's view shows it.""" + client, ctx, git, kube, validator, keys = world + people(ctx) + owned(ctx, "kim", TEAM) + r = client.post("/api/v1/clusters/CRC/namespaces", json={**BIG, "onBehalfOf": "jane"}, headers=auth(keys, SVC_USER, **SVC)) + assert r.status_code == 202, r.text + rid = r.json()["requestId"] + assert "clientOwners" in stored(ctx, rid) and "submittedBySub" in stored(ctx, rid) + preview = client.post("/api/v1/clusters/CRC/namespaces?dryRun=true", + json={**BIG, "namespace": "payments-preview", "onBehalfOf": "jane"}, + headers=auth(keys, SVC_USER, **SVC)) + assert preview.status_code == 200, preview.text + for body in (preview.json(), r.json(), client.get(f"/api/v1/requests/{rid}", headers=auth(keys, "amy", **AMY)).json()): + assert set(body["requester"]) == {"requester", "automated", "submittedBy", "submittedByClient"}, body["requester"] + + +def test_an_owner_decides_where_the_rule_allows_self_approval(world): + """selfApproval: true lets the requester and the submitter decide; it lets the client's owners decide too.""" + client, ctx, git, kube, validator, keys = world + people(ctx) + owned(ctx, "kim") + rid = for_jane(client, keys, "payments-batch") + r = client.post(f"/api/v1/requests/{rid}:approve", json={}, headers=auth(keys, "kim", **KIM)) + assert r.status_code == 200 and r.json()["status"] == "approved", r.text + + +def test_the_owners_are_those_of_the_time_it_was_filed(world): + """A change of identity.clientOwners after a request was filed does not move who may decide it: the owners are stored.""" + client, ctx, git, kube, validator, keys = world + strict(ctx) + people(ctx) + owned(ctx, "kim") + rid = for_jane(client, keys, "payments-batch") + owned(ctx) # the entry emptied after the filing + r = client.post(f"/api/v1/requests/{rid}:approve", json={}, headers=auth(keys, "kim", **KIM)) + assert (r.status_code, r.json().get("code")) == (409, "self-approval"), r.text + + +def test_a_username_the_directory_does_not_know_refuses_the_request(world, owner_log): + """An owner that cannot be resolved is never dropped: 500 internal-error, nothing filed, and the log names it.""" + client, ctx, git, kube, validator, keys = world + people(ctx) + owned(ctx, "kim", "kjm") + r = client.post("/api/v1/clusters/CRC/namespaces", json={**BIG, "onBehalfOf": "jane"}, headers=auth(keys, SVC_USER, **SVC)) + assert (r.status_code, r.json().get("code")) == (500, "internal-error"), r.text + assert "kjm" not in r.text + with ctx.db.session() as s: + assert s.scalar(select(func.count()).select_from(ChangeRequestRow)) == 0 + assert [e for e in owner_log if e["event"] == "client_owner_unknown"] == [ + {"event": "client_owner_unknown", "log_level": "error", "client_id": "svc-payments-ci", "username": "kjm", + "directory": True}] + + +def test_a_directory_that_cannot_be_reached_is_idp_unavailable(world): + """Keycloak down and the name not cached: 503 idp-unavailable with retryAfter, for an owner and for onBehalfOf alike. + Before the fix the onBehalfOf lookup's DirectoryUnavailable escaped every handler: 500 internal-error.""" + client, ctx, git, kube, validator, keys = world + people(ctx, down=True) + for entries, delegation in ((("kim",), {}), ((), {"onBehalfOf": "jane"})): + owned(ctx, *entries) + r = client.post("/api/v1/clusters/CRC/namespaces", json={**BIG, **delegation}, headers=auth(keys, SVC_USER, **SVC)) + assert (r.status_code, r.json().get("code"), r.json().get("retryAfter")) == (503, "idp-unavailable", 30), r.text + + +def test_a_client_without_an_entry_is_allowed_and_named_once(world, owner_log): + """The owner's decision: a client that sends onBehalfOf with no entry keeps the rule from before (no owners) and is + named in a warning, once in each process.""" + client, ctx, git, kube, validator, keys = world + strict(ctx) + people(ctx) + first, second = for_jane(client, keys, "payments-batch"), for_jane(client, keys, "payments-other") + assert "clientOwners" not in stored(ctx, first) + assert client.post(f"/api/v1/requests/{first}:approve", json={}, headers=auth(keys, "kim", **KIM)).status_code == 200 + assert [e["client_ids"] for e in owner_log if e["event"] == "client_without_owners"] == [["svc-payments-ci"]] + assert status(client, keys, second) == "pending_approval" + + +def test_the_start_names_each_known_client_without_an_entry_and_each_unknown_username(world, owner_log): + """At the start cmapi knows the clients that the auto-approval policies name and those that filed for another person + before; each without an entry is named. A username the directory does not know is named as an error.""" + client, ctx, git, kube, validator, keys = world + people(ctx) + svc_ops = dict(roles=["cmapi-requester"], client="svc-ops-bot", employee_id=None) + pending(client, keys, who=("service-account-svc-ops-bot", svc_ops), onBehalfOf="jane") # a client that filed before + owner_log.clear() + check_client_owners(ctx) + assert [(e["event"], e["client_ids"]) for e in owner_log if e["event"] == "client_without_owners"] == [ + ("client_without_owners", ["svc-ops-bot", "svc-payments-ci"])] + owner_log.clear() + ctx.cfg.client_owners, _ = ClientOwners.parse({"svc-payments-ci": ["kim", "kjm"], "svc-ops-bot": [TEAM]}) + check_client_owners(ctx) + assert [(e["event"], e.get("client_id"), e.get("username")) for e in owner_log] == [ + ("client_owner_unknown", "svc-payments-ci", "kjm")] + + +def test_usernames_without_a_directory_stop_the_start(test_config, keys, monkeypatch, tmp_path): + """A username is compared by its sub, which only the directory gives: with no directory the start stops, naming it.""" + d = tmp_path / "config" + shutil.copytree(test_config, d) + lines = (d / "instance.yaml").read_text().splitlines(keepends=True) + at = next(i for i, line in enumerate(lines) if line.startswith(" groupPath: ")) + lines.insert(at + 1, " clientOwners: {svc-payments-ci: [kim, /cmapi/team-payments]}\n") + (d / "instance.yaml").write_text("".join(lines)) + with pytest.raises(ConfigError, match=r"identity.clientOwners names usernames \(svc-payments-ci\)"): + with build_world(d, keys, monkeypatch): + pass + + +@pytest.mark.parametrize("failure", ["connect", "gateway", "rate-limit", "empty"]) +def test_a_keycloak_that_is_down_is_idp_unavailable_through_the_real_http_call(world, monkeypatch, owner_log, failure): + """#798 through the directory that the API pods use (KeycloakAdminDirectory over httpx), where the tests above use + InMemoryDirectory: a refused connection (httpx.ConnectError, which is not an OSError), a gateway's 502 page, a 429 and + an empty 200. The start goes on with `client_owners_unchecked`, and a filing answers 503 idp-unavailable with + Retry-After, for the owner lookup and for onBehalfOf. Before the fix the connection error and the 502 page's JSON error + left the start (the API did not start) and answered 500; the 429 was read as "no such user" (500 and 422).""" + client, ctx, *_, keys = world + owned(ctx, "kim") + + def keycloak(method, url, **kwargs): + if method == "POST": # the token: the outage starts after it + return httpx.Response(200, json={"access_token": "test-token"}) + if failure == "connect": + raise httpx.ConnectError("fixture offline") + if failure == "empty": + return httpx.Response(200, content=b"") + return httpx.Response(429 if failure == "rate-limit" else 502, text="unavailable") + + monkeypatch.setattr(httpx, "request", keycloak) + ctx.pipeline.directory = ctx.directory = CachedDirectory( + KeycloakAdminDirectory("https://directory.invalid", "test", "reader", "", _http_for_directory(True))) + check_client_owners(ctx) + events = [e["event"] for e in owner_log] + assert "client_owners_unchecked" in events and "client_owner_unknown" not in events, owner_log + for delegation in ({}, {"onBehalfOf": "jane"}): + r = client.post("/api/v1/clusters/CRC/namespaces", json={**BIG, **delegation}, headers=auth(keys, SVC_USER, **SVC)) + assert (r.status_code, r.json()["code"], r.json()["retryAfter"], r.headers["Retry-After"]) == ( + 503, "idp-unavailable", 30, "30"), r.text + + +@pytest.mark.parametrize("workflow_owners", [[], [TEAM]], ids=["workflow-client-no-owners", "workflow-client-owned"]) +def test_an_owner_of_the_client_that_started_an_operation_cannot_decide_its_requests(world, workflow_owners): + """An operation's step is sent by svc-cmapi-workflows for whoever started the run (Pipeline.plan_namespace, + submitted_by). When a service client started it, the request holds that client's owners beside the workflow client's, + and the ledger refuses both: the client's own request would refuse kim, so the operation's request does too. + Before the fix the starter's owners were dropped for the sender's: kim approved (200) and rejected (200).""" + client, ctx, *_, keys = world + people(ctx) + strict(ctx) + ctx.cfg.client_owners, problems = ClientOwners.parse({"svc-payments-ci": ["kim"], WORKFLOWS_CLIENT: workflow_owners}) + assert problems == [] + starter = Identity("sub-svc-payments-ci", "svc-payments-ci", "service", "svc-payments-ci", + roles=frozenset({"cmapi-requester"})) + sender = Identity(WORKFLOWS_CLIENT, WORKFLOWS_CLIENT, "service", WORKFLOWS_CLIENT, roles=starter.roles) + plan = ctx.pipeline.plan_namespace(starter, "CRC", BIG, action="create", submitted_by=sender) + assert set(plan.view()["requester"]) == {"requester", "automated", "submittedBy", "submittedByClient"} + with ctx.db.session() as s: + row = ctx.pipeline.submit(sender, plan, RequestRepo(s), JobRepo(s), idempotency_key=None, + body_fingerprint="test", justification="an operation's step") + rid, filed_as = row.request_id, row.status + assert filed_as == "pending_approval" + before = recorded(ctx, rid) + deciders = [("kim", KIM)] + ([("bob", BOB)] if workflow_owners else []) + for name, who in deciders: + for verb, (body, _) in DECISIONS.items(): + r = client.post(f"/api/v1/requests/{rid}:{verb}", json=body, headers=auth(keys, name, **who)) + assert (r.status_code, r.json().get("code")) == (409, "self-approval"), r.text + assert recorded(ctx, rid) == before + record = stored(ctx, rid) + assert record["starterClientOwners"] == {"client": "svc-payments-ci", "subs": ["sub-kim"], "groups": []} + assert record["clientOwners"] == {"client": WORKFLOWS_CLIENT, "subs": [], "groups": workflow_owners} + r = client.post(f"/api/v1/requests/{rid}:approve", json={}, headers=auth(keys, "amy", **AMY)) + assert r.status_code == 200 and r.json()["status"] == "approved", r.text + assert set(r.json()["requester"]) == {"requester", "automated", "submittedBy", "submittedByClient"} diff --git a/docs/14-authorization.md b/docs/14-authorization.md index 2a2e98ac..d5c9bc65 100644 --- a/docs/14-authorization.md +++ b/docs/14-authorization.md @@ -63,7 +63,7 @@ A role is a client role on the client of the instance: `cmapi-nonprod`, `cmapi-s | `audit:export` | | | | | | | yes | | 0 | | `approvals:relay` | | | | | | | | yes | 0 | -`namespaces:protect` is what makes an operator (#366). No route declares it: the routes check it inside, in the environment of the object. It lets a caller set and remove the operator-only labels and annotations of `metadata-keys.yaml` (`cmapi.net/protected` and `do-not-delete`; a requester gets 403), cancel another person's request, and read employee IDs in the directory (`cmapi/src/cmapi/core/authz.py:160-166`, `cmapi/src/cmapi/core/pipeline.py:307`). It is a permission, not a role name: a role of `authz-roles.yaml` that inherits `cmapi-operator` is an operator, and a role that grants it in some environments makes an operator there only. A file that lists `permissions:` for `cmapi-operator` itself must name `namespaces:protect`, or that role is no longer an operator. +`namespaces:protect` is what makes an operator (#366). No route declares it: the routes check it inside, in the environment of the object. It lets a caller set and remove the operator-only labels and annotations of `metadata-keys.yaml` (`cmapi.net/protected` and `do-not-delete`; a requester gets 403), cancel another person's request, and read employee IDs in the directory (`cmapi/src/cmapi/core/authz.py:160-166`, `cmapi/src/cmapi/core/pipeline.py:345`). It is a permission, not a role name: a role of `authz-roles.yaml` that inherits `cmapi-operator` is an operator, and a role that grants it in some environments makes an operator there only. A file that lists `permissions:` for `cmapi-operator` itself must name `namespaces:protect`, or that role is no longer an operator. Each column name has the prefix `cmapi-` in Keycloak. An operator or an admin cannot approve with those roles alone: `requests:approve` is only in `cmapi-approver`. On CRC the group `app-cmapi-rbac-operator` also gives `cmapi-approver`. @@ -129,7 +129,7 @@ request with a bearer token ### Step 1: the token -The core routers and the plugin routers have the token check as a dependency, and the rate limit after it (#689) (`cmapi/src/cmapi/main.py:206-210`). These routes answer without a token. `/healthz`, `/readyz` and `/api/v1/version` come from the health routers, which have no such dependency (`cmapi/src/cmapi/main.py:201-202`). `/problems` and `/problems/{code}` are always public (`cmapi/src/cmapi/main.py:416-430`). `POST /api/v1/webhooks/git` (#783) is mounted beside the version, outside the token check: the Git host has no token, and the delivery's HMAC signature is checked by the route instead (see the table above). `/docs/oauth2-redirect` has no guard, and exists unless `docs.enabled` is `false` (`cmapi/src/cmapi/main.py:493-495`). The seven other docs paths are public unless `docs.public` is `false`; then they need a token and take one from the caller's read bucket, as the API routes do (`cmapi/src/cmapi/main.py:442`). They are `/docs`, `/redoc`, `/openapi.json`, `/openapi.yaml`, `/docs/changelog`, `/docs/redoc-start.js` and `/docs/swagger.css`. They exist unless `docs.enabled` is `false` (`cmapi/src/cmapi/main.py:389-390`). `cmapi/tests/service/test_review_c_authz.py:15-24` lists these routes and the Git webhook as `PUBLIC`, with the `HEAD` of each GET (#605), and every other route must answer 401 with no token. `/metrics` is not an API route: it is served on its own port (`cmapi/src/cmapi/main.py:243-244`). The check is `Authenticator.authenticate` (`cmapi/src/cmapi/core/auth.py:179-215`). It verifies the token offline against the signing keys of the realm. +The core routers and the plugin routers have the token check as a dependency, and the rate limit after it (#689) (`cmapi/src/cmapi/main.py:229-233`). These routes answer without a token. `/healthz`, `/readyz` and `/api/v1/version` come from the health routers, which have no such dependency (`cmapi/src/cmapi/main.py:224-225`). `/problems` and `/problems/{code}` are always public (`cmapi/src/cmapi/main.py:440-454`). `POST /api/v1/webhooks/git` (#783) is mounted beside the version, outside the token check: the Git host has no token, and the delivery's HMAC signature is checked by the route instead (see the table above). `/docs/oauth2-redirect` has no guard, and exists unless `docs.enabled` is `false` (`cmapi/src/cmapi/main.py:517-519`). The seven other docs paths are public unless `docs.public` is `false`; then they need a token and take one from the caller's read bucket, as the API routes do (`cmapi/src/cmapi/main.py:466`). They are `/docs`, `/redoc`, `/openapi.json`, `/openapi.yaml`, `/docs/changelog`, `/docs/redoc-start.js` and `/docs/swagger.css`. They exist unless `docs.enabled` is `false` (`cmapi/src/cmapi/main.py:413-414`). `cmapi/tests/service/test_review_c_authz.py:15-24` lists these routes and the Git webhook as `PUBLIC`, with the `HEAD` of each GET (#605), and every other route must answer 401 with no token. `/metrics` is not an API route: it is served on its own port (`cmapi/src/cmapi/main.py:266-267`). The check is `Authenticator.authenticate` (`cmapi/src/cmapi/core/auth.py:179-215`). It verifies the token offline against the signing keys of the realm. | Check | Source | Refusal | |---|---|---| @@ -145,7 +145,7 @@ The core routers and the plugin routers have the token check as a dependency, an | `iss` is the issuer of the instance | `auth.py:202-204` | 401 `unauthenticated`, "Token issuer is not trusted" | | The token is an access token: its JOSE header `typ` is `at+jwt` or `application/at+jwt` (RFC 9068, section 4), and its claim `typ` is `Bearer` or absent. With `auth.acceptLegacyTokenType: true` in `instance.yaml`, the header `JWT` with the claim `Bearer` passes also | `auth.py:209-214` | 401 `unauthenticated`, "Token is not an access token" | -Each 401 has the header `WWW-Authenticate: Bearer error="invalid_token"` (`auth.py:240-241`, `main.py:287-289`). The tests are in `cmapi/tests/service/test_auth.py`. +Each 401 has the header `WWW-Authenticate: Bearer error="invalid_token"` (`auth.py:240-241`, `main.py:311-313`). The tests are in `cmapi/tests/service/test_auth.py`. ### Step 2: the claims @@ -176,9 +176,9 @@ A role can have a list of environments. The route checks the permission again wh | Route group | Where the environment comes from | Source | |---|---|---| -| Create, change, delete or extend a namespace, or set or remove its expiry | The cluster's environment | `cmapi/src/cmapi/core/pipeline.py:292`, `:611` | +| Create, change, delete or extend a namespace, or set or remove its expiry | The cluster's environment | `cmapi/src/cmapi/core/pipeline.py:325`, `:649` | | Read the namespaces of a cluster | The cluster's environment | `cmapi/src/cmapi/plugins/namespaces/router.py:196`, `:237` | -| List the adoption candidates or the skipped namespaces, or adopt a namespace (#739: `namespaces:write`) | The cluster's environment | `cmapi/src/cmapi/plugins/adoption/router.py:57`, `cmapi/src/cmapi/core/pipeline.py:728` | +| List the adoption candidates or the skipped namespaces, or adopt a namespace (#739: `namespaces:write`) | The cluster's environment | `cmapi/src/cmapi/plugins/adoption/router.py:57`, `cmapi/src/cmapi/core/pipeline.py:766` | | Read one request, its events or its approval status | The request's environment | `cmapi/src/cmapi/routers/requests.py:103`, `:116`, `:130` | | Approve, reject, cancel, retry or revert a request | The request's environment | `requests.py:154`, `:192`, `:216`, `:243`, `:277` | | Confirm a prune | The request's environment | `cmapi/src/cmapi/routers/admin.py:136` | @@ -201,25 +201,25 @@ The tests `test_environment_role_cannot_*` cover each route group (`test_review_ ### Step 5: who can approve or reject -An approval and a rejection have more checks than the permission, the same for both (`approvals.py:395-417`, `ApprovalLedger._eligible`; #779). Before #779 a rejection had only the permission in the environment, so an approver in no approving group of the request could veto it. The request is locked first. The checks are in this order; between the first and the second, a request that is not `pending_approval` gets 409 `not-pending`: +An approval and a rejection have more checks than the permission, the same for both (`approvals.py:401-424`, `ApprovalLedger._eligible`; #779). Before #779 a rejection had only the permission in the environment, so an approver in no approving group of the request could veto it. The request is locked first. The checks are in this order; between the first and the second, a request that is not `pending_approval` gets 409 `not-pending`: | Check | Refusal | |---|---| | The caller has `requests:approve`, or `requests:reject` for a rejection, in the environment of the request (`requests.py:154`, `:192`) | 403 `environment-forbidden` | | The caller has not approved this request before: a person decides a request once, and an approval is not turned into a rejection | 409 `already-approved` | -| The caller did not file the request for another person, unless the rule has `selfApproval: true` | 409 `self-approval`, "The operation starter or client owner cannot approve" (or "reject") | +| The caller did not file the request for another person, and is not an owner of the service client that sent it (`identity.clientOwners`), unless the rule has `selfApproval: true` | 409 `self-approval`, "The operation starter or client owner cannot approve" (or "reject") | | The caller is not the requester, unless the rule has `selfApproval: true` | 409 `self-approval`, "Requesters cannot approve their own request here"; a rejection's detail adds that `:cancel` withdraws it | | The caller is in an approving group that the request still needs: with the caller, one more seat can be filled, and an earlier approver of two groups moves to another seat when that is needed | 403 `not-eligible`, with the groups that are still needed | Who can reject is who can approve. The last check is the same matching for both, so it does not depend on the order of the rule's slots: when an approver of two groups holds the seat of the first, a person of that first group can still approve, and so can still reject (`test_who_may_reject_is_who_may_approve_and_the_group_is_one_still_open`, `tests/core/test_approvals.py`). A rejection that passes ends the request and moves no approval. Its approvals row records a group that is still needed when the caller is in one, and otherwise the group that the caller's approval would have counted for (`counted_for`, with `decision` reject; docs/16). The tests are in `test_reject_decision_779_780.py`. -The ledger can also refuse the owners of the service client that filed a request (docs/01, "Approval of record"), and no route gives it any: see "What is not built". +The owners of a service client come from the instance's `identity.clientOwners` (docs/18; the owner's decision on #789): a username, compared by the `sub` that the directory gives for it, or a Keycloak group, compared with the `groups` claim of the person who decides. They are resolved when the client sends a request, in its own name or for another person, and stored with the request beside `submittedBySub` (`clientOwners` in the row's `requester`, never in a response), so a later change of the setting does not move who may decide a request already filed (`cmapi/src/cmapi/core/pipeline.py`, `Pipeline.with_client_owners`; `RequestRepo.ledger`). A step of an operation is sent by `svc-cmapi-workflows` for whoever started the run. When a service client started it, the request stores that client's owners too (`starterClientOwners`), and the ledger refuses the owners of both clients: the client's own request would refuse them, and an operation lowers no check. A username that the directory does not know refuses the client's request with 500 `internal-error` and the log line `client_owner_unknown`: an owner is never dropped. A client with no entry has no owners, as before #789; the start names each such client that it knows of, and any other is named the first time it sends `onBehalfOf` (`client_without_owners`). The tests are in `test_client_owners_789.py`. An approval rule names a group by its short name, for example `approver-platform`. The path template makes the full path, and the check compares it with the `groups` claim. A request keeps the path that it was decided under, so a change of the template does not move the approvers of an open request (`cmapi/src/cmapi/core/db/repo.py:36-44`). The tests are `test_self_approval_refused_when_the_environment_forbids_it` and `test_submitter_cannot_approve_what_it_filed_on_behalf_of_someone` (`test_review_c_authz.py:204-214`). ### Step 6: the identity of a requester -A write that makes a request also checks who the requester is (`cmapi/src/cmapi/core/identity/checks.py`, called from `pipeline.py:194-196`). These refusals are 422, because the token is valid and the request cannot be recorded: +A write that makes a request also checks who the requester is (`cmapi/src/cmapi/core/identity/checks.py`, called from `pipeline.py:196-203`). These refusals are 422, because the token is valid and the request cannot be recorded: | Code | When | |---|---| @@ -288,7 +288,7 @@ When a person calls, cmapi records the request under the caller of the token. Th | Value | Where it comes from | Where it is kept | |---|---|---| -| `sub` | The claim `sub` (`claims.py:70`) | The database. Self-approval compares it (`approvals.py:409-411`) | +| `sub` | The claim `sub` (`claims.py:70`) | The database. Self-approval compares it (`approvals.py:416-418`) | | Username | The claim `preferred_username` (`claims.py:78`) | The database, and as a label of the namespace (`claims.py:3-5`) | | `email` | The claim `email` (`claims.py:74`) | The database | | `employee_id` | The claim `employee_id` (`claims.py:78`) | The database | @@ -296,15 +296,15 @@ When a person calls, cmapi records the request under the caller of the token. Th The record is `Identity.record` (`claims.py:55-60`). It is in the database only, and never in Git: the comment of the method says so, and so does step 2 above. Git holds the plan. -A person calls as themselves. If a person sends `onBehalfOf`, cmapi refuses with 422 `on-behalf-of-not-allowed` (`checks.py:74-78`). This is step 6. +A person calls as themselves. If a person sends `onBehalfOf`, cmapi refuses with 422 `on-behalf-of-not-allowed` (`checks.py:94-98`). This is step 6. ### No shared submitter -A shared human account, for example `cmapi.requester`, that submits for many people is not in the design. A person cannot use `onBehalfOf` (`checks.py:74-78`), so a shared account would be recorded as the requester. It would have three effects: +A shared human account, for example `cmapi.requester`, that submits for many people is not in the design. A person cannot use `onBehalfOf` (`checks.py:94-98`), so a shared account would be recorded as the requester. It would have three effects: - Attribution is lost. Each request would carry the `sub` and the username of the shared account, and not those of the person. -- The self-approval check fails. The check compares `sub` values (`approvals.py:409-411`). The requester would carry the `sub` of the shared account. A person who submits through it and then approves with their own account has another `sub`, so the check would not refuse. -- The employee ID record is lost. The token of the shared account has one `employee_id`, or none, and a person's write needs one when the instance requires it (`checks.py:79-81`). +- The self-approval check fails. The check compares `sub` values (`approvals.py:416-418`). The requester would carry the `sub` of the shared account. A person who submits through it and then approves with their own account has another `sub`, so the check would not refuse. +- The employee ID record is lost. The token of the shared account has one `employee_id`, or none, and a person's write needs one when the instance requires it (`checks.py:99-101`). A tool that must act for people has its own path: see the next section. @@ -318,15 +318,15 @@ The users filter of realm `cmapi` is `(uid=cmapi.*)` (`docs/15`, "The LDAP feder ### Tools that act for people -A tool signs in with the client credentials grant. It is a service client, or an account that holds a role in `identity.automationRoles`. The default role is `cmapi-onboarding`, and `cmapi-automation` holds it (`checks.py:1-15`; `docs/15`, "The clients"). The tool is the caller. Three cases follow (`checks.py:70-95`, called from `pipeline.py:298`): +A tool signs in with the client credentials grant. It is a service client, or an account that holds a role in `identity.automationRoles`. The default role is `cmapi-onboarding`, and `cmapi-automation` holds it (`checks.py:1-18`; `docs/15`, "The clients"). The tool is the caller. Three cases follow (`checks.py:90-115`, called from `pipeline.py:331`): | Case | What cmapi does | Source | |---|---|---| -| The tool sends no `onBehalfOf` | The tool is the requester. The request is recorded as automated. If `identity.requireOnBehalfOf` is `true`, the tool must name a person, and without one the answer is 422 `on-behalf-of-required` | `checks.py:83-88`; `problem_docs.py:115` | -| The tool sends `onBehalfOf`: a username or an employee ID | cmapi looks the value up in the directory. The person must be enabled, or the answer is 422 `unknown-user`. The person is recorded as the requester and the tool as the caller. The request is recorded as automated | `checks.py:89-95` | -| A person sends `onBehalfOf` | 422 `on-behalf-of-not-allowed` | `checks.py:74-78`; `problem_docs.py:114` | +| The tool sends no `onBehalfOf` | The tool is the requester. The request is recorded as automated. If `identity.requireOnBehalfOf` is `true`, the tool must name a person, and without one the answer is 422 `on-behalf-of-required` | `checks.py:103-108`; `problem_docs.py:115` | +| The tool sends `onBehalfOf`: a username or an employee ID | cmapi looks the value up in the directory. The person must be enabled, or the answer is 422 `unknown-user`. The person is recorded as the requester and the tool as the caller. The request is recorded as automated | `checks.py:109-115` | +| A person sends `onBehalfOf` | 422 `on-behalf-of-not-allowed` | `checks.py:94-98`; `problem_docs.py:114` | -Self-approval uses the requester and the submitter. The ledger refuses the requester as approver: `requester_sub` is the `sub` of the named person (`checks.py:49-53`, `pipeline.py:888`, `approvals.py:409-411`). It also refuses the submitter, which is the `sub` of the tool, unless the approval rule has `selfApproval: true` (`cmapi/src/cmapi/core/db/repo.py:249-251`, `approvals.py:407-408`). The record keeps the submitter in `submittedBySub`, and the response leaves it out (`checks.py:59-64`, `views.py:25-27`). +Self-approval uses the requester and the submitter. The ledger refuses the requester as approver: `requester_sub` is the `sub` of the named person (`checks.py:60-64`, `pipeline.py:926`, `approvals.py:416-418`). It also refuses the submitter, which is the `sub` of the tool, and the owners of a service client that sent the request (`identity.clientOwners`, #789), unless the approval rule has `selfApproval: true` (`cmapi/src/cmapi/core/db/repo.py:253-261`, `approvals.py:413-415`). The record keeps the submitter in `submittedBySub` and the owners in `clientOwners` (and in `starterClientOwners`, for a step of an operation that a service client started), and the response leaves them out (`checks.py:70-86`, `views.py:26-28`). With `onBehalfOf`, cmapi trusts the tool to name the person. The directory proves that the person exists and is enabled. It does not prove that the person signed in. @@ -365,7 +365,7 @@ Each refusal is an RFC 9457 problem with the media type `application/problem+jso | 403 | `environment-forbidden` | A role gives the permission, but not in this environment | Use the instance or the role for that environment | | 403 | `webhook-signature-invalid` | `POST /api/v1/webhooks/git` only: the delivery's `X-Hub-Signature-256` is missing or is not the HMAC-SHA256 of its body with this instance's webhook secret (#783). 403, not 401: RFC 9110, section 15.5.2, makes a 401 carry a `WWW-Authenticate` challenge, and HTTP has none for a signed body | Set the same secret on the Git host and in Secret `cmapi-git-webhook`, then redeliver from the host | | 403 | `not-eligible` | The caller is in no approving group that the request still needs, on `:approve` or `:reject` | Another approver must act | -| 409 | `self-approval` | The caller is the requester, or the client that filed the request for the requester, and the rule does not have `selfApproval: true` | Another approver must act. A requester withdraws their own request with `:cancel` | +| 409 | `self-approval` | The caller is the requester, the client that filed the request for the requester, or an owner of the service client that sent it (`identity.clientOwners`), and the rule does not have `selfApproval: true` | Another approver must act. A requester withdraws their own request with `:cancel` | | 409 | `already-approved` | The caller approved this request before, and now approves or rejects it | No action. Another approver of a group still needed can reject it, and the requester or an operator can cancel it | | 503 | `idp-unavailable` | The signing keys cannot be read and the key of this token is not cached | Try again after `retryAfter` seconds | @@ -376,7 +376,7 @@ The code `forbidden` has two more causes. Each is a refusal of the code, not of | A caller cancels a request that is not theirs and does not hold `namespaces:protect` in its environment | "Only the requester or an operator can cancel" | `cmapi/src/cmapi/core/lifecycle.py:125`, `cmapi/src/cmapi/routers/requests.py:221` | | A write sets or removes an operator-only label or annotation (`cmapi.net/protected`, `do-not-delete`) and the caller does not hold `namespaces:protect` in the environment | "Needs namespaces:protect in . Keys: ." (the cluster's environment, #532) | `cmapi/src/cmapi/core/metadata.py:1434` | -The ledger also refuses a relay client without `approvals:relay` with this code ("Relay client lacks approvals:relay", `cmapi/src/cmapi/core/approvals.py:376`), but no route can reach it: the approve route in `routers/requests.py` passes no relay to `ApprovalLedger.approve` (see "What is not built"). +The ledger also refuses a relay client without `approvals:relay` with this code ("Relay client lacks approvals:relay", `cmapi/src/cmapi/core/approvals.py:382`), but no route can reach it: the approve route in `routers/requests.py` passes no relay to `ApprovalLedger.approve` (see "What is not built"). A sample 403, taken from a run of the service suite's app on 2026-11-13. A caller with the role `cmapi-viewer` sent `POST /api/v1/admin/auto-approval:pause`: @@ -400,8 +400,7 @@ A sample 403, taken from a run of the service suite's app on 2026-11-13. A calle |---|---| | Routes for quotas, service accounts, grants, configuration, cluster onboarding, reload, events and audit export | Not built. Their permissions exist in `authz.py`, and no route uses them | | `adoption:write`: the scan of a cluster and the unmanaged-namespaces report (#252's admin operations) | Not built. The adoption of one namespace is self-service: its three routes need `namespaces:write` in the cluster's environment, and the approval rules gate it (#739, the owner's decision of 2026-11-26 on #26). The routes declare and enforce the same permission (`cmapi/src/cmapi/plugins/adoption/router.py`, `ADOPT_PERMISSION`) | -| The approval relay for email, ServiceNow and chat (`approvals:relay`) | The check exists in `approvals.py:373-376`. No route accepts a relayed approval | -| An owner of the service client that filed a request cannot approve or reject it (docs/01, "Approval of record") | The check exists in `approvals.py:407-408` (`client_owner_subs`), and only the pure tests give it owners. `RequestRepo.ledger` passes none (`cmapi/src/cmapi/core/db/repo.py:249-251`), because cmapi has no record of who owns a client. So a person who controls the client's credentials, and is in an approving group that the request needs, can approve or reject what that client filed for another person. The client itself is refused, unless the rule has `selfApproval: true`. Filed as #789 | +| The approval relay for email, ServiceNow and chat (`approvals:relay`) | The check exists in `approvals.py:379-382`. No route accepts a relayed approval | | A scope by team or by namespace name | Not designed. A role with `namespaces:create` can ask for each name that is not reserved (`authz.py:8-10`) | ## Proof diff --git a/docs/15-keycloak-integration.md b/docs/15-keycloak-integration.md index ff08b4c3..00649709 100644 --- a/docs/15-keycloak-integration.md +++ b/docs/15-keycloak-integration.md @@ -100,7 +100,7 @@ Both calls verify Keycloak's certificate against the CA in ConfigMap `cmapi-trus ## From sign-in to a permitted call -Swagger UI uses Authorization Code with PKCE through the public client `cmapi-docs` (`cmapi/src/cmapi/main.py:199-200`, `core/auth.py:218-223`). The portal uses the same flow through `cmapi-portal`: see "The portal's sign-in". +Swagger UI uses Authorization Code with PKCE through the public client `cmapi-docs` (`cmapi/src/cmapi/main.py:222-223`, `core/auth.py:218-223`). The portal uses the same flow through `cmapi-portal`: see "The portal's sign-in". ```text Browser (Swagger UI at /docs) Keycloak, realm cmapi cmapi-api diff --git a/docs/16-data-model.md b/docs/16-data-model.md index e04fd39b..880683f1 100644 --- a/docs/16-data-model.md +++ b/docs/16-data-model.md @@ -8,13 +8,13 @@ The database is PostgreSQL through CloudNativePG, or an existing PostgreSQL serv | Table | One row is | Written by | Read by | |---|---|---|---| -| `change_requests` | One write to a namespace: its plan, its approval rule, its requester, its pull request and its state | The API when a write is submitted (`RequestRepo.insert`, `core/db/repo.py:166`), then the API and the worker on each state change (`RequestRepo.move`, `repo.py:199`) | The request routes, the worker jobs, the KPI report | -| `request_events` | One state change or note of a request, in order | `RequestRepo.event` and `RequestRepo.move` (`repo.py:194-199`) | `GET /api/v1/requests/{request_id}/events` | -| `approvals` | One decision of one person on one request: an approval or, since migration `0014`, a rejection (#780) | `RequestRepo.record_approval` (`repo.py:257`) and `RequestRepo.record_rejection` (`repo.py:268`) | The approval ledger (`repo.py:243`), which reads the approvals only (`repo.py:85`) | -| `jobs` | One unit of work for the worker, with its lease | `JobRepo.enqueue` (`repo.py:280`) | The worker: `JobRepo.claim` (`repo.py:293`) | -| `audit_events` | One recorded action: who, what and on which target | `AuditRepo.record` (`repo.py:365`) | No route reads it yet. `AuditRepo.recent` exists (`repo.py:369`) | -| `jwks_keys` | The last good signing keys of one issuer | `DbKeyStore.save` (`repo.py:406`) | `DbKeyStore.load` (`repo.py:401`), when a pod starts while Keycloak does not answer | -| `admin_switches` | One switch of the instance, for example `auto-approval`, with who set it | `SwitchRepo.set` (`repo.py:387`) | `SwitchRepo.get` (`repo.py:377`), for the admin view. Each approval decision reads the value with `SwitchRepo.value` (`repo.py:381`), in the caller's transaction when it has one | +| `change_requests` | One write to a namespace: its plan, its approval rule, its requester, its pull request and its state | The API when a write is submitted (`RequestRepo.insert`, `core/db/repo.py:172`), then the API and the worker on each state change (`RequestRepo.move`, `repo.py:205`) | The request routes, the worker jobs, the KPI report | +| `request_events` | One state change or note of a request, in order | `RequestRepo.event` and `RequestRepo.move` (`repo.py:200-205`) | `GET /api/v1/requests/{request_id}/events` | +| `approvals` | One decision of one person on one request: an approval or, since migration `0014`, a rejection (#780) | `RequestRepo.record_approval` (`repo.py:267`) and `RequestRepo.record_rejection` (`repo.py:278`) | The approval ledger (`repo.py:249`), which reads the approvals only (`repo.py:85`) | +| `jobs` | One unit of work for the worker, with its lease | `JobRepo.enqueue` (`repo.py:290`) | The worker: `JobRepo.claim` (`repo.py:303`) | +| `audit_events` | One recorded action: who, what and on which target | `AuditRepo.record` (`repo.py:375`) | No route reads it yet. `AuditRepo.recent` exists (`repo.py:379`) | +| `jwks_keys` | The last good signing keys of one issuer | `DbKeyStore.save` (`repo.py:416`) | `DbKeyStore.load` (`repo.py:411`), when a pod starts while Keycloak does not answer | +| `admin_switches` | One switch of the instance, for example `auto-approval`, with who set it | `SwitchRepo.set` (`repo.py:397`) | `SwitchRepo.get` (`repo.py:387`), for the admin view. Each approval decision reads the value with `SwitchRepo.value` (`repo.py:391`), in the caller's transaction when it has one | | `approval_notifications` | One notice that a channel recorded for a request | The worker job `channel_notify` (`jobs/channel_notify.py:30`) | The same job, to send a notice only once | | `expiration_notices` | One expiry notice for a namespace | No code writes it yet. The job `expire_check` is not built | No code reads it yet | | `policy_rejections` | One refusal of cmapi before Git on one UTC day, or Kyverno's warnings on a plan that became a request (#302) | `RejectionRepo.record` (`core/rejections.py`), from the namespace routes, `_submit` and the job `pr_checks`; pruned by the job `rejections_prune` | `GET /api/v1/policies/rejections` | @@ -67,8 +67,8 @@ These indexes and constraints carry correctness. The code relies on each of them | One decision for each person on a request: a person who approved cannot then reject (409 `already-approved`, #779) | The unique index `uq_approvals_person` on `(request_id, approver_sub)` | Migration `0002` | | A decision is an approval or a rejection, and each row from before the column is an approval | The check `ck_approvals_decision` on `decision IN ('approve', 'reject')`, and the column's default `'approve'`. Only an approval fills a slot (`RequestRepo.approvals`). The downgrade refuses while a rejection is stored | Migration `0014` | | An approval says which approving group it counted for | `approvals.counted_for`. Each new approval writes the column again for each approval of the request, because the ledger can move an earlier approval to another slot. It is null for an approval from before the column | Migration `0004` | -| One pending job for each kind, request and payload kind. A job with no request counts the request as empty. A second `enqueue` with the same three values does nothing (`JobRepo.enqueue`, `repo.py:280`) | The partial unique index `uq_jobs_pending` on `(kind, coalesce(request_id, ''), coalesce(payload->>'kind', ''))`, for rows with no `done_at` | Migration `0001`, line 108 | -| A worker that lost its lease cannot commit | `jobs.lease_generation` increases at each claim, and the commit checks it | Migration `0003`, `JobRepo.assert_lease` (`repo.py:306`) | +| One pending job for each kind, request and payload kind. A job with no request counts the request as empty. A second `enqueue` with the same three values does nothing (`JobRepo.enqueue`, `repo.py:290`) | The partial unique index `uq_jobs_pending` on `(kind, coalesce(request_id, ''), coalesce(payload->>'kind', ''))`, for rows with no `done_at` | Migration `0001`, line 108 | +| A worker that lost its lease cannot commit | `jobs.lease_generation` increases at each claim, and the commit checks it | Migration `0003`, `JobRepo.assert_lease` (`repo.py:316`) | | A requester is a person or a service | The check `ck_cr_requester_kind` | Migration `0001`, line 54 | | One delivery of the Git webhook is acted on once (#783) | The primary key `webhook_deliveries_pkey` on `(provider, delivery_id)`. `receive` inserts the row with `ON CONFLICT DO NOTHING` before it moves anything, in the same transaction: a second delivery with the same ID, even one sent at the same moment, waits for the first transaction and then finds the row, so it moves nothing. The check `ck_webhook_queued_request`: a delivery that moved a check names its request | Migration `0015` | | A hold is released with its reason, or not at all | The check `ck_resv_released`: `released_at` and `released_why` are both set or both null. `released_why` is the state the request moved to (`synced`, `rejected`, `cancelled`, `timeout`, `failed`, `superseded`, `sync_failed`) or `expired`. No code writes `observed` (docs/02's list): each reader stops counting a hold from its own watch, and the row stays active until the lifecycle releases it | Migration `0011` | @@ -153,10 +153,10 @@ The table `_T` in `cmapi/src/cmapi/core/lifecycle.py` holds each allowed move. N |---|---|---| | `plan` | `files` (the rendered files of the folder, path to text, null for a file that the plan removes), `prev` (the folder as Git held it), `changes` (path to `added`, `changed` or `removed`), `facts` (what the approval rules read, for example `beyondTier`, `beyondTierKeys`, `networkExposure`, `tierChange`, `quotaIncreasePct`, `keyClasses`), `capacity`, `spec` (the namespace spec that the renderer used), `findings` (each finding of the validator, with its severity and source) and `beyondTier` (the keys of a custom tier that differ from the tier, and the approvals that they add; null when none) | `Plan.stored` | | `requirement` | `rule` (for example `rnd-create`), `slots` (each `group`, `count` and `reason`), `selfApproval`, `timeoutHours`, `reasons`, `auto` (`auto:`, `none-required`, or null), `autoFallback` (the guard that stopped a matching auto-approval policy) and `groupPath` (the `identity.groupPath` of the instance when the rule was decided) | `requirement_to_json` | -| `requester` | `requester` (the person: `sub`, `username`, `email`, `givenName`, `middleName`, `familyName`, `employeeId`, `kind`, and `clientId` when the person is an `Identity`), `automated`, and, when a service sent the request for a person: `submittedBy`, `submittedBySub` and `submittedByClient` | `Requester.record` | +| `requester` | `requester` (the person: `sub`, `username`, `email`, `givenName`, `middleName`, `familyName`, `employeeId`, `kind`, and `clientId` when the person is an `Identity`), `automated`, and, when a service sent the request for a person: `submittedBy`, `submittedBySub` and `submittedByClient`; and, when a service client with an entry in `identity.clientOwners` sent it, `clientOwners` (`client`, `subs`, `groups`: its owners when it filed, #789); and, for a step of an operation that a service client with an entry started, `starterClientOwners` (the same three keys, for the client that started the run) | `Requester.record` | | `pr` | `number`, `url`, `branch`, `head` | `open_pr` | -`submittedBySub` stays in the database. The API leaves it out of each view (`cmapi/src/cmapi/core/views.py`). A request keeps its own `groupPath`, so a later change of `identity.groupPath` cannot move the approvers of an open request. A row from before that key was written is read with the older template `/cmapi/cmapi-{name}` (`LEGACY_GROUP_PATH`, `core/authz.py`). +`submittedBySub`, `clientOwners` and `starterClientOwners` stay in the database. The API leaves them out of each view (`public_record`, `cmapi/src/cmapi/core/identity/checks.py`). A request keeps its own `clientOwners`, so a later change of `identity.clientOwners` cannot move who may decide an open request. A request keeps its own `groupPath`, so a later change of `identity.groupPath` cannot move the approvers of an open request. A row from before that key was written is read with the older template `/cmapi/cmapi-{name}` (`LEGACY_GROUP_PATH`, `core/authz.py`). ### `request_events` diff --git a/docs/18-configuration.md b/docs/18-configuration.md index a0a890a7..59e6bddc 100644 --- a/docs/18-configuration.md +++ b/docs/18-configuration.md @@ -89,6 +89,7 @@ How to make the bot account, its token and its SSH key, and how to switch `insta | `instance.identity.requireOnBehalfOf` | boolean | `false` | `true` makes a service client name the person that the request is for | | `instance.identity.automationRoles` | list of roles | `[cmapi-onboarding]` | A caller with one of these roles needs no `employee_id` | | `instance.identity.groupPath` | text | `/cmapi/app-cmapi-rbac-{name}` | The path of the Keycloak group that an approving group of `approval-rules.yaml` names. It starts with `/` and holds `{name}` one time. A bad value stops the start (`core/authz.py`, `check_group_path`) | +| `instance.identity.clientOwners` | mapping of a client ID to a list of usernames and group paths | `{}` | Who owns each service client (#789). An owner may not approve or reject what the client sends, in its own name or for another person, unless the rule has `selfApproval: true` (docs/14, "Step 5"). An entry that starts with `/` is a Keycloak group by its full path, as the token's `groups` claim carries it, for example `/cmapi/team-payments`; any other entry is a username (Keycloak refuses `/` in a username). A username is resolved to its `sub` through the directory when the client sends a request, and stored with the request; a group is compared with the decider's token. `[]` says the client has no owners. A value that is not a list of names, or a username with white space, stops the start; usernames with no directory (no `CMAPI_DIRECTORY_CLIENT_SECRET`) stop it too. A username that the directory does not know refuses each request of that client with 500 `internal-error` and the log line `client_owner_unknown`; the API's start logs it first. A client with no entry has no owners: the start names each one it knows of (the clients that `approval-rules.yaml` names in `requester.clients`, and those that filed for another person before) in `client_without_owners`, and any other the first time it sends `onBehalfOf` (`core/identity/owners.py`, `core/pipeline.py`, `main.py`, `check_client_owners`) | | `instance.git.repository` | text | None. Needed | The cluster-configs repository of the instance, as `owner/name` | | `instance.git.webUrl` | text (URL) | The API URL of the Git host | The address of the repository for people | | `instance.git.url` | text (URL) | `/.git` | The URL the worker's Git layer clones and pushes (#286): `https://host/path`, `ssh://git@host[:port]/path` or `git@host:path`. cmapi refuses `http://` and `git://` (no TLS), and a user or a token in an `https` URL (`core/git/transport.py`, `parse_remote`) | diff --git a/docs/21-usage-from-thanos.md b/docs/21-usage-from-thanos.md index 82eeb43c..c3b50bb6 100644 --- a/docs/21-usage-from-thanos.md +++ b/docs/21-usage-from-thanos.md @@ -115,9 +115,9 @@ from the file. The file also creates the Namespace `cmapi-system` and the Servic | Rule | API group and resources | Verbs | Why cmapi needs it | |---|---|---|---| -| 1 (`examples/baseline/cmapi-reader-rbac.yaml:23-25`) | core: `namespaces`, `nodes`, `resourcequotas`, `limitranges`, `serviceaccounts` | get, list, watch | Namespaces, ResourceQuotas and LimitRanges are the kinds `WatchCache` watches (`cmapi/src/cmapi/core/clients/kube.py:428`), and check 6 lists Namespaces (`cmapi/src/cmapi/core/registry.py:703`). `NodeCache` watches Nodes (`cmapi/src/cmapi/core/clients/nodes.py:33`, `:114`). The adoption plan lists a namespace's ServiceAccounts to count what stays unmanaged: `Pipeline._unadopted_counts` (`cmapi/src/cmapi/core/pipeline.py:691-701`), over `UNADOPTED_KINDS` (`cmapi/src/cmapi/core/adoption.py:43`) | -| 2 (`examples/baseline/cmapi-reader-rbac.yaml:26-28`) | core: `pods`, `persistentvolumeclaims` | list | The delete thresholds count a namespace's pods and PVCs: `Pipeline.workload_counts` (`cmapi/src/cmapi/core/pipeline.py:261-267`) | -| 3 (`examples/baseline/cmapi-reader-rbac.yaml:29-31`) | `rbac.authorization.k8s.io`: `roles`, `rolebindings`, `clusterroles`, `clusterrolebindings` | get, list, watch | The adoption plan lists a namespace's RoleBindings in the same count: `Pipeline._unadopted_counts` (`cmapi/src/cmapi/core/pipeline.py:691-701`). No code reads the other three today | +| 1 (`examples/baseline/cmapi-reader-rbac.yaml:23-25`) | core: `namespaces`, `nodes`, `resourcequotas`, `limitranges`, `serviceaccounts` | get, list, watch | Namespaces, ResourceQuotas and LimitRanges are the kinds `WatchCache` watches (`cmapi/src/cmapi/core/clients/kube.py:428`), and check 6 lists Namespaces (`cmapi/src/cmapi/core/registry.py:703`). `NodeCache` watches Nodes (`cmapi/src/cmapi/core/clients/nodes.py:33`, `:114`). The adoption plan lists a namespace's ServiceAccounts to count what stays unmanaged: `Pipeline._unadopted_counts` (`cmapi/src/cmapi/core/pipeline.py:729-739`), over `UNADOPTED_KINDS` (`cmapi/src/cmapi/core/adoption.py:43`) | +| 2 (`examples/baseline/cmapi-reader-rbac.yaml:26-28`) | core: `pods`, `persistentvolumeclaims` | list | The delete thresholds count a namespace's pods and PVCs: `Pipeline.workload_counts` (`cmapi/src/cmapi/core/pipeline.py:294-300`) | +| 3 (`examples/baseline/cmapi-reader-rbac.yaml:29-31`) | `rbac.authorization.k8s.io`: `roles`, `rolebindings`, `clusterroles`, `clusterrolebindings` | get, list, watch | The adoption plan lists a namespace's RoleBindings in the same count: `Pipeline._unadopted_counts` (`cmapi/src/cmapi/core/pipeline.py:729-739`). No code reads the other three today | | 4 (`examples/baseline/cmapi-reader-rbac.yaml:32-34`) | `security.openshift.io`: `securitycontextconstraints` | get, list, watch | No code reads it today | | 5 (`examples/baseline/cmapi-reader-rbac.yaml:35-37`) | `user.openshift.io`: `users`, `groups`, `identities` | get, list, watch | The identity check reads `users/~`, which every authenticated user may read (`cmapi/src/cmapi/core/clients/kube.py:273-275`); no code lists the others today | | 6 (`examples/baseline/cmapi-reader-rbac.yaml:38-40`) | `quota.openshift.io`: `clusterresourcequotas` | get, list, watch | No code reads it today | @@ -221,7 +221,7 @@ they are kept. While any finding stands, `ThanosQuerier.query` refuses before it the user-workload Prometheus and the Thanos Ruler, which CRC reported at 86400 seconds beside the platform's 1296000 (`docs/reviews/2026-12-01-issue-763/README.md`, D1). - **A namespace create never queries Thanos.** Only a quota change on an existing namespace reads usage - (`cmapi/src/cmapi/core/pipeline.py:467-474`). A test creates a namespace on PostgreSQL with `usage.source: thanos` and both + (`cmapi/src/cmapi/core/pipeline.py:505-512`). A test creates a namespace on PostgreSQL with `usage.source: thanos` and both grants missing: it is auto-approved, reaches `synced`, and makes no monitoring call; the quota change after it plans with usage `unavailable` (`cmapi/tests/service/test_reader_thanos_grants_724.py:428-470`). diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md index 55b85e77..424b1e7e 100644 --- a/docs/GLOSSARY.md +++ b/docs/GLOSSARY.md @@ -176,6 +176,7 @@ Status: read from `main` at `afd1206` on 2026-11-23. Each row was read from the | LDAP | The existing LDAP server that federates users and groups into Keycloak. cmapi adds its groups and 13 test users to it and changes nothing else. | [11-existing-identity-services.md](11-existing-identity-services.md), [14-authorization.md](14-authorization.md) | | `employee_id` | The token claim that a person's request needs. Without it: 422 `identity-incomplete`. A role in `identity.automationRoles` needs none. | [18-configuration.md](18-configuration.md) | | `onBehalfOf` | A service client names the person a request is for. A person calls as themselves (422 `on-behalf-of-not-allowed`); a service client with `requireOnBehalfOf` must name one (422 `on-behalf-of-required`). | [core/docs.py](../cmapi/src/cmapi/core/docs.py), [18-configuration.md](18-configuration.md) | +| Client owner, `identity.clientOwners` | A person who owns a service client: a username or a Keycloak group listed for the client ID in `instance.yaml`. Resolved to `sub` when the client sends a request and stored with it (`clientOwners`, never in a response; `starterClientOwners` for the client that started an operation). An owner may not approve or reject what the client sent unless the rule has `selfApproval: true` (409 `self-approval`, #789). | [18-configuration.md](18-configuration.md), [core/identity/owners.py](../cmapi/src/cmapi/core/identity/owners.py) | | `cmapi.requester` | The test user that requests namespaces on CRC. | [14-authorization.md](14-authorization.md), [HANDOVER-AND-RESUME.md](../HANDOVER-AND-RESUME.md) | ## Clusters and environments diff --git a/docs/citations.lock.json b/docs/citations.lock.json index 389be927..dc2eee2c 100644 --- a/docs/citations.lock.json +++ b/docs/citations.lock.json @@ -1,14 +1,14 @@ { - "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|373-376": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|379-382": [ " if relay is not None:", " ok = relay_permitted if relay_permitted is not None else \"approvals:relay\" in builtin_permissions(relay)", " if not ok:", " raise Problem.forbidden(\"Relay client lacks approvals:relay\")" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|376-376": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|382-382": [ " raise Problem.forbidden(\"Relay client lacks approvals:relay\")" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|395-417": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|401-424": [ " def _eligible(self, person: Identity, verb: str, permitted: bool | None, entry: dict[str, Any]) -> int:", " \"\"\"The checks of a decision, approve or reject, in docs/14's order; returns the seat the person would fill.", "", @@ -21,7 +21,8 @@ " if person.sub in {e[\"sub\"] for e in self.entries}:", " raise Problem.conflict(\"already-approved\", \"This person already approved the request\"", " + (\"\" if verb == \"approve\" else \", and a person decides a request once\"))", - " if person.sub in self.client_owner_subs or person.sub == self.operation_starter_sub:", + " if person.sub in self.client_owner_subs or self.client_owner_groups & person.groups \\", + " or person.sub == self.operation_starter_sub:", " raise Problem.conflict(\"self-approval\", f\"The operation starter or client owner cannot {verb}\")", " if person.sub == self.requester_sub and not self.requirement.self_approval:", " raise Problem.conflict(\"self-approval\", f\"Requesters cannot {verb} their own request here\"", @@ -33,11 +34,12 @@ " # The person is tried last and the matching grew, so the augmenting path that grew it starts at them: they hold a seat.", " return next(si for si, pi in after.items() if pi == len(self.entries))" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|407-408": [ - " if person.sub in self.client_owner_subs or person.sub == self.operation_starter_sub:", + "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|413-415": [ + " if person.sub in self.client_owner_subs or self.client_owner_groups & person.groups \\", + " or person.sub == self.operation_starter_sub:", " raise Problem.conflict(\"self-approval\", f\"The operation starter or client owner cannot {verb}\")" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|409-411": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|416-418": [ " if person.sub == self.requester_sub and not self.requirement.self_approval:", " raise Problem.conflict(\"self-approval\", f\"Requesters cannot {verb} their own request here\"", " + (\"\" if verb == \"approve\" else \"; :cancel withdraws it\"))" @@ -318,10 +320,16 @@ "any namespace name (outside the reserved ones) in the environments that role covers; approval rules decide what needs approval,", "and approving groups (Keycloak groups) decide who may approve." ], - "docs/14-authorization.md|cmapi/src/cmapi/core/db/repo.py|249-251": [ - " submitter = (row.requester or {}).get(\"submittedBySub\")", + "docs/14-authorization.md|cmapi/src/cmapi/core/db/repo.py|253-261": [ + " # Who filed it for someone else is a second identity on the request, and the owners of the service client that", + " # filed it are a third (#789, stored when it was filed): under a no-self-approval rule none of them may decide it.", + " # An operation's step holds two snapshots, its sender's and its starter's client's, and the ledger refuses both.", + " record = row.requester or {}", + " owners = [] if req.self_approval else [record[k] for k in (\"clientOwners\", \"starterClientOwners\") if record.get(k)]", " ledger = ApprovalLedger(req, requester_sub=row.requester_sub,", - " operation_starter_sub=None if req.self_approval else submitter)" + " operation_starter_sub=None if req.self_approval else record.get(\"submittedBySub\"),", + " client_owner_subs=frozenset(sub for o in owners for sub in o.get(\"subs\", ())),", + " client_owner_groups=frozenset(group for o in owners for group in o.get(\"groups\", ())))" ], "docs/14-authorization.md|cmapi/src/cmapi/core/db/repo.py|36-44": [ " return {\"rule\": r.rule, \"slots\": [asdict(s) for s in r.slots], \"selfApproval\": r.self_approval,", @@ -342,7 +350,7 @@ " x: dict[str, Any] = {\"x-cmapi-permission\": permission, \"x-cmapi-plugin\": self.plugin,", " \"x-plugin-version\": self.version, **extra}" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/identity/checks.py|1-15": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/identity/checks.py|1-18": [ "\"\"\"Request-time identity checks: who the request is for, and the email-domain rule.", "", "- A person calling with their own token is the requester; sending onBehalfOf is refused.", @@ -355,26 +363,57 @@ " (identity.automationRoles, default [cmapi-onboarding]). An AI agent or a script signs in as the service", " client cmapi-automation, with client credentials. An automation caller may also send onBehalfOf.", "- Every request records whether it was automated (a service client or an automation account).", + "- A request a service client sends records the owners of that client (identity.clientOwners, core/identity/owners.py; #789),", + " whom the approval ledger refuses as approvers unless the rule has selfApproval: true. A step of an operation that a", + " service client started records that client's owners too: the workflow client sends it, and delegation lowers no check.", "- Email-valued governed keys (cmapi.net/team-dl) must be an address in one of emailDomains from", " metadata-keys.yaml. Format only: DLs are never looked up.", "\"\"\"" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/identity/checks.py|49-53": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/identity/checks.py|103-108": [ + " if not on_behalf_of:", + " if require_on_behalf_of:", + " raise Problem.unprocessable(\"on-behalf-of-required\",", + " \"A service client or automation account must name the person the \"", + " \"request is for\")", + " return Requester(person=caller, caller=caller, automated=True) # the bot is the requester" + ], + "docs/14-authorization.md|cmapi/src/cmapi/core/identity/checks.py|109-115": [ + " if directory is None:", + " raise Problem.unprocessable(\"unknown-user\", \"No directory is configured\")", + " person = directory.get_user(on_behalf_of) or directory.find_by_employee_id(on_behalf_of)", + " if person is None or not person.enabled or is_reserved(person.sub, person.username):", + " raise Problem.unprocessable(\"unknown-user\", f\"{on_behalf_of} is not an enabled user\",", + " onBehalfOf=on_behalf_of)", + " return Requester(person=person, caller=caller, automated=True)" + ], + "docs/14-authorization.md|cmapi/src/cmapi/core/identity/checks.py|60-64": [ " def sub(self) -> str:", " \"\"\"The person's Keycloak user ID: the requester_sub the approval ledger refuses as approver.\"\"\"", " if not self.person.sub:", " raise Problem.unprocessable(\"unknown-user\", f\"No user ID for {self.person.username}\")", " return self.person.sub" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/identity/checks.py|59-64": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/identity/checks.py|70-86": [ " def record(self) -> dict:", " rec = {\"requester\": self.person.record(), \"automated\": self.automated}", " if self.person is not self.caller:", " rec[\"submittedBy\"] = self.caller.username", " rec[\"submittedBySub\"] = self.caller.sub", - " if self.caller.kind == \"service\":" + " if self.caller.kind == \"service\":", + " rec[\"submittedByClient\"] = self.caller.client_id", + " if self.client_owners is not None:", + " rec[\"clientOwners\"] = self.client_owners.record()", + " if self.starter_client_owners is not None:", + " rec[\"starterClientOwners\"] = self.starter_client_owners.record()", + " return rec", + "", + "", + "def public_record(record: dict) -> dict:", + " \"\"\"A request's requester record as a response shows it: without PRIVATE_RECORD_KEYS.\"\"\"", + " return {k: v for k, v in record.items() if k not in PRIVATE_RECORD_KEYS}" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/identity/checks.py|70-95": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/identity/checks.py|90-115": [ " directory: DirectoryProvider | CachedDirectory | None,", " require_employee_id: bool = True, require_on_behalf_of: bool = False,", " automation_roles: Iterable[str] = (\"cmapi-onboarding\",)) -> Requester:", @@ -402,35 +441,18 @@ " onBehalfOf=on_behalf_of)", " return Requester(person=person, caller=caller, automated=True)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/identity/checks.py|74-78": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/identity/checks.py|94-98": [ " if not automated:", " if on_behalf_of:", " raise Problem.unprocessable(\"on-behalf-of-not-allowed\",", " \"A person calls as themselves; onBehalfOf is for service clients \"", " \"and automation accounts\")" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/identity/checks.py|79-81": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/identity/checks.py|99-101": [ " if require_employee_id and not caller.employee_id:", " raise Problem.unprocessable(\"identity-incomplete\",", " \"The token has no employee_id claim; check the cmapi-identity client scope\")" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/identity/checks.py|83-88": [ - " if not on_behalf_of:", - " if require_on_behalf_of:", - " raise Problem.unprocessable(\"on-behalf-of-required\",", - " \"A service client or automation account must name the person the \"", - " \"request is for\")", - " return Requester(person=caller, caller=caller, automated=True) # the bot is the requester" - ], - "docs/14-authorization.md|cmapi/src/cmapi/core/identity/checks.py|89-95": [ - " if directory is None:", - " raise Problem.unprocessable(\"unknown-user\", \"No directory is configured\")", - " person = directory.get_user(on_behalf_of) or directory.find_by_employee_id(on_behalf_of)", - " if person is None or not person.enabled or is_reserved(person.sub, person.username):", - " raise Problem.unprocessable(\"unknown-user\", f\"{on_behalf_of} is not an enabled user\",", - " onBehalfOf=on_behalf_of)", - " return Requester(person=person, caller=caller, automated=True)" - ], "docs/14-authorization.md|cmapi/src/cmapi/core/identity/claims.py|3-5": [ "The requester's identity is never taken from a request body: username and email go on the", "Namespace (cmapi.net/requested-by-user, cmapi.net/requested-by); names and employee ID stay in the", @@ -495,27 +517,32 @@ "docs/14-authorization.md|cmapi/src/cmapi/core/metadata.py|1434-1434": [ " raise Problem.forbidden(f\"{_operator_only_reason((sources or {}).get('environment'))} Keys: {keys}.\")" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|194-196": [ - " return resolve_requester(who, on_behalf_of, self.directory, self.identity.get(\"requireEmployeeId\", True),", - " self.identity.get(\"requireOnBehalfOf\", False),", - " self.identity.get(\"automationRoles\", [\"cmapi-onboarding\"]))" - ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|292-292": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|196-203": [ + " def requester_for(self, who: Identity, on_behalf_of: str | None) -> Requester:", + " try:", + " requester = resolve_requester(who, on_behalf_of, self.directory, self.identity.get(\"requireEmployeeId\", True),", + " self.identity.get(\"requireOnBehalfOf\", False),", + " self.identity.get(\"automationRoles\", [\"cmapi-onboarding\"]))", + " except DirectoryUnavailable as exc:", + " raise directory_unavailable(exc) from exc", + " return self.with_client_owners(requester, warn=bool(on_behalf_of))" + ], + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|325-325": [ " self.cfg.roles.require(who, \"namespaces:create\" if action == \"create\" else \"namespaces:write\", env)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|298-298": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|331-331": [ " direct = self.requester_for(who, body.get(\"onBehalfOf\"))" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|307-307": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|345-345": [ " operator = self.cfg.roles.is_operator(who, env)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|611-611": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|649-649": [ " self.cfg.roles.require(who, \"namespaces:write\", env)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|728-728": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|766-766": [ " self.cfg.roles.require(who, ADOPT_PERMISSION, env)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|888-888": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|926-926": [ " requirement=requirement_to_json(req), requester=plan.requester.record(), requester_sub=plan.requester.sub," ], "docs/14-authorization.md|cmapi/src/cmapi/core/problem_docs.py|114-114": [ @@ -524,36 +551,36 @@ "docs/14-authorization.md|cmapi/src/cmapi/core/problem_docs.py|115-115": [ " \"on-behalf-of-required\": \"Name the person in `onBehalfOf`. A service client must say for whom it calls.\"," ], - "docs/14-authorization.md|cmapi/src/cmapi/core/views.py|25-27": [ - " # submittedBySub is a stable identifier the ledger needs (self-approval through onBehalfOf); it is not", - " # part of the public contract, so it stays in the row and out of the response.", - " \"approval\": approval_view(req, ledger), \"requester\": {k: v for k, v in row.requester.items() if k != \"submittedBySub\"}," + "docs/14-authorization.md|cmapi/src/cmapi/core/views.py|26-28": [ + " # submittedBySub and clientOwners are what the ledger needs (self-approval through onBehalfOf, #789); they are not", + " # part of the public contract, so they stay in the row and out of the response.", + " \"approval\": approval_view(req, ledger), \"requester\": public_record(row.requester)," ], - "docs/14-authorization.md|cmapi/src/cmapi/main.py|201-202": [ + "docs/14-authorization.md|cmapi/src/cmapi/main.py|224-225": [ " app.include_router(health.router)", " app.include_router(health.version_router)" ], - "docs/14-authorization.md|cmapi/src/cmapi/main.py|206-210": [ + "docs/14-authorization.md|cmapi/src/cmapi/main.py|229-233": [ " authed_routers = (me.router, requests.router, operations.router, admin.router, *cfg.plugins.routers())", " # Each route that takes a token takes one from its caller's bucket, after the sign-in (routers/__init__.py, rate_limit;", " # #689). The routes with no token (the version, health, the problem pages, the docs) have no caller to count.", " for r in authed_routers:", " app.include_router(r, dependencies=[Depends(authed), Depends(limited)])" ], - "docs/14-authorization.md|cmapi/src/cmapi/main.py|243-244": [ + "docs/14-authorization.md|cmapi/src/cmapi/main.py|266-267": [ " if s.metrics_port:", " start_metrics(s.metrics_port, ctx.cfg.name, s.component)" ], - "docs/14-authorization.md|cmapi/src/cmapi/main.py|287-289": [ + "docs/14-authorization.md|cmapi/src/cmapi/main.py|311-313": [ " @app.exception_handler(Problem)", " async def problem_handler(_: Request, exc: Problem) -> Response:", " return problem_response(exc, dict(unauthenticated_headers(exc)))" ], - "docs/14-authorization.md|cmapi/src/cmapi/main.py|389-390": [ + "docs/14-authorization.md|cmapi/src/cmapi/main.py|413-414": [ " if docs_enabled:", " _add_docs(app, ctx, docs_cfg, authed, problem_response)" ], - "docs/14-authorization.md|cmapi/src/cmapi/main.py|416-430": [ + "docs/14-authorization.md|cmapi/src/cmapi/main.py|440-454": [ "def _add_problem_pages(app: FastAPI, ctx: AppContext, problem_base: str) -> None:", " \"\"\"/problems and /problems/{code}: what the `type` of a problem resolves to (RFC 9457, section 4; #182).", "", @@ -570,10 +597,10 @@ " raise Problem(404, \"object-not-found\", \"No such problem type. /problems lists each one\")", " return HTMLResponse(problem_html(code, problem_base, ctx.cfg.name))" ], - "docs/14-authorization.md|cmapi/src/cmapi/main.py|442-442": [ + "docs/14-authorization.md|cmapi/src/cmapi/main.py|466-466": [ " guard = [] if docs_cfg.get(\"public\", True) else [Depends(authed), Depends(rate_limit(authed))]" ], - "docs/14-authorization.md|cmapi/src/cmapi/main.py|493-495": [ + "docs/14-authorization.md|cmapi/src/cmapi/main.py|517-519": [ " def docs_redirect() -> Response:", " return get_swagger_ui_oauth2_redirect_html()", "" @@ -895,7 +922,7 @@ "docs/15-keycloak-integration.md|cmapi/src/cmapi/core/identity/claims.py|80-80": [ " groups=frozenset(claims.get(\"groups\", []))," ], - "docs/15-keycloak-integration.md|cmapi/src/cmapi/main.py|199-200": [ + "docs/15-keycloak-integration.md|cmapi/src/cmapi/main.py|222-223": [ " swagger_ui_init_oauth={\"clientId\": \"cmapi-docs\", \"usePkceWithAuthorizationCodeGrant\": True,", " \"scopes\": \"openid\"})" ], @@ -1049,10 +1076,10 @@ "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|129-129": [ " def by_idempotency(self, caller_sub: str, key: str) -> ChangeRequestRow | None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|166-166": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|172-172": [ " def insert(self, row: ChangeRequestRow, first_event: E, by: str, note: str = \"\") -> ChangeRequestRow:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|194-199": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|200-205": [ " def event(self, row: ChangeRequestRow, event: str, by: str, note: str = \"\", detail: Mapping[str, Any] | None = None) -> None:", " self.s.add(RequestEventRow(request_id=row.request_id, event=event, status=row.status, by=by, note=note,", " detail=dict(detail) if detail else None))", @@ -1060,46 +1087,46 @@ "", " def move(self, row: ChangeRequestRow, event: E, by: str, note: str = \"\", **kw: Any) -> S:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|199-199": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|205-205": [ " def move(self, row: ChangeRequestRow, event: E, by: str, note: str = \"\", **kw: Any) -> S:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|243-243": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|249-249": [ " def ledger(self, row: ChangeRequestRow) -> ApprovalLedger | None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|257-257": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|267-267": [ " def record_approval(self, row: ChangeRequestRow, who: Identity, comment: str, relayed_by: str | None," ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|268-268": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|278-278": [ " def record_rejection(self, row: ChangeRequestRow, who: Identity, comment: str, decided_for: str) -> None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|280-280": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|290-290": [ " def enqueue(self, kind: str, *, request_id: str | None = None, cluster_id: str = \"\", delay: float = 0," ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|293-293": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|303-303": [ " def claim(self, worker_id: str, lease_seconds: int = 300) -> JobRow | None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|306-306": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|316-316": [ " def assert_lease(self, job_id: int, worker_id: str, generation: int) -> None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|365-365": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|375-375": [ " def record(self, actor: Identity, action: str, target: str, detail: Mapping[str, Any] | None = None) -> None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|369-369": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|379-379": [ " def recent(self, limit: int = 200) -> list[AuditEventRow]:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|377-377": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|387-387": [ " def get(self, name: str) -> dict[str, Any] | None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|381-381": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|391-391": [ " def value(self, name: str) -> dict[str, Any] | None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|387-387": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|397-397": [ " def set(self, name: str, value: Mapping[str, Any], by: str) -> None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|401-401": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|411-411": [ " def load(self, issuer: str) -> list[dict[str, Any]] | None:" ], - "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|406-406": [ + "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|416-416": [ " def save(self, issuer: str, keys: list[dict[str, Any]]) -> None:" ], "docs/16-data-model.md|cmapi/src/cmapi/core/db/repo.py|85-85": [ @@ -1574,7 +1601,7 @@ "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/clients/policyreports.py|38-38": [ "POLICY_KINDS = (\"ValidatingPolicy\",)" ], - "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|261-267": [ + "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|294-300": [ " def workload_counts(self, cluster_id: str, ns: str) -> tuple[int, int]:", " \"\"\"Pods and PVCs in a namespace, for the delete thresholds. A live read: unknown is 503, never 0.\"\"\"", " client = self.registry.cache(cluster_id).client", @@ -1583,7 +1610,7 @@ " return (len(client.list(\"Pod\", namespace=ns)[\"items\"]),", " len(client.list(\"PersistentVolumeClaim\", namespace=ns)[\"items\"]))" ], - "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|467-474": [ + "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|505-512": [ " # A quota change on an existing namespace reads its live 14-day usage (docs/01, \"Quota changes on existing namespaces\");", " # nothing else does: \"Never queried while creating a namespace or setting its first quota\" (docs/01, Thanos on onboarding).", " usage_view, usage_facts = None, {}", @@ -1593,7 +1620,7 @@ " if old_hard.keys() != hard.keys() or any(qty(old_hard[k]) != qty(hard[k]) for k in hard):", " usage_view, usage_facts = plan_usage(self.usage.namespace(cluster_id, ns), old_hard, hard)" ], - "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|691-701": [ + "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|729-739": [ " def _unadopted_counts(self, cluster_id: str, ns: str) -> dict[str, int | None]:", " \"\"\"D2: how many ServiceAccounts and RoleBindings the namespace has, which the adoption leaves unmanaged. A kind that", " cannot be read is null (not known), never 0.\"\"\"", diff --git a/docs/reviews/2026-12-01-issue-789/design.md b/docs/reviews/2026-12-01-issue-789/design.md new file mode 100644 index 00000000..15b2d999 --- /dev/null +++ b/docs/reviews/2026-12-01-issue-789/design.md @@ -0,0 +1,128 @@ +# #789: the owners of a service client may not decide what it sends + +Part of story #18. The implementer was Opus 5.5 at `high`, and wrote every commit of the pull request. This record holds the +design choices, their sources, and the options that were not taken. The choice of where owners come from is the owner's +(issue #789, comment of 2026-12-01); the research behind it is in the coordinator's record of that day. It is not reopened +here. + +## What was wrong + +docs/01, "Approval of record": the approver is "not an owner of the svc client that asked". `ApprovalLedger` had the check +(`client_owner_subs`), and `RequestRepo.ledger`, the only constructor outside the tests, gave it no owners, because cmapi had +no record of who owns a client. Where the rule has `selfApproval: false`, a person who holds a client's credentials could have +the client file a request for jane (`onBehalfOf`) and then approve or reject it with their own token. + +## The owner's decision (2026-12-01) + +1. Owners come from the instance configuration: `identity.clientOwners: {: [usernames or groups]}`, reviewed in + Git. Usernames are resolved to `sub` through the DirectoryProvider (view-users), so cmapi needs no new Keycloak privilege. +2. A client that sends `onBehalfOf` and has no entry keeps the rule from before: allowed, with a warning that names it. + +## Sources + +| Source | What it says | Fetched | +|---|---|---| +| Keycloak, `UsernameProhibitedCharactersValidator.java`, | `PATTERN = Pattern.compile("^[^<>&\"'\\s\\v\\h$%!#?§,;:*~/\\\\|^=\\[\\]{}()`\\p{Cntrl}]+$")`: a username holds no `/`, no white space and no control character | 2026-12-01 | +| Keycloak, `keycloak-default-user-profile.json`, | The `username` attribute's `validations` hold `"username-prohibited-characters": {}`: the validator above is on by default (also on `release/26.0`) | 2026-12-01 | +| Keycloak, `GroupMembershipMapper.java`, | `full.path`, "Full group path": "Include full path to group i.e. /top/level1/level2". cmapi's `cmapi-identity` scope maps the groups this way (docs/15: `groups`, for example `/cmapi/app-cmapi-rbac-requester`) | 2026-12-01 | +| OWASP Secure Coding Practices, Quick Reference Guide, Checklist, "Access control", | "Access controls should fail securely"; "Deny all access if the application cannot access its security configuration information" | 2026-12-01 | +| RFC 9110, sections 15.6.1 and 15.6.4, | 500: "the server encountered an unexpected condition that prevented it from fulfilling the request". 503: "the server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. The server MAY send a Retry-After header field" | 2026-12-01 | +| cmapi docs/14, "Step 5", and `RequestRepo` (`requirement_from_json`) | "A request keeps the path that it was decided under, so a change of the template does not move the approvers of an open request" | in the repository | + +## Decisions + +### 1. A username or a group, told apart by `/` + +An entry that starts with `/` is a Keycloak group by its full path, compared with the `groups` claim of the person who +decides; any other entry is a username. Keycloak's default user profile refuses `/` in a username (the validator above), and +the token carries groups by full path (the mapper above, docs/15), so the two cannot be confused and the setting stays the +one list the owner chose. The start refuses an entry that cannot be either: not a string, empty, a username with white space +or a control character, or a group path that is only `/` or holds a control character. A group's name may hold a space in +Keycloak, so a space is allowed in a group path. `[]` is allowed: it says the client has no owners and silences the warning. + +### 2. Resolved when the client sends the request, and stored with it + +The owners are resolved when the request is planned (`Pipeline.requester_for` and the operations' `submitted_by` path, through +`Pipeline.with_client_owners`) and stored in the request's `requester` record as `clientOwners: {client, subs, groups}`, beside +`submittedBySub`. `RequestRepo.ledger` reads them back. Reasons: + +- It is how cmapi already treats the other inputs of a decision: the requirement and the group path are stored with the + request, so that a later change of the configuration does not move who may decide a request already filed (docs/14). The + owners are the people who controlled the client when it filed, which is the conflict the check is about. +- Decision-time resolution would put a Keycloak call on every `:approve` and `:reject` and every view of a request. Submit + time already needs the directory for `onBehalfOf`, so no route gains a dependency it did not have. +- The record is JSONB: no migration (none is added; the head stays 0014 on this branch). + +A group is stored by name and compared with the decider's token at the decision, since membership is the token's. Requests +filed before this version have no `clientOwners`: they were filed when no owner was configured anywhere, and keep the rule of +that time until they are decided or time out (`timeoutHours`, 8 to 24 hours in the reference rules). + +The check covers any request that a service client sends: for another person, in its own name, or as the operations' client +(`svc-cmapi-workflows`) when an entry names its owners. docs/01 says "an owner of the svc client that asked", without a +condition on `onBehalfOf`. Like the submitter, the owners may decide where the rule has `selfApproval: true`. + +### 3. An unknown username is never dropped + +A username that the directory does not know refuses each request of that client: 500 `internal-error`, since the fault is the +instance's configuration and not the caller's request (RFC 9110: "an unexpected condition that prevented it from fulfilling +the request"), and the log line `client_owner_unknown` (error) names the client and +the username with the answer's request ID. Dropping the name would turn the check off for that owner in silence, which is what +OWASP's "Access controls should fail securely" rules out. 500 `internal-error` is already a documented answer of every +operation, so the API document does not change, and its action ("give the `X-Request-Id` ... to the platform team: the log +line with that ID has the cause") is the right one. A 422 was not taken: it tells the caller to change the request, which it +cannot. + +Two checks come earlier. Usernames with no directory (no `CMAPI_DIRECTORY_CLIENT_SECRET`, or `identity.directory` other than +`keycloak`) stop the start (`core/context.py`), since no request of those clients could be filed. And the API's start looks up +each username once and logs `client_owner_unknown` for each one it does not find, or `client_owners_unchecked` when the +directory cannot be reached; the start goes on, because whether a user exists is a fact of Keycloak, not of the files. + +A directory that cannot be reached and has no cached answer answers 503 `idp-unavailable` with `retryAfter` 30, as +`GET /api/v1/directory/users/{username}` does. + +### 4. A client with no entry: allowed, and named + +What cmapi can know at the start is the clients that its configuration names (`approval-rules.yaml`, an auto-approval policy's +`requester.clients`) and the clients that have filed a request for another person before (`change_requests`, `requester_kind` +`service` with `submittedByClient`). The API's start names each one without an entry in one `client_without_owners` warning. +Any other client is unknown until it calls, so it is named the first time it sends `onBehalfOf`, once in each process, in a +`client_without_owners` warning with the same fields. A client in its own name with no entry is not logged: the client itself +is the requester and is refused as such. + +### 5. The owners stay out of every response + +`clientOwners` is the ledger's, as `submittedBySub` is: `public_record` (`core/identity/checks.py`) leaves both out of the +plan's answer and the request's view, so the API contract does not change. + +## A defect found on the way + +#798 (sev:low). A requester's `onBehalfOf` lookup with Keycloak down and the name not cached raised `DirectoryUnavailable` out +of every handler: 500 `internal-error`, logged as `unhandled`. It now answers 503 `idp-unavailable`, in the same lines that the owners' lookup uses +(`Pipeline.requester_for`). `test_a_directory_that_cannot_be_reached_is_idp_unavailable` failed before the change. + +## Tests + +`cmapi/tests/service/test_client_owners_789.py` (12 tests) and `cmapi/tests/core/test_client_owners_789.py` (15 tests). The +proof of #789 is `test_an_owner_of_the_client_cannot_approve_or_reject_what_it_filed_for_someone`, by username and by group, for +`:approve` and for `:reject`: four cases, each 200 before the fix and 409 `self-approval` after. +The output before and after the change is in `tests-before-after.md` beside this record. + +## What the review changed (2026-12-01) + +Reviewer 1: Codex, gpt-6.2-astra xhigh (no test run: its sandbox refused `sysctl`). Reviewer 2: Fable 5.2. The coordinator read +every production hunk of reviewer 2's `final.diff`, applied it with `patch -p1 -F0` and found the twelve files byte-identical to +reviewer 2's tree (`cmp`). + +| Finding | Ruling | +|---|---| +| R1 High: an operation's step loses the starting client's owners | Accepted, simplified. Measured on head: a service client with owner kim starts an operation, and kim's `:approve` of the step's request answered 200. The step now stores `starterClientOwners` beside `clientOwners`, and the ledger refuses both (the RFC 8693 §1.1 rule `ApprovalRules.decide` already applies); 409 `self-approval` with the fix | +| R1 Medium (R2: worse, a regression of this PR): directory transport errors | Accepted, narrowed. On head, with a username owner configured, the API did not start while Keycloak was down: `httpx.ConnectError` is not an `OSError`, and a gateway's HTML 502 raised `JSONDecodeError`. Any non-200 search answer was read as "no such user". Now each is DirectoryUnavailable (503 `idp-unavailable`, #798) | +| R1 High: a revert loses who asked for it | True, pre-existing, needs no client: filed #807 (Medium, security), started at once | +| R1 High: read the directory fresh for each owner on every filing | Rejected: it removes the decided 15-minute cache (docs/01:354). A username reaches a new `sub` only by delete and re-create. Filed in #808 | +| R1 High and Medium: `examples/local` reference app | Out of this PR: a separate app that never had these checks. Filed #809 | +| R1 Medium: `clientOwners: null`; a token with no `azp`; a 10 s start budget | Rejected: null means absent for every key; Keycloak always sets `azp` (`TokenManager.initToken`); the first directory failure already ends the start loop. The first and third are in #808 | +| R1 Low: username grammar | In #808 | + +Reviewer 2's runs: service `test_client_owners_789.py` 18 passed (head code with the new tests: 6 failed); core 21 passed (head +code: 5 failed); `test_reject_decision_779_780` 8, `test_review_c_authz` 13, `test_operations_review_774` 20 passed on head and on +the final tree. diff --git a/docs/reviews/2026-12-01-issue-789/tests-before-after.md b/docs/reviews/2026-12-01-issue-789/tests-before-after.md new file mode 100644 index 00000000..ade91796 --- /dev/null +++ b/docs/reviews/2026-12-01-issue-789/tests-before-after.md @@ -0,0 +1,104 @@ +# #789 tests, before and after + +Run by the implementer (Opus 5.5 at high) on the service suite's PostgreSQL 16 (127.0.0.1:55432, database cmapi_t264), no cluster, one file at a time with the 1-minute load under 16, on 2026-12-01. + +## Service: `cmapi/tests/service/test_client_owners_789.py` + +**Before**: the two defect sites put back as on main 03cda30c, everything else of this change in place (so the test file imports): `RequestRepo.ledger` passes no owners (the #789 site), and `Pipeline.requester_for` has no handler for `DirectoryUnavailable` (the #798 site). + +``` +# load at start: { 12.71 14.08 14.06 } +# defect sites reverted: RequestRepo.ledger passes no owners; requester_for has no DirectoryUnavailable handler +FFFF..F.F... [100%] +=================================== FAILURES =================================== +E AssertionError: {"clusterId":"CRC","requestId":"req-20261201-0001","instance":"nonprod","namespace":"payments-batch","env":"dev","plugin":"namespaces","action":"create","reason":null,"justification":"Payments service dev namespace","status":"approved","pla + assert (200, None) == (409, 'self-approval') + + At index 0 diff: 200 != 409 + Use -v to get more diff +---------------------------- Captured stdout setup ----------------------------- +----------------------------- Captured stdout call ----------------------------- +cmapi/tests/service/test_client_owners_789.py:88: AssertionError: {"clusterId":"CRC","requestId":"req-20261201-0001","instance":"nonprod","namespace":"payments-batch","env":"dev","plugin":"namespaces","action":"create","reason":null,"justification":"Payments s +E AssertionError: {"clusterId":"CRC","requestId":"req-20261201-0001","instance":"nonprod","namespace":"payments-batch","env":"dev","plugin":"namespaces","action":"create","reason":null,"justification":"Payments service dev namespace","status":"rejected","pla + assert (200, None) == (409, 'self-approval') + + At index 0 diff: 200 != 409 + Use -v to get more diff +---------------------------- Captured stdout setup ----------------------------- +----------------------------- Captured stdout call ----------------------------- +cmapi/tests/service/test_client_owners_789.py:88: AssertionError: {"clusterId":"CRC","requestId":"req-20261201-0001","instance":"nonprod","namespace":"payments-batch","env":"dev","plugin":"namespaces","action":"create","reason":null,"justification":"Payments s +E AssertionError: {"clusterId":"CRC","requestId":"req-20261201-0001","instance":"nonprod","namespace":"payments-batch","env":"dev","plugin":"namespaces","action":"create","reason":null,"justification":"Payments service dev namespace","status":"approved","pla + assert (200, None) == (409, 'self-approval') + + At index 0 diff: 200 != 409 + Use -v to get more diff +---------------------------- Captured stdout setup ----------------------------- +----------------------------- Captured stdout call ----------------------------- +cmapi/tests/service/test_client_owners_789.py:88: AssertionError: {"clusterId":"CRC","requestId":"req-20261201-0001","instance":"nonprod","namespace":"payments-batch","env":"dev","plugin":"namespaces","action":"create","reason":null,"justification":"Payments s +E AssertionError: {"clusterId":"CRC","requestId":"req-20261201-0001","instance":"nonprod","namespace":"payments-batch","env":"dev","plugin":"namespaces","action":"create","reason":null,"justification":"Payments service dev namespace","status":"rejected","pla + assert (200, None) == (409, 'self-approval') + + At index 0 diff: 200 != 409 + Use -v to get more diff +---------------------------- Captured stdout setup ----------------------------- +----------------------------- Captured stdout call ----------------------------- +cmapi/tests/service/test_client_owners_789.py:88: AssertionError: {"clusterId":"CRC","requestId":"req-20261201-0001","instance":"nonprod","namespace":"payments-batch","env":"dev","plugin":"namespaces","action":"create","reason":null,"justification":"Payments s +E AssertionError: {"clusterId":"CRC","requestId":"req-20261201-0001","instance":"nonprod","namespace":"payments-batch","env":"dev","plugin":"namespaces","action":"create","reason":null,"justification":"Payments service dev namespace","status":"approved","pla + assert (200, None) == (409, 'self-approval') + + At index 0 diff: 200 != 409 + Use -v to get more diff +---------------------------- Captured stdout setup ----------------------------- +----------------------------- Captured stdout call ----------------------------- +cmapi/tests/service/test_client_owners_789.py:128: AssertionError: {"clusterId":"CRC","requestId":"req-20261201-0001","instance":"nonprod","namespace":"payments-batch","env":"dev","plugin":"namespaces","action":"create","reason":null,"justification":"Payments +E AssertionError: {"type":"https://cmapi.ephico2real.com/problems/internal-error","title":"internal error","status":500,"detail":"The service failed. Give the X-Request-Id of this answer to the platform team","code":"internal-error"} + assert (500, 'internal-error', None) == (503, 'idp-unavailable', 30) + + At index 0 diff: 500 != 503 + Use -v to get more diff +---------------------------- Captured stdout setup ----------------------------- +----------------------------- Captured stdout call ----------------------------- +cmapi/tests/service/test_client_owners_789.py:154: AssertionError: {"type":"https://cmapi.ephico2real.com/problems/internal-error","title":"internal error","status":500,"detail":"The service failed. Give the X-Request-Id of this answer to the platform team","c +=========================== short test summary info ============================ +FAILED tests/service/test_client_owners_789.py::test_an_owner_of_the_client_cannot_approve_or_reject_what_it_filed_for_someone[by-username-approve] +FAILED tests/service/test_client_owners_789.py::test_an_owner_of_the_client_cannot_approve_or_reject_what_it_filed_for_someone[by-username-reject] +FAILED tests/service/test_client_owners_789.py::test_an_owner_of_the_client_cannot_approve_or_reject_what_it_filed_for_someone[by-group-approve] +FAILED tests/service/test_client_owners_789.py::test_an_owner_of_the_client_cannot_approve_or_reject_what_it_filed_for_someone[by-group-reject] +FAILED tests/service/test_client_owners_789.py::test_the_owners_are_those_of_the_time_it_was_filed +FAILED tests/service/test_client_owners_789.py::test_a_directory_that_cannot_be_reached_is_idp_unavailable +6 failed, 6 passed in 27.73s +``` + +The decisions the owners made before the fix, from the run's own `http` log lines (kim by username, bob by the group `/cmapi/team-payments`): + +``` + 1 "route": "/api/v1/requests/{request_id}:approve", "status": 200, "caller_sub": "sub-bob" + 2 "route": "/api/v1/requests/{request_id}:approve", "status": 200, "caller_sub": "sub-kim" + 1 "route": "/api/v1/requests/{request_id}:reject", "status": 200, "caller_sub": "sub-bob" + 1 "route": "/api/v1/requests/{request_id}:reject", "status": 200, "caller_sub": "sub-kim" +``` + +**After** (the committed change): + +``` +# load at start: { 13.99 14.57 14.27 } +............ [100%] +12 passed in 26.88s +``` + +## Core: `cmapi/tests/core/test_client_owners_789.py` + +Run with the core job's packages (`examples/local/requirements.txt`, which has no structlog: the new module logs nothing itself). Before: `core/approvals.py` as on main; the other 14 tests cover the new module and setting, which main does not have. + +``` +E TypeError: ApprovalLedger.__init__() got an unexpected keyword argument 'client_owner_groups' +cmapi/tests/core/test_client_owners_789.py:22: TypeError: ApprovalLedger.__init__() got an unexpected keyword argument 'client_owner_groups' +FAILED tests/core/test_client_owners_789.py::test_the_ledger_refuses_an_owner_by_sub_or_by_a_group_of_the_token +1 failed, 14 passed in 0.79s +``` + +After: + +``` +15 passed in 1.14s +``` diff --git a/examples/config/instance.yaml b/examples/config/instance.yaml index cd51f364..00e7dc94 100644 --- a/examples/config/instance.yaml +++ b/examples/config/instance.yaml @@ -24,6 +24,7 @@ instance: requireOnBehalfOf: false # bots (service-account clients) may request in their own name automationRoles: [cmapi-onboarding] # callers with these roles need no employee ID (cmapi-automation) groupPath: /cmapi/app-cmapi-rbac-{name} # the token's group for an approving group in approval-rules.yaml; a site with its own directory sets its own (docs/11) + # clientOwners: {svc-payments-ci: [jane, /cmapi/team-payments]} # who owns a service client: never decides what it sends (docs/18, #789) # email domains for the team DL: emailDomains in cluster-configs/policies/metadata-keys.yaml (format only; DLs are not looked up) git: repository: caas/cluster-configs-nonprod diff --git a/examples/instances/nonprod/instance.yaml b/examples/instances/nonprod/instance.yaml index 3b00d07b..f4cfcd9e 100644 --- a/examples/instances/nonprod/instance.yaml +++ b/examples/instances/nonprod/instance.yaml @@ -26,6 +26,7 @@ instance: requireOnBehalfOf: false # bots (service-account clients) may request in their own name automationRoles: [cmapi-onboarding] # callers with these roles need no employee ID (cmapi-automation) groupPath: /cmapi/app-cmapi-rbac-{name} # the token's group for an approving group in approval-rules.yaml; a site with its own directory sets its own (docs/11) + # clientOwners: {svc-payments-ci: [jane, /cmapi/team-payments]} # who owns a service client: never decides what it sends (docs/18, #789) # email domains for the team DL: emailDomains in cluster-configs/policies/metadata-keys.yaml git: repository: caas/cluster-configs-nonprod diff --git a/examples/instances/prod/instance.yaml b/examples/instances/prod/instance.yaml index 5d088881..0713c718 100644 --- a/examples/instances/prod/instance.yaml +++ b/examples/instances/prod/instance.yaml @@ -26,6 +26,7 @@ instance: requireOnBehalfOf: false # bots (service-account clients) may request in their own name automationRoles: [cmapi-onboarding] # callers with these roles need no employee ID (cmapi-automation) groupPath: /cmapi/app-cmapi-rbac-{name} # the token's group for an approving group in approval-rules.yaml; a site with its own directory sets its own (docs/11) + # clientOwners: {svc-payments-ci: [jane, /cmapi/team-payments]} # who owns a service client: never decides what it sends (docs/18, #789) # email domains for the team DL: emailDomains in cluster-configs/policies/metadata-keys.yaml git: repository: caas/cluster-configs-prod diff --git a/examples/instances/staging/instance.yaml b/examples/instances/staging/instance.yaml index 56c73156..0504c810 100644 --- a/examples/instances/staging/instance.yaml +++ b/examples/instances/staging/instance.yaml @@ -26,6 +26,7 @@ instance: requireOnBehalfOf: false # bots (service-account clients) may request in their own name automationRoles: [cmapi-onboarding] # callers with these roles need no employee ID (cmapi-automation) groupPath: /cmapi/app-cmapi-rbac-{name} # the token's group for an approving group in approval-rules.yaml; a site with its own directory sets its own (docs/11) + # clientOwners: {svc-payments-ci: [jane, /cmapi/team-payments]} # who owns a service client: never decides what it sends (docs/18, #789) # email domains for the team DL: emailDomains in cluster-configs/policies/metadata-keys.yaml git: repository: caas/cluster-configs-staging