codex/windows-native-pilot-shell-20261030
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 199 lines 7.83 KB
Raw
1 """Author evidence bound to an authenticated, scoped UNREVIEWED staging request.
2
3 An actual FastAPI request MUST get principal from verified RSA-bearer Depends.
4 A user-constructed VerifiedPrincipal Python object is not authentication.
5 This is neither a human reviewer attestation nor financial approval.
6 """
7 from __future__ import annotations
8
9 from dataclasses import dataclass
10 from hashlib import sha256
11 import json
12
13 from fastapi import HTTPException
14 from sqlalchemy import (
15 CheckConstraint, Column, DateTime, ForeignKey, Integer, String,
16 Table, UniqueConstraint, func, insert, select,
17 )
18 from sqlalchemy.orm import Session
19
20 from aram_backend.authenticated_identity import VerifiedPrincipal
21 from aram_backend.mapping_batch_review import MappingBatchPreview
22 from aram_backend.mapping_draft_store import (
23 _proposal_metadata, mapping_review_drafts,
24 save_unreviewed_batch, get_unreviewed_batch,
25 )
26 from aram_backend.mapping_service import MappingValidationError
27 from aram_backend.mapping_year_authorization import require_year_access
28
29
30 class MappingAuthorConflict(MappingValidationError):
31 """A request key has legacy, missing or different-author attribution."""
32
33
34 mapping_draft_authors = Table(
35 "mapping_draft_authors", _proposal_metadata,
36 Column("id", Integer, primary_key=True),
37 Column("draft_id", Integer, ForeignKey(
38 mapping_review_drafts.c.id, ondelete="RESTRICT",
39 ), nullable=False),
40 Column("year_id", Integer, nullable=False),
41 Column("issuer", String(512), nullable=False),
42 Column("subject", String(128), nullable=False),
43 Column("role", String(32), nullable=False),
44 Column("company_code", String(64), nullable=False),
45 Column("fiscal_year", Integer, nullable=False),
46 Column("payload_hash", String(64), nullable=False),
47 Column("author_hash", String(64), nullable=False),
48 Column("created_at", DateTime(timezone=True),
49 nullable=False, server_default=func.current_timestamp()),
50 UniqueConstraint("draft_id", name="uq_mapping_draft_authors_draft"),
51 CheckConstraint("role = 'mapping_proposer'", name="ck_mapping_draft_authors_proposer"),
52 )
53
54 SQLITE_AUTHOR_GUARD_DDL = (
55 """CREATE TRIGGER mapping_draft_authors_no_update
56 BEFORE UPDATE ON mapping_draft_authors
57 BEGIN SELECT RAISE(ABORT, 'Mapping author evidence is insert-only'); END""",
58 """CREATE TRIGGER mapping_draft_authors_no_delete
59 BEFORE DELETE ON mapping_draft_authors
60 BEGIN SELECT RAISE(ABORT, 'Mapping author evidence is insert-only'); END""",
61 )
62
63
64 @dataclass(frozen=True)
65 class DraftAuthor:
66 draft_id: int
67 year_id: int
68 issuer: str
69 subject: str
70 role: str
71 company_code: str
72 fiscal_year: int
73 payload_hash: str
74
75
76 def _canonical(value: dict[str, object]) -> str:
77 return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
78
79
80 def _author_digest(values: dict[str, object]) -> str:
81 return sha256(_canonical(values).encode("utf-8")).hexdigest()
82
83
84 def _values(
85 *, draft_id: int, year_id: int, issuer: str, subject: str,
86 company_code: str, fiscal_year: int, payload_hash: str,
87 ) -> dict[str, object]:
88 return {
89 "draft_id": draft_id, "year_id": year_id,
90 "issuer": issuer, "subject": subject, "role": "mapping_proposer",
91 "company_code": company_code, "fiscal_year": fiscal_year,
92 "payload_hash": payload_hash,
93 }
94
95
96 def _insert_author_evidence(session: Session, values: dict[str, object]) -> None:
97 session.execute(
98 insert(mapping_draft_authors).values(
99 **values, author_hash=_author_digest(values),
100 )
101 )
102
103
104 def get_draft_author(
105 session: Session, *, draft_id: int, year_id: int,
106 ) -> DraftAuthor:
107 """Read verified same-year author binding; legacy unbound drafts DENIED."""
108 with session.no_autoflush:
109 saved = get_unreviewed_batch(session, draft_id=draft_id, year_id=year_id)
110 row = session.execute(select(mapping_draft_authors).where(
111 mapping_draft_authors.c.draft_id == draft_id,
112 mapping_draft_authors.c.year_id == year_id,
113 )).mappings().first()
114 if row is None:
115 raise MappingAuthorConflict("unattributed Mapping draft cannot be claimed")
116 values = _values(
117 draft_id=row["draft_id"], year_id=row["year_id"],
118 issuer=row["issuer"], subject=row["subject"],
119 company_code=row["company_code"], fiscal_year=row["fiscal_year"],
120 payload_hash=row["payload_hash"],
121 )
122 if (
123 row["role"] != "mapping_proposer"
124 or row["payload_hash"] != saved.checksum
125 or row["author_hash"] != _author_digest(values)
126 ):
127 raise MappingAuthorConflict("Mapping author evidence corrupted")
128 return DraftAuthor(**values)
129
130
131 def stage_authored_unreviewed_batch(
132 session: Session, *, snapshot: MappingBatchPreview, request_key: str,
133 principal: VerifiedPrincipal,
134 ):
135 """Caller-managed transaction; binding, draft and system event all atomic.
136
137 Only use after FastAPI Depends(require_verified_principal). Nothing here
138 grants a finance reviewer an approval right or saves MappingRule.
139 """
140 if not isinstance(snapshot, MappingBatchPreview):
141 raise MappingValidationError("invalid Mapping batch")
142 grant = require_year_access(
143 session, principal=principal, year_id=snapshot.year_id,
144 required_role="mapping_proposer",
145 )
146 # Refuse retroactive authorship on legacy proposals. A draft may have
147 # existed before the authenticated staging request, so identifying its ID
148 # *after* the saver would allow a caller to take ownership of history.
149 existing = session.execute(select(mapping_review_drafts.c.id).where(
150 mapping_review_drafts.c.year_id == snapshot.year_id,
151 mapping_review_drafts.c.request_key == request_key,
152 )).scalar_one_or_none()
153 if existing is not None:
154 previous_author = get_draft_author(
155 session, draft_id=existing, year_id=snapshot.year_id,
156 )
157 if (previous_author.issuer, previous_author.subject) != (
158 principal.issuer, principal.subject,
159 ):
160 raise MappingAuthorConflict(
161 "Mapping draft request key belongs to another author"
162 )
163 saved = save_unreviewed_batch(session, snapshot, request_key=request_key)
164 values = _values(
165 draft_id=saved.id, year_id=snapshot.year_id,
166 issuer=principal.issuer, subject=principal.subject,
167 company_code=grant.company_code, fiscal_year=grant.fiscal_year,
168 payload_hash=saved.checksum,
169 )
170 current = session.execute(select(mapping_draft_authors).where(
171 mapping_draft_authors.c.draft_id == saved.id,
172 )).mappings().first()
173 if current is not None:
174 author = get_draft_author(session, draft_id=saved.id, year_id=snapshot.year_id)
175 if (author.issuer, author.subject, author.company_code,
176 author.fiscal_year) != (
177 principal.issuer, principal.subject, grant.company_code,
178 grant.fiscal_year,
179 ):
180 raise MappingAuthorConflict("Mapping draft request key belongs to another author")
181 return saved
182 # The request-key lookup above proved this is a new record; do not
183 # retrofit authenticated authorship onto legacy unbound drafts.
184 _insert_author_evidence(session, values)
185 return saved
186
187
188 def check_independent_mapping_reviewer(
189 session: Session, *, draft_id: int, year_id: int,
190 reviewer: VerifiedPrincipal,
191 ) -> None:
192 """Read-only *eligibility* check, NEVER an Approved state transition."""
193 require_year_access(
194 session, principal=reviewer, year_id=year_id,
195 required_role="mapping_reviewer",
196 )
197 author = get_draft_author(session, draft_id=draft_id, year_id=year_id)
198 if (author.issuer, author.subject) == (reviewer.issuer, reviewer.subject):
199 raise HTTPException(status_code=403, detail="Author cannot review own Mapping")