feat(evidence): GET /evidence for the Galena archive; technical account fenced to it (Atrium#53)

Every round's file with its sha256 of every room on a Galena document. A person sees the rooms they
may enter; the archive's technical account (fixed id ARCHIVE_READER_ID, minted by the hub) sees all,
is audited as evidence.read, and gets 404 on every other route.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 13:06:59 +01:00
co-authored by Claude Opus 5.5
parent aaab5cf057
commit 6f2c6dba0e
7 changed files with 227 additions and 2 deletions
+5
View File
@@ -12,6 +12,7 @@ no-op instead of a crash.
from __future__ import annotations
import re
import uuid
from functools import lru_cache
from pathlib import Path
@@ -157,6 +158,10 @@ class Settings(BaseSettings):
# underscores no. A two-word app therefore has a schema `my_app` and a module slug `my-app`, and
# the scaffolder derives the second from the first so the default is already legal.
module_slug: str = "agora"
# The Archive's technical account (Atrium#53): the hub creates it under this fixed id, with no
# password, and Galena carries its read-only token. Here it reaches `GET /evidence` and nothing
# else (deps.get_current_user). An id, not an e-mail: nobody can register their way into it.
archive_reader_id: uuid.UUID = uuid.UUID("a2c41e00-0000-4000-8000-000000000053")
# Where people sign in when identity is shared — the hub's address as a BROWSER sees it, e.g.
# /atrium/ on the platform. Empty standalone (there is no hub), and empty is survivable on the
# platform too: the console then says where accounts live without linking to them. It is
+5
View File
@@ -29,6 +29,7 @@ from .enums import TokenScope
from .errors import AuthenticationError, AuthorizationError
from .models import AppUser
from .services import auth as auth_service
from .services import authz as authz_service
from .services import moderation as moderation_service
SESSION_COOKIE = get_settings().session_cookie_name
@@ -148,6 +149,10 @@ def get_current_user(request: Request, db: Session = Depends(get_db)) -> AppUser
# at the edge of both shapes with no second code path — so never make it depend on
# `shares_identity`.
moderation_service.assert_may_use(db, user)
# The Archive's technical account (Atrium#53) holds a platform credential, so without this it
# would reach every screen here. It reaches the evidence routes and is refused (404) elsewhere.
authz_service.assert_archive_reader_route(
user, getattr(request.scope.get("route"), "path", request.url.path))
request.state.credential_id = credential.id
request.state.credential_kind = credential.kind
+2 -2
View File
@@ -24,7 +24,7 @@ from .logging_config import configure_logging
from .models import SHARED_TABLES
from .observability import setup_observability
from .services import events as events_svc
from .routers import admin, auth, dashboard, guest, health, rooms, stats, users
from .routers import admin, auth, dashboard, evidence, guest, health, rooms, stats, users
API_PREFIX = "/api/v1"
@@ -129,7 +129,7 @@ if settings.cors_origins_list:
for router in (
health.router, auth.router, users.router, admin.router,
rooms.router, guest.router, dashboard.router, stats.router,
rooms.router, guest.router, dashboard.router, stats.router, evidence.router,
):
app.include_router(router, prefix=API_PREFIX)
+36
View File
@@ -0,0 +1,36 @@
"""The Archive's evidence contract (Atrium#53): what Galena copies into a contract's package.
Each item's `download` is a path under /api/v1/, same auth, always an attachment. The Archive's
technical account may reach these routes and nothing else here (`deps.get_current_user`).
"""
from __future__ import annotations
import uuid
from dredd_core.plain_files import response_headers
from fastapi import APIRouter, Depends, Path, Request, Response
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import extract_token, get_current_user
from ..models import AppUser
from ..services import evidence
router = APIRouter(tags=["evidence"])
@router.get("/evidence")
def list_evidence(document_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
out = evidence.for_document(db, user, document_id)
db.commit()
return out
@router.get("/evidence/rooms/{room_id}/rounds/{number}")
def round_file(room_id: uuid.UUID, request: Request, number: int = Path(ge=1, le=10_000),
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> Response:
data, name = evidence.round_file(db, user, room_id, number, token=extract_token(request))
db.commit() # the audit row of a technical-account read
media, headers = response_headers(name, download=True)
return Response(data, media_type=media, headers=headers)
+17
View File
@@ -29,6 +29,7 @@ from __future__ import annotations
from sqlalchemy.orm import Session as DbSession
from ..config import get_settings
from ..errors import NotFoundError
from ..models import AppUser
from . import moderation
@@ -63,3 +64,19 @@ def assert_moderator(db: DbSession, user: AppUser) -> AppUser:
moderator out of the job they were given. `deps.require_moderator` is the HTTP edge of this one.
"""
return moderation.assert_moderator(db, user)
# ── the Archive's technical account (Atrium#53) ───────────────────────────────
#: The only routes it may reach: the evidence a Galena archive package is collected from.
EVIDENCE_PREFIX = "/api/v1/evidence"
def is_archive_reader(user: AppUser) -> bool:
"""The hub's passwordless account Galena collects evidence with (fixed id, read-only token)."""
return user.id == get_settings().archive_reader_id
def assert_archive_reader_route(user: AppUser, route_path: str) -> None:
"""The technical account reads evidence and nothing else: 404 anywhere else, as for a stranger."""
if is_archive_reader(user) and not route_path.startswith(EVIDENCE_PREFIX):
raise NotFoundError("Not found.")
+76
View File
@@ -0,0 +1,76 @@
"""What Galena's Archive collects from this module for one document (Atrium#53, contract `evidence`).
`GET /evidence?document_id=` lists every round's file, with its sha256, of every negotiation room on
that Galena document. A person sees the rooms they may enter (`rooms.can_enter`); the Archive's
technical account sees all of them, and each of its uses is audited (`evidence.read`).
"""
from __future__ import annotations
import uuid
from typing import Any
from dredd_core.document_ref import DocumentRef
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ..config import get_settings
from ..errors import NotFoundError
from ..models import AppUser, NegotiationRoom
from . import audit, authz, negotiation, rooms
def _audit(db: DbSession, user: AppUser, entity_type: str, entity_id: Any, detail: str) -> None:
if authz.is_archive_reader(user):
audit.record(db, actor_id=user.id, action="evidence.read", entity_type=entity_type,
entity_id=entity_id, detail=detail)
def _readable(db: DbSession, user: AppUser, room: NegotiationRoom) -> bool:
return authz.is_archive_reader(user) or rooms.can_enter(db, room, user)
def _rooms(db: DbSession, document_id: uuid.UUID) -> list[NegotiationRoom]:
return list(db.scalars(select(NegotiationRoom)
.where(NegotiationRoom.ref_document_id == document_id)
.order_by(NegotiationRoom.created_at, NegotiationRoom.id)))
def items_for(room: NegotiationRoom, rounds: list[dict]) -> list[dict[str, Any]]:
"""One item per round (`negotiation.rounds` rows: number, filename, sha256, commit_sha)."""
return [{"kind": "round", "name": r["filename"], "sha256": r["sha256"],
"source_id": f"{room.id}:{r['number']}", "commit_sha": r.get("commit_sha"),
"download": f"evidence/rooms/{room.id}/rounds/{r['number']}"} for r in rounds]
def _rounds(db: DbSession, room: NegotiationRoom) -> list[dict]:
out = []
for r in negotiation.rounds(db, room):
ref, name = negotiation.round_ref(db, room, r["number"])
out.append({"number": r["number"], "filename": name, "sha256": ref.sha256,
"commit_sha": ref.commit_sha if isinstance(ref, DocumentRef) else None})
return out
def for_document(db: DbSession, user: AppUser, document_id: uuid.UUID) -> dict[str, Any]:
"""The contract's answer: always 200, empty items and a note when nothing is there."""
items: list[dict[str, Any]] = []
for room in _rooms(db, document_id):
if _readable(db, user, room):
items += items_for(room, _rounds(db, room))
_audit(db, user, "document", document_id, f"{len(items)} items")
return {"module": get_settings().module_slug, "document_id": str(document_id),
"items": items,
"note": None if items else "Brak pokojów negocjacji tego dokumentu."}
def round_file(db: DbSession, user: AppUser, room_id: uuid.UUID, number: int, *,
token: str | None) -> tuple[bytes, str]:
room = db.get(NegotiationRoom, room_id)
if room is None or room.ref_document_id is None or not _readable(db, user, room):
raise NotFoundError("Not found.")
data, name = negotiation.round_bytes(db, room, number, token=token)
_audit(db, user, "negotiation_room", room.id, f"round {number}")
return data, name
__all__ = ["for_document", "items_for", "round_file"]
+86
View File
@@ -0,0 +1,86 @@
"""DB-free tests of the Archive's evidence contract (Atrium#53) and the technical account's fence."""
from __future__ import annotations
import uuid
from types import SimpleNamespace
import pytest
from fastapi.testclient import TestClient
from app import main
from app.config import get_settings
from app.db import get_db
from app.errors import NotFoundError
from app.services import audit, authz, evidence, rooms
from app.services import auth as auth_service
from app.services import moderation as moderation_service
DOC = uuid.uuid4()
READER = get_settings().archive_reader_id
ROUNDS = [{"number": 1, "filename": "umowa.docx", "sha256": "a" * 64, "commit_sha": "c" * 40},
{"number": 2, "filename": "umowa-v2.docx", "sha256": "b" * 64, "commit_sha": None}]
def test_items_for():
room = SimpleNamespace(id=uuid.uuid4())
items = evidence.items_for(room, ROUNDS)
assert items[1] == {"kind": "round", "name": "umowa-v2.docx", "sha256": "b" * 64,
"source_id": f"{room.id}:2", "commit_sha": None,
"download": f"evidence/rooms/{room.id}/rounds/2"}
assert items[0]["commit_sha"] == "c" * 40
@pytest.fixture
def two_rooms(monkeypatch):
found = [SimpleNamespace(id=uuid.uuid4()), SimpleNamespace(id=uuid.uuid4())]
audited = []
monkeypatch.setattr(evidence, "_rooms", lambda db, d: found)
monkeypatch.setattr(evidence, "_rounds", lambda db, room: ROUNDS)
monkeypatch.setattr(rooms, "can_enter", lambda db, room, user: room is found[0])
monkeypatch.setattr(audit, "record", lambda db, **kw: audited.append(kw))
return found, audited
def test_person_sees_rooms_they_may_enter(two_rooms):
found, audited = two_rooms
out = evidence.for_document(None, SimpleNamespace(id=uuid.uuid4()), DOC)
assert out["module"] == "agora" and len(out["items"]) == 2
assert all(i["source_id"].startswith(str(found[0].id)) for i in out["items"])
assert audited == []
def test_technical_account_sees_all_audited(two_rooms):
_found, audited = two_rooms
out = evidence.for_document(None, SimpleNamespace(id=READER), DOC)
assert len(out["items"]) == 4
assert audited == [{"actor_id": READER, "action": "evidence.read", "entity_type": "document",
"entity_id": DOC, "detail": "4 items"}]
def test_nothing_is_a_note(monkeypatch):
monkeypatch.setattr(evidence, "_rooms", lambda db, d: [])
out = evidence.for_document(None, SimpleNamespace(id=uuid.uuid4()), DOC)
assert out["items"] == [] and out["note"]
def test_fence():
with pytest.raises(NotFoundError):
authz.assert_archive_reader_route(SimpleNamespace(id=READER), "/api/v1/rooms")
authz.assert_archive_reader_route(SimpleNamespace(id=READER), "/api/v1/evidence")
authz.assert_archive_reader_route(SimpleNamespace(id=uuid.uuid4()), "/api/v1/rooms")
@pytest.mark.parametrize("path, status", [("/api/v1/rooms", 404), ("/api/v1/auth/me", 404),
(f"/api/v1/evidence?document_id={DOC}", 200)])
def test_technical_account_reaches_only_evidence(monkeypatch, path, status):
reader = SimpleNamespace(id=READER, is_admin=False, is_active=True)
cred = SimpleNamespace(scope="read", id=uuid.uuid4(), kind="app_token")
monkeypatch.setattr(auth_service, "resolve_session_full", lambda db, t: (reader, cred))
monkeypatch.setattr(moderation_service, "assert_may_use", lambda db, u: None)
monkeypatch.setattr(evidence, "for_document", lambda db, u, d: {"items": []})
main.app.dependency_overrides[get_db] = lambda: SimpleNamespace(commit=lambda: None)
try:
r = TestClient(main.app).get(path, headers={"Authorization": "Bearer t"})
finally:
main.app.dependency_overrides.clear()
assert r.status_code == status, r.text