fix/password-unicode-validation-20261111
add-index-html-10623938925177053894 arena/094f314c-aram chatgpt-phase1b2-autopilot codex/adr-future-connectors-pi-v1 codex/aram-account-note-source-trace-20261031 codex/aram-actions-node24-maintenance-20261031 codex/aram-analyst-review-workbook-20261031 codex/aram-bs-candidate-statement-20261031 codex/aram-cash-flow-direct-candidate-20261031 codex/aram-clean-reference-year-integrity-20261030 codex/aram-cross-statement-controls-20261031 codex/aram-equity-changes-candidate-20261031 codex/aram-five-statement-cli-20261031 codex/aram-five-statement-integration-20261031 codex/aram-five-statement-orchestrator-20261031 codex/aram-gate3-coverage-target-guard-20261030 codex/aram-gate3-hidden-xlsx-guard-20261030 codex/aram-gate3-integration-validation-20261030 codex/aram-gate3-mapping-change-preview-20261030 codex/aram-gate3-stale-note-guard-20261030 codex/aram-income-statement-candidate-20261031 codex/aram-manifest-referential-integrity-20261031 codex/aram-mapping-source-parser-20261101 codex/aram-multidimensional-mapping-20261101 codex/aram-multistatement-mapping-20261031 codex/aram-pipeline-manifest-schema-20261031 codex/aram-readonly-mapping-coverage-20261031 codex/aram-reconciliation-review-gate-20261031 codex/aram-same-flush-fiscal-lock-20261030 codex/aram-synthetic-windows-demo-20261031 codex/aram-trial-balance-diagnostic-20261031 codex/aram-windows-background-detail-search-20261031 codex/aram-windows-detail-review-20261031 codex/aram-windows-five-statement-pilot-20261031 codex/aram-windows-statement-figures-20261031 codex/gate-2a-pilot-workbook codex/gate-2a-pilot-workbook-6864754244772568979 codex/gate3-authenticated-principal-boundary-20261030 codex/gate3-authored-draft-staging-20261030 codex/gate3-carry-forward-preview-20261023 codex/gate3-draft-staging-audit-20261030 codex/gate3-mapping-batch-freshness-20261030 codex/gate3-mapping-batch-review-20261030 codex/gate3-mapping-core codex/gate3-mapping-coverage-20261023 codex/gate3-mapping-excel-20261023 codex/gate3-note-mapping-review-20261023 codex/gate3-signed-year-scope-20261030 codex/gate3-unapproved-proposal-storage-20261030 codex/payvast-mapping-discovery-20261023 codex/phase-2a-backend-foundation codex/phase-2b-post-merge-record codex/phase-2b-source-registration codex/phase-2b-source-registration-12955190277775369594 codex/post-gate2a-control-reconciliation codex/post-pr18-acceptance-record codex/project-control-foundation codex/t1-repo-hygiene-20261023 codex/t2-ci-hardening-20261023 codex/t3-explicit-migrations-20261023 codex/t6a-readonly-diagnostics-20261023 codex/v1-01-safety-gate-hardening codex/v1-year-isolation-followup-20261023 codex/windows-native-pilot-shell-20261030 docs/aram-master-control-plan-20261111 docs/aram-roadmap-dashboard-20261030 docs/financial-statement-reconciliation-1402-1404-20261110 feat/gate3-governed-mapping-20261101 feat/gate3-package9-1-security-20261103 feat/gate3-package9-isolated-20261103 fix/password-unicode-validation-20261111 governance/aram-5-1-3-controls-20261030 governance/role-based-operating-model jules-1168663913887856558-73b8a885 jules-gate-2b-mapping-workflow-foundation-4137724387867065330 phase-1b1-audit-report-7365389436990903239 phase-2a-backend-foundation-10237597358138521261 phase1b2-postmerge-metadata-fix refactor/drg-parent-year-id-15088443704684163304 source-data-cleanup
py 124 lines 5.14 KB
Raw
1 """Protected mapping HTTP operations.
2
3 A deployment MUST supply a trusted identity resolver and an isolated MappingStore.
4 The API never accepts actor, roles, or company permissions from request bodies.
5 """
6 from __future__ import annotations
7
8 from collections.abc import Callable
9
10 from fastapi import APIRouter, Depends, Header, HTTPException
11 from pydantic import BaseModel, Field
12
13 from aram_backend.mapping_access import AuthenticatedPrincipal, MappingAccess
14 from aram_backend.mapping_store import MappingStore
15 from aram_backend.mapping_workflow import MappingDecision, MappingWorkflowError
16
17 router = APIRouter(prefix="/api/v1/mapping", tags=["mapping"])
18 _identity_resolver: Callable[[str], AuthenticatedPrincipal | None] | None = None
19 _store: MappingStore | None = None
20
21
22 def configure_mapping_service(
23 *, store: MappingStore, identity_resolver: Callable[[str], AuthenticatedPrincipal | None]
24 ) -> None:
25 """Server-only composition root; never expose as a route."""
26 global _identity_resolver, _store
27 _store = store
28 _identity_resolver = identity_resolver
29
30
31 def reset_mapping_service() -> None:
32 """Explicitly disable service, including when a credential provider fails."""
33 global _identity_resolver, _store
34 _store = None
35 _identity_resolver = None
36
37
38 def _service() -> tuple[MappingStore, MappingAccess]:
39 if _store is None or _identity_resolver is None:
40 raise HTTPException(status_code=503, detail="mapping service not configured")
41 return _store, MappingAccess(_identity_resolver)
42
43
44 def _credential(authorization: str | None = Header(default=None)) -> str:
45 if not authorization or not authorization.startswith("Bearer "):
46 raise HTTPException(status_code=401, detail="Bearer authentication required")
47 token = authorization[7:]
48 if not token or token != token.strip():
49 raise HTTPException(status_code=401, detail="invalid bearer token")
50 return token
51
52
53 class Proposal(BaseModel):
54 mapping_id: str = Field(min_length=1)
55 account_full_code: str = Field(min_length=1)
56 target_statement: str = Field(min_length=1)
57 statement_section: str = Field(min_length=1)
58 note_number: str = Field(min_length=1)
59 subnote_code: str | None = None
60 source: str = "Manual"
61
62
63 class OwnerAcceptance(BaseModel):
64 reason: str = Field(min_length=15, max_length=2000)
65
66 class Revision(BaseModel):
67 target_statement: str = Field(min_length=1)
68 statement_section: str = Field(min_length=1)
69 note_number: str = Field(min_length=1)
70 subnote_code: str | None = None
71
72
73 def _apply(company: str, year: int, token: str, action):
74 store, access = _service()
75 try:
76 workspace, revision = store.load(company, year)
77 result = action(access, workspace, token)
78 store.save(workspace, revision)
79 return result
80 except MappingWorkflowError as exc:
81 message = str(exc)
82 if message in {"mapping access denied", "authenticated credential required"}:
83 raise HTTPException(status_code=403, detail="access denied") from exc
84 if "concurrent update" in message:
85 raise HTTPException(status_code=409, detail="concurrent update") from exc
86 raise HTTPException(status_code=422, detail=message) from exc
87
88
89 @router.post("/{company}/{year}/proposals", response_model=MappingDecision)
90 def propose(company: str, year: int, payload: Proposal, token: str = Depends(_credential)):
91 def action(access, workspace, credential):
92 return access.propose(credential, workspace, MappingDecision(
93 payload.mapping_id, company, year, payload.account_full_code,
94 payload.target_statement, payload.statement_section, payload.note_number,
95 payload.subnote_code, 1, "Draft", None, payload.source,
96 ))
97 return _apply(company, year, token, action)
98
99
100 @router.post("/{company}/{year}/{mapping_id}/review", response_model=MappingDecision)
101 def review(company: str, year: int, mapping_id: str, token: str = Depends(_credential)):
102 return _apply(company, year, token, lambda a, w, t: a.review(t, w, mapping_id))
103
104
105 @router.post("/{company}/{year}/{mapping_id}/approve", response_model=MappingDecision)
106 def approve(company: str, year: int, mapping_id: str, token: str = Depends(_credential)):
107 return _apply(company, year, token, lambda a, w, t: a.approve(t, w, mapping_id))
108
109
110 @router.post("/{company}/{year}/{mapping_id}/owner-accept", response_model=MappingDecision)
111 def owner_accept(company: str, year: int, mapping_id: str, payload: OwnerAcceptance,
112 token: str = Depends(_credential)):
113 """Exception acceptance; never equivalent to independent Approved status."""
114 return _apply(company, year, token,
115 lambda a, w, t: a.owner_accept(t, w, mapping_id, reason=payload.reason))
116
117 @router.post("/{company}/{year}/{mapping_id}/revise", response_model=MappingDecision)
118 def revise(company: str, year: int, mapping_id: str, payload: Revision,
119 token: str = Depends(_credential)):
120 return _apply(company, year, token, lambda a, w, t: a.revise(
121 t, w, mapping_id, target_statement=payload.target_statement,
122 statement_section=payload.statement_section, note_number=payload.note_number,
123 subnote_code=payload.subnote_code,
124 ))