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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion cmapi/src/cmapi/core/approvals.py
Original file line number Diff line number Diff line change
Expand Up @@ -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", [])}

Expand Down Expand Up @@ -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]:
Expand Down Expand Up @@ -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"
Expand Down
12 changes: 9 additions & 3 deletions cmapi/src/cmapi/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -171,14 +175,16 @@ 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:
problems.append(f"instance.clusterTokens: {exc}")
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]:
Expand Down
33 changes: 27 additions & 6 deletions cmapi/src/cmapi/core/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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"),
Expand Down
18 changes: 14 additions & 4 deletions cmapi/src/cmapi/core/db/repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)))))

Expand Down Expand Up @@ -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})
Expand Down
20 changes: 20 additions & 0 deletions cmapi/src/cmapi/core/identity/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""
Expand All @@ -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!#$%&'*+/=?^_`{|}~.-]+$")

Expand All @@ -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:
Expand All @@ -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,
Expand Down
6 changes: 4 additions & 2 deletions cmapi/src/cmapi/core/identity/keycloak_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}
Expand Down
Loading
Loading