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
26 changes: 26 additions & 0 deletions backend/tests/test_shared_staff_scope.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""Unbound or cross-profile shared staff proofs cannot grant native access."""

import pytest

from townlight_records.auth.desktop_session import (
NativeDesktopPrincipal,
shared_staff_scope,
validate_native_session,
)


def test_shared_principal_stays_inside_host_request_scope(tmp_path):
proof = "e" * 64
principal = NativeDesktopPrincipal("clerk@city.example", "City Clerk", "clerk", 20)
with shared_staff_scope(tmp_path, proof, principal):
actor = validate_native_session(proof, profile_root=tmp_path, now_unix_seconds=10)
assert actor.allows_module("townlight_meetings")
assert not actor.allows_module("townlight_records")
with pytest.raises(PermissionError):
validate_native_session(proof, profile_root=tmp_path / "different-profile", now_unix_seconds=10)
with pytest.raises(PermissionError):
validate_native_session("a" * 64, profile_root=tmp_path, now_unix_seconds=10)
with pytest.raises(PermissionError):
validate_native_session(proof, profile_root=tmp_path, now_unix_seconds=20)
with pytest.raises(PermissionError):
validate_native_session(proof, profile_root=tmp_path, now_unix_seconds=10)
23 changes: 23 additions & 0 deletions backend/townlight_records/auth/desktop_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from __future__ import annotations

from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
import hashlib
import hmac
Expand Down Expand Up @@ -49,6 +51,19 @@ def allows_module(self, module_id: str) -> bool:
return modules is None or module_id in modules


_shared_staff = ContextVar("desktop_shared_staff", default=None)


@contextmanager
def shared_staff_scope(profile_root: Path, proof: str, principal: NativeDesktopPrincipal):
"""Accept a host-authenticated staff identity only within its gated request."""
token = _shared_staff.set((profile_root, proof, principal))
try:
yield
finally:
_shared_staff.reset(token)


def _json_file(path: Path) -> object:
return json.loads(path.read_text(encoding="utf-8"))

Expand All @@ -70,6 +85,14 @@ def validate_native_session(
denied = "Sign in with an authorized Townlight desktop account."
if not isinstance(proof, str) or len(proof) != 64:
raise PermissionError(denied)
shared = _shared_staff.get()
if shared is not None:
root, expected_proof, principal = shared
now = int(time.time()) if now_unix_seconds is None else now_unix_seconds
if (root != profile_root or not proof.isascii() or not hmac.compare_digest(proof, expected_proof)
or principal.expires_at_unix_seconds <= now):
raise PermissionError(denied)
return principal
try:
supplied = bytes.fromhex(proof)
config = profile_root / "config"
Expand Down
5 changes: 5 additions & 0 deletions backend/townlight_records/desktop_bridge/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -615,6 +615,11 @@ async def native_request_operation(
req = await session.get(RecordsRequest, request_id, with_for_update=True)
if req is None:
raise HTTPException(404, "Records request not found.")
expected = getattr(command.payload, "expectedResponseSha256", None)
if expected is not None:
current = artifacts.text_hash(req.response_draft or "")
if current != expected:
raise HTTPException(409, {"current_response_sha256": current})
try:
message = await apply_command(session, req, RecordsActor(actor, request.state.native_role), command)
except ValueError as error:
Expand Down
2 changes: 2 additions & 0 deletions backend/townlight_records/desktop_bridge/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,10 +144,12 @@ class FeeWaiverPayload(NativePayload):
class DraftPayload(NativePayload):
responseDraft: str = Field(min_length=1)
citation: str = ""
expectedResponseSha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$")


class ApprovalPayload(NativePayload):
approvalNote: str = ""
expectedResponseSha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$")


class AssignCommand(NativePayload):
Expand Down
Loading