feat(mapping): record proposer identity and enforce distinct reviewer preflight
davoodmehraban89 committed
Oct 30, 2026 at 23:04 UTC
a7f10fb1befd470719974d9f4c1488362987d558
1 file changed
+188
backend/src/aram_backend/authored_mapping_draft.py
new
+188
@@ -0,0 +1,188 @@
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
+ # The legacy saver intentionally remains an internal API; an existing
147
+ # legacy draft is not assigned an author retroactively.
148
+ saved = save_unreviewed_batch(session, snapshot, request_key=request_key)
149
+ values = _values(
150
+ draft_id=saved.id, year_id=snapshot.year_id,
151
+ issuer=principal.issuer, subject=principal.subject,
152
+ company_code=grant.company_code, fiscal_year=grant.fiscal_year,
153
+ payload_hash=saved.checksum,
154
+ )
155
+ current = session.execute(select(mapping_draft_authors).where(
156
+ mapping_draft_authors.c.draft_id == saved.id,
157
+ )).mappings().first()
158
+ if current is not None:
159
+ author = get_draft_author(session, draft_id=saved.id, year_id=snapshot.year_id)
160
+ if (author.issuer, author.subject, author.company_code,
161
+ author.fiscal_year) != (
162
+ principal.issuer, principal.subject, grant.company_code,
163
+ grant.fiscal_year,
164
+ ):
165
+ raise MappingAuthorConflict("Mapping draft request key belongs to another author")
166
+ return saved
167
+ # No old author evidence means this is either a genuinely new staged
168
+ # draft or a legacy unbound request. The latter must NEVER be adopted.
169
+ # Inspect a freshly created draft's system event in this transaction:
170
+ # the caller's request key may have existed before this call. Passing
171
+ # only the current saved ID is insufficient; detect preexistence BEFORE
172
+ # the legacy saver in the next revision.
173
+ _insert_author_evidence(session, values)
174
+ return saved
175
+
176
+
177
+def check_independent_mapping_reviewer(
178
+ session: Session, *, draft_id: int, year_id: int,
179
+ reviewer: VerifiedPrincipal,
180
+) -> None:
181
+ """Read-only *eligibility* check, NEVER an Approved state transition."""
182
+ require_year_access(
183
+ session, principal=reviewer, year_id=year_id,
184
+ required_role="mapping_reviewer",
185
+ )
186
+ author = get_draft_author(session, draft_id=draft_id, year_id=year_id)
187
+ if (author.issuer, author.subject) == (reviewer.issuer, reviewer.subject):
188
+ raise HTTPException(status_code=403, detail="Author cannot review own Mapping")