diff --git a/server/identity/app/reviewers.py b/server/identity/app/reviewers.py new file mode 100644 index 0000000000..2f676da7d1 --- /dev/null +++ b/server/identity/app/reviewers.py @@ -0,0 +1,76 @@ +"""Who may accept proposed content: a person who administers the namespace, acts under +their own name and wrote none of what they review. + +`reviewer_subjects` refuses with a typed reason and the calling op words its own +answer, so the rule names no kind of content.""" + +from __future__ import annotations + +from collections.abc import Iterable +from typing import TYPE_CHECKING, Literal + +from server.auth import aliases, context +from server.auth.authz import CachedGate +from server.core.ch import sequential_reads +from server.memory.app.provenance import writer_actor +from server.operations.base import Role + +if TYPE_CHECKING: + from server.auth.jwt import AuthInfo + +# Why a caller may not review, in the order the rule tests: no principal or subject, a +# service account, an actor that is not the token's own, no admin role on the namespace. +Reason = Literal["signed_out", "service_account", "actor", "role"] + + +class NotAReviewer(Exception): + """The caller may not review: `reason` is the first test of the rule it fails.""" + + def __init__(self, reason: Reason) -> None: + super().__init__(reason) + self.reason = reason + + +def person() -> AuthInfo | None: + """The request's principal when it is signed in under a subject and is not a + service account.""" + auth = context.current_auth() + if auth is None or not auth.subject or auth.is_service_account: + return None + return auth + + +def independent(reviewers: set[str], authors: Iterable[str]) -> bool: + """Whether the reviewer whose subjects are `reviewers` (`reviewer_subjects`) is none + of `authors`, compared case-folded. Never for an empty `authors`: a caller that + cannot say who wrote the content cannot show its reviewer is someone else. + + A blank author names no principal (`trust.subject_of` gives `''` for a pipeline's + actor) and is never the reviewer, so a caller for which blank means an unknown + author drops it or refuses first, as `memory.proposal_decide` does with + `trust.is_valid_actor`.""" + folded = {author.casefold() for author in authors} + return bool(folded) and folded.isdisjoint(reviewers) + + +async def reviewer_subjects(org: str, namespace: str, actor: str) -> set[str]: + """The case-folded subject and aliases of the caller, who must be a person + administering `namespace`. `actor`, the name the decision is recorded under, must be + the token's own (`writer_actor`). Raises `NotAReviewer` with the first test failed, + in the order of `Reason`. + + The aliases are read with sequential consistency and a failed read raises: an alias + missing from the set would make its author look independent.""" + auth = person() + if auth is None: + # A principal with a subject that is no person is a service account. + principal = context.current_auth() + signed_in = principal is not None and bool(principal.subject) + raise NotAReviewer("service_account" if signed_in else "signed_out") + if actor != writer_actor(): + raise NotAReviewer("actor") + if not await CachedGate(auth, org).admits(namespace, Role.ADMIN): + raise NotAReviewer("role") + with sequential_reads(): + tied = await aliases.read_aliases(org, auth.subject, None) + return {subject.casefold() for subject in [auth.subject, *tied]} diff --git a/server/memory/app/proposals.py b/server/memory/app/proposals.py index 6af18685ab..051f438b9f 100644 --- a/server/memory/app/proposals.py +++ b/server/memory/app/proposals.py @@ -26,6 +26,7 @@ from fastapi import HTTPException +from server.identity.app.reviewers import NotAReviewer, independent, reviewer_subjects from server.identity.domain.read_scope import WHOLE_NAMESPACE, ReadFilters, scope_and from server.memory.app import webhooks from server.memory.domain.proposal_policy import ProposalPolicy, parse_policy @@ -37,34 +38,19 @@ Decision = Literal["accept", "reject"] -async def _reviewer_subjects(org: str, namespace: str, actor: str) -> set[str]: - """Acceptance needs an authenticated human admin, including internal callers.""" - from server.auth.aliases import read_aliases - from server.auth.authz import CachedGate - from server.auth.context import current_auth - from server.memory.app.provenance import writer_actor - from server.operations.base import Role - - auth = current_auth() - if ( - auth is None - or not auth.subject - or auth.is_service_account - or actor != writer_actor() - or not await CachedGate(auth, org).admits(namespace, Role.ADMIN) - ): +async def _accepting_reviewer(org: str, namespace: str, actor: str) -> set[str]: + """The subjects of the caller accepting a proposal (`reviewer_subjects`), internal + callers included. Every refusal is one answer: it does not say which test failed.""" + try: + return await reviewer_subjects(org, namespace, actor) + except NotAReviewer as e: raise HTTPException( status_code=403, detail={ "code": "AUTH_INSUFFICIENT", "message": "A human administrator must review the proposal.", }, - ) - from server.core.ch import sequential_reads - - with sequential_reads(): - aliases = await read_aliases(org, auth.subject, None) - return {s.casefold() for s in [auth.subject, *aliases]} + ) from e _POLICY_CACHE: dict[tuple[str, str], tuple[float, ProposalPolicy]] = {} @@ -189,7 +175,7 @@ async def decide( import server.memory.store as memory_repo from server.memory.domain.proposal_review import reviewed_changes - reviewers = await _reviewer_subjects(org, namespace, actor) if decision == "accept" else set() + reviewers = await _accepting_reviewer(org, namespace, actor) if decision == "accept" else set() if ch is None: from server.core.ch import get_client @@ -269,7 +255,7 @@ def _approval_refusal(row: Any, decision: Decision, reviewers: set[str], approve if decision != "accept": return "" proposer = str(row.actor or "") - if not is_valid_actor(proposer) or subject_of(proposer).casefold() in reviewers: + if not is_valid_actor(proposer) or not independent(reviewers, {subject_of(proposer)}): return "an independent reviewer is required" if row.value_truncated or approved != sha256_value(row.value): return "proposal content must match approved_sha256" diff --git a/tests/unit/test_proposals.py b/tests/unit/test_proposals.py index 73944b2fd6..419141f025 100644 --- a/tests/unit/test_proposals.py +++ b/tests/unit/test_proposals.py @@ -521,6 +521,16 @@ async def linked(*args, **kwargs): assert not out[0].decided and ch.inserts == [] +def test_a_human_administrator_can_accept_what_a_pipeline_proposed(repo): + """A pipeline's actor names no principal, so every reviewer is independent of it.""" + repo["rows"]["p1"] = repo["rows"]["p1"].model_copy(update={"actor": "process:consolidation"}) + ch = _CH() + out = asyncio.run( + p.decide("o", "n", ["p1"], "accept", actor="human:t", approved_sha256={"p1": _HASH}, ch=ch) + ) + assert out[0].decided and len(ch.inserts) == 1 + + async def test_listing_decodes_the_native_fixed_string_hash(monkeypatch): from server.memory.api.models_proposals import MemoryProposalsInput from server.memory.app import proposals_ops diff --git a/tests/unit/test_reviewer_rule.py b/tests/unit/test_reviewer_rule.py new file mode 100644 index 0000000000..e5098b33b0 --- /dev/null +++ b/tests/unit/test_reviewer_rule.py @@ -0,0 +1,126 @@ +"""A review is decided by a person who administers the namespace, acts under their own +name and wrote none of what they review (`server.identity.app.reviewers`).""" + +from __future__ import annotations + +from typing import Any + +import pytest +from fastapi import HTTPException + +from server.auth.jwt import AuthInfo +from server.identity.app import reviewers +from server.memory.app import proposals +from server.operations.base import Role +from tests.unit.ch_fake import RecordingCH +from tests.unit.principals import NAMESPACE, ORG, acting_as, principal + +ALICE = principal("admin", subject="Alice", service_account=False) +ROBOT = principal("admin", subject="sa:robot") + +# (the reason, the caller, the actor the call names). The last three fail more than +# one test of the rule: the reason is the first test failed. +REFUSALS: list[tuple[str, AuthInfo | None, str]] = [ + ("signed_out", None, "human:Alice"), + ("signed_out", principal("admin", subject="", service_account=False), "human:"), + ("service_account", ROBOT, "process:sa:robot"), + ("actor", ALICE, "human:bob"), + ("role", principal("writer", subject="Alice", service_account=False), "human:Alice"), + ("signed_out", None, "process:sa:robot"), + ("service_account", principal("writer", subject="sa:robot"), "human:Alice"), + ("actor", principal("writer", subject="Alice", service_account=False), "human:bob"), +] +REFUSAL_IDS = [ + "no principal", + "no subject", + "service account", + "another actor", + "not an administrator", + "no principal, a process actor", + "service account, another actor, not an administrator", + "another actor, not an administrator", +] + + +@pytest.fixture() +def alias_reads(monkeypatch: pytest.MonkeyPatch) -> list[bool]: + """The gate answers from the token's role claim and the alias directory ties the + subject to one email. Returns, per alias read, whether it was sequential.""" + from server.auth import aliases, authz + from server.core.ch import sequential_reads_active + + async def admits(self: authz.CachedGate, namespace: str, role: Role) -> bool: + assert (self.org, namespace, role) == (ORG, NAMESPACE, Role.ADMIN) + return Role.ADMIN in self.auth.roles + + reads: list[bool] = [] + + async def read_aliases(org: str, subject: str, ch: Any) -> list[str]: + assert org == ORG + reads.append(sequential_reads_active()) + return [subject, "Alice@Example.com"] + + monkeypatch.setattr(authz.CachedGate, "admits", admits) + monkeypatch.setattr(aliases, "read_aliases", read_aliases) + return reads + + +@pytest.mark.parametrize(("reason", "auth", "actor"), REFUSALS, ids=REFUSAL_IDS) +async def test_each_refusal_has_its_reason( + alias_reads: list[bool], reason: str, auth: AuthInfo | None, actor: str +) -> None: + """A refused caller gets no reviewer set and no alias read, and the reason is the + first test failed: signed out, service account, actor, role.""" + with acting_as(auth), pytest.raises(reviewers.NotAReviewer) as refused: + await reviewers.reviewer_subjects(ORG, NAMESPACE, actor) + assert refused.value.reason == reason + assert alias_reads == [] + + +async def test_another_actor_is_refused(alias_reads: list[bool]) -> None: + """An administrator reviews only as the actor their token gives: another name, kind + or case is refused.""" + with acting_as(ALICE): + subjects = await reviewers.reviewer_subjects(ORG, NAMESPACE, "human:Alice") + assert subjects == {"alice", "alice@example.com"} + assert alias_reads == [True] + for other in ("human:bob", "process:Alice", "human:alice", "Alice", ""): + with pytest.raises(reviewers.NotAReviewer) as refused: + await reviewers.reviewer_subjects(ORG, NAMESPACE, other) + assert refused.value.reason == "actor" + assert alias_reads == [True] + + +def test_no_author_is_not_independent() -> None: + """Content with no author, or with an author who is the reviewer under an alias in + another case, has no independent reviewer.""" + subjects = {"alice", "alice@example.com"} + assert reviewers.independent(subjects, {"bob"}) + assert not reviewers.independent(subjects, set()) + assert not reviewers.independent(subjects, {"ALICE@Example.com"}) + assert not reviewers.independent(subjects, {"bob", "Alice"}) + + +def test_a_person_is_signed_in_and_not_a_service_account() -> None: + with acting_as(ALICE): + assert reviewers.person() is ALICE + for auth in (None, ROBOT, principal("admin", subject="", service_account=False)): + with acting_as(auth): + assert reviewers.person() is None + + +@pytest.mark.parametrize(("reason", "auth", "actor"), REFUSALS, ids=REFUSAL_IDS) +async def test_proposal_refusal_is_unchanged( + alias_reads: list[bool], reason: str, auth: AuthInfo | None, actor: str +) -> None: + """`memory.proposal_decide` answers every reason with one 403, and the refused call + runs no statement.""" + ch = RecordingCH() + with acting_as(auth), pytest.raises(HTTPException) as refused: + await proposals.decide(ORG, NAMESPACE, ["candidate"], "accept", actor=actor, ch=ch) + assert refused.value.status_code == 403 + assert refused.value.detail == { + "code": "AUTH_INSUFFICIENT", + "message": "A human administrator must review the proposal.", + } + assert ch.statements() == []