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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions server/identity/app/reviewers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""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."""
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]}
34 changes: 10 additions & 24 deletions server/memory/app/proposals.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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]] = {}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down
10 changes: 10 additions & 0 deletions tests/unit/test_proposals.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
126 changes: 126 additions & 0 deletions tests/unit/test_reviewer_rule.py
Original file line number Diff line number Diff line change
@@ -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() == []
Loading