@davoodmehraban89 / Aram / commits / b25ce45
Fork 0

feat(gate3): scoped access, conservative mapping quality, integrity and backup verification

Davood Mehraban committed Nov 1, 2026 at 22:01 UTC b25ce454ff182f1d3c611b872f44b78c0d8c0fe1
9 files changed +397 -3
PROJECT_STATUS.md
+9
@@ -97,3 +97,12 @@ The accepted branch does not include PR #7 desktop/release work, PR #16 alternat
97 - Status: CHANGES REQUESTED; Gate 3 is not formally accepted. No merge or release.
98 - Unresolved: authenticated identity and authorization, privileged-database tamper resistance, independent review, operational recovery drill, mapping ambiguity and real-data acceptance.
99 - Rollback: revert isolated PR commits; accepted base and canonical financial source files remain untouched.
100 +
101 +## 2026-11-01 — Gate 3 Package 4 (supersedes earlier Gate 3 summaries)
102 +- Isolated branch and Draft PR #82; accepted base source-data-cleanup@7dc864fd032f0c4ae4d650d89304a01286a6d914 unchanged.
103 +- New security facade: role/scope checks with injected trusted identity resolver; NOT connected to production API/IdP.
104 +- New integrity verification and consistent SQLite backup-to-fresh-file test; no external tamper-evident audit anchor.
105 +- Conservative ambiguity assessment; Excel hierarchy/notes roundtrip fixes; no real-ledger reconciliation claimed.
106 +- Review evidence: docs/GATE3_PACKAGE4_REVIEW.md (three self-review perspectives, not independent reviewers).
107 +- Formal Gate 3 status: CHANGES REQUESTED; PR must remain Draft. Do not merge/release/start Gate 4 implementation before independent acceptance.
108 +- Remaining blockers: independent reviewer approval, API/IdP authorization integration, external audit integrity, authorized financial reconciliation and operational recovery evidence.
backend/src/aram_backend/mapping_access.py new
+71
@@ -0,0 +1,71 @@
1 +"""Server-side mapping authorization boundary.
2 +
3 +The identity resolver MUST verify the request against an external identity
4 +provider; never accept a user-supplied username as authenticated identity.
5 +"""
6 +from __future__ import annotations
7 +
8 +from collections.abc import Callable
9 +from dataclasses import dataclass
10 +from typing import Literal
11 +
12 +from aram_backend.mapping_workflow import (
13 + MappingDecision,
14 + MappingWorkflowError,
15 + MappingWorkspace,
16 +)
17 +
18 +Role = Literal["maker", "reviewer", "approver"]
19 +
20 +
21 +@dataclass(frozen=True)
22 +class AuthenticatedPrincipal:
23 + subject: str
24 + company_scopes: frozenset[str]
25 + roles: frozenset[Role]
26 +
27 +
28 +class MappingAccess:
29 + """Fail-closed role/scope checks; resolver is a trusted server dependency."""
30 +
31 + def __init__(self, resolve_identity: Callable[[str], AuthenticatedPrincipal | None]):
32 + self._resolve = resolve_identity
33 +
34 + def _authorize(self, credential: str, workspace: MappingWorkspace, role: Role) -> str:
35 + if not isinstance(credential, str) or not credential:
36 + raise MappingWorkflowError("authenticated credential required")
37 + principal = self._resolve(credential)
38 + if (principal is None or not isinstance(principal, AuthenticatedPrincipal)
39 + or not principal.subject.strip()
40 + or workspace.company_code not in principal.company_scopes
41 + or role not in principal.roles):
42 + raise MappingWorkflowError("mapping access denied")
43 + return principal.subject
44 +
45 + def propose(self, credential: str, workspace: MappingWorkspace,
46 + decision: MappingDecision) -> MappingDecision:
47 + actor = self._authorize(credential, workspace, "maker")
48 + return workspace.propose(decision, actor=actor)
49 +
50 + def review(self, credential: str, workspace: MappingWorkspace,
51 + mapping_id: str) -> MappingDecision:
52 + actor = self._authorize(credential, workspace, "reviewer")
53 + return workspace.transition(mapping_id, "Reviewed", actor=actor)
54 +
55 + def approve(self, credential: str, workspace: MappingWorkspace,
56 + mapping_id: str) -> MappingDecision:
57 + actor = self._authorize(credential, workspace, "approver")
58 + return workspace.transition(mapping_id, "Approved", actor=actor)
59 +
60 + def revise(self, credential: str, workspace: MappingWorkspace, mapping_id: str,
61 + *, target_statement: str, statement_section: str, note_number: str,
62 + subnote_code: str | None) -> MappingDecision:
63 + actor = self._authorize(credential, workspace, "maker")
64 + return workspace.revise(mapping_id, actor=actor, target_statement=target_statement,
65 + statement_section=statement_section, note_number=note_number,
66 + subnote_code=subnote_code)
67 +
68 + def carry_forward(self, credential: str, workspace: MappingWorkspace,
69 + previous: tuple[MappingDecision, ...]) -> int:
70 + actor = self._authorize(credential, workspace, "maker")
71 + return workspace.carry_forward(previous, actor=actor)
backend/src/aram_backend/mapping_quality.py new
+54
@@ -0,0 +1,54 @@
1 +"""Conservative mapping ambiguity report; never infers approval from a workbook."""
2 +from __future__ import annotations
3 +
4 +from collections import defaultdict
5 +from collections.abc import Iterable
6 +from dataclasses import dataclass
7 +
8 +from aram_backend.mapping_workflow import MappingDecision, MappingWorkflowError
9 +
10 +
11 +@dataclass(frozen=True)
12 +class MappingQuality:
13 + company_code: str
14 + fiscal_year: int
15 + unmapped_accounts: tuple[str, ...]
16 + pending_accounts: tuple[str, ...]
17 + conflicting_accounts: tuple[str, ...]
18 + approved_accounts: tuple[str, ...]
19 +
20 + @property
21 + def ready(self) -> bool:
22 + return not (self.unmapped_accounts or self.pending_accounts or self.conflicting_accounts)
23 +
24 +
25 +def assess_mapping_quality(
26 + accounts: Iterable[str], decisions: Iterable[MappingDecision], *,
27 + company_code: str, fiscal_year: int,
28 +) -> MappingQuality:
29 + """Classify all accounts; never silently select between conflicting mappings."""
30 + if not company_code.strip() or isinstance(fiscal_year, bool) or fiscal_year <= 0:
31 + raise MappingWorkflowError("invalid quality scope")
32 + codes = tuple(accounts)
33 + if any(not isinstance(code, str) or not code.strip() for code in codes):
34 + raise MappingWorkflowError("invalid account code")
35 + grouped: dict[str, list[MappingDecision]] = defaultdict(list)
36 + for d in decisions:
37 + if (d.company_code, d.fiscal_year) != (company_code, fiscal_year):
38 + raise MappingWorkflowError("foreign mapping in quality assessment")
39 + if d.account_full_code not in codes:
40 + raise MappingWorkflowError("mapping references unknown account")
41 + grouped[d.account_full_code].append(d)
42 + unmapped, pending, conflicting, approved = [], [], [], []
43 + for code in sorted(set(codes)):
44 + mappings = grouped[code]
45 + if not mappings:
46 + unmapped.append(code)
47 + elif len(mappings) > 1:
48 + conflicting.append(code)
49 + elif mappings[0].status != "Approved":
50 + pending.append(code)
51 + else:
52 + approved.append(code)
53 + return MappingQuality(company_code, fiscal_year, tuple(unmapped),
54 + tuple(pending), tuple(conflicting), tuple(approved))
backend/src/aram_backend/mapping_store.py
+61
@@ -154,3 +154,64 @@ class MappingStore:
154 (company, year),
155 ).fetchall()
156 return tuple(MappingAuditEvent(**json.loads(row[0])) for row in rows)
157 +
158 +
159 + def verify_integrity(self) -> None:
160 + """Detect corruption and state/audit disagreement; not privileged tamper-proof."""
161 + with closing(self._connect()) as db:
162 + if db.execute("PRAGMA quick_check").fetchone()[0] != "ok":
163 + raise MappingWorkflowError("SQLite integrity check failed")
164 + rows = db.execute(
165 + "SELECT company, year, payload FROM mapping_state ORDER BY company, year"
166 + ).fetchall()
167 + for company, year, payload in rows:
168 + state = json.loads(payload)
169 + audit = [json.loads(r[0]) for r in db.execute(
170 + "SELECT payload FROM mapping_audit WHERE company=? AND year=? ORDER BY sequence",
171 + (company, year),
172 + )]
173 + if state["audit"] != audit:
174 + raise MappingWorkflowError("persisted audit/state mismatch")
175 + workspace, _ = self.load(company, year)
176 + latest = {}
177 + for event in workspace.audit:
178 + prior = latest.get(event.mapping_id)
179 + if prior is None:
180 + valid = (event.previous_status is None
181 + and event.previous_version is None
182 + and event.new_status == "Draft"
183 + and event.new_version == 1)
184 + else:
185 + valid = (event.previous_status == prior[0]
186 + and event.previous_version == prior[1]
187 + and event.new_version == prior[1] + 1
188 + and ((prior[0] == "Draft" and event.new_status == "Reviewed")
189 + or (prior[0] == "Reviewed" and event.new_status == "Approved")
190 + or event.new_status == "Draft"))
191 + if not valid:
192 + raise MappingWorkflowError("invalid persisted audit chain")
193 + latest[event.mapping_id] = (event.new_status, event.new_version)
194 + if latest != {d.mapping_id: (d.status, d.version)
195 + for d in workspace.decisions}:
196 + raise MappingWorkflowError("persisted mapping state diverged")
197 + orphan = db.execute(
198 + "SELECT 1 FROM mapping_audit a WHERE NOT EXISTS "
199 + "(SELECT 1 FROM mapping_state s WHERE s.company=a.company AND s.year=a.year) "
200 + "LIMIT 1"
201 + ).fetchone()
202 + if orphan:
203 + raise MappingWorkflowError("orphan audit events")
204 +
205 + def backup_to(self, destination: str | Path) -> None:
206 + """Create consistent SQLite snapshot; never overwrite an existing backup."""
207 + target = Path(destination)
208 + if target.exists() or target.resolve() == Path(self.path).resolve():
209 + raise MappingWorkflowError("backup destination must be new and distinct")
210 + self.verify_integrity()
211 + try:
212 + with closing(self._connect()) as source, closing(sqlite3.connect(target)) as backup:
213 + source.backup(backup)
214 + MappingStore(target).verify_integrity()
215 + except Exception:
216 + target.unlink(missing_ok=True)
217 + raise
backend/src/aram_backend/mapping_workflow.py
+11 -3
@@ -278,7 +278,9 @@ def export_pilot_mapping_workbook(
278 for d in decisions:
279 if (d.company_code, d.fiscal_year) != (company_code, fiscal_year):
280 raise MappingWorkflowError("foreign company/year in export")
281 - if d.mapping_id in seen:
281 + if d.mapping_id in seen or any(
282 + existing[0] == d.mapping_id for existing in foreign_rows
283 + ):
284 raise MappingWorkflowError("duplicate mapping ID in export")
285 seen.add(d.mapping_id)
286 account = accounts.get((company_code, fiscal_year, d.account_full_code))
@@ -295,8 +297,14 @@ def export_pilot_mapping_workbook(
297 row.update({
298 "mapping_id": d.mapping_id, "company_code": company_code,
299 "fiscal_year": fiscal_year, "account_full_code": d.account_full_code,
298 - "account_level": previous[d.mapping_id]["account_level"]
299 - if d.mapping_id in previous else "General",
300 + "account_level": next(
301 + level for field, level in (
302 + ("detail4_code", "Detail4"), ("detail3_code", "Detail3"),
303 + ("detail2_code", "Detail2"), ("detail1_code", "Detail1"),
304 + ("subsidiary_code", "Subsidiary"), ("general_code", "General"),
305 + ) if account[field] is not None
306 + ),
307 + "notes": previous.get(d.mapping_id, {}).get("notes"),
308 "target_statement": d.target_statement,
309 "statement_section": d.statement_section,
310 "note_number": d.note_number, "subnote_code": d.subnote_code,
backend/tests/test_mapping_access.py new
+56
@@ -0,0 +1,56 @@
1 +
2 +import pytest
3 +from aram_backend.mapping_access import AuthenticatedPrincipal, MappingAccess
4 +from aram_backend.mapping_workflow import (
5 + MappingDecision,
6 + MappingWorkflowError,
7 + MappingWorkspace,
8 +)
9 +
10 +
11 +def decision():
12 + return MappingDecision("M1", "001", 1405, "0010", "BS", "Assets",
13 + "01", None, 1, "Draft", None, "Manual")
14 +
15 +
16 +def test_authenticated_scoped_segregation_and_revisions():
17 + identities = {
18 + "token-maker": AuthenticatedPrincipal("maker", frozenset({"001"}), frozenset({"maker"})),
19 + "token-review": AuthenticatedPrincipal("reviewer", frozenset({"001"}), frozenset({"reviewer"})),
20 + "token-approve": AuthenticatedPrincipal("approver", frozenset({"001"}), frozenset({"approver"})),
21 + "token-foreign": AuthenticatedPrincipal("foreign", frozenset({"002"}), frozenset({"approver"})),
22 + }
23 + access = MappingAccess(identities.get)
24 + space = MappingWorkspace("001", 1405)
25 + for credential in ("", "maker", "token-foreign", "token-review"):
26 + with pytest.raises(MappingWorkflowError):
27 + access.propose(credential, space, decision())
28 + access.propose("token-maker", space, decision())
29 + with pytest.raises(MappingWorkflowError, match="access denied"):
30 + access.approve("token-maker", space, "M1")
31 + access.review("token-review", space, "M1")
32 + access.approve("token-approve", space, "M1")
33 + assert space.decisions[0].status == "Approved"
34 + assert [e.actor for e in space.audit] == ["maker", "reviewer", "approver"]
35 + access.revise("token-maker", space, "M1", target_statement="IS",
36 + statement_section="Revenue", note_number="02", subnote_code=None)
37 + assert space.decisions[0].status == "Draft"
38 +
39 +
40 +def test_identity_resolver_failure_is_fail_closed():
41 + access = MappingAccess(lambda _: None)
42 + with pytest.raises(MappingWorkflowError, match="access denied"):
43 + access.propose("anything", MappingWorkspace("001", 1405), decision())
44 +
45 +
46 +def test_maker_with_approver_role_cannot_approve_own_mapping():
47 + users = {
48 + "a": AuthenticatedPrincipal("a", frozenset({"001"}), frozenset({"maker", "approver"})),
49 + "b": AuthenticatedPrincipal("b", frozenset({"001"}), frozenset({"reviewer"})),
50 + }
51 + access = MappingAccess(users.get)
52 + space = MappingWorkspace("001", 1405)
53 + access.propose("a", space, decision())
54 + access.review("b", space, "M1")
55 + with pytest.raises(MappingWorkflowError, match="independent"):
56 + access.approve("a", space, "M1")
backend/tests/test_mapping_recovery_quality.py new
+86
@@ -0,0 +1,86 @@
1 +import sqlite3
2 +from dataclasses import replace
3 +
4 +import pytest
5 +from aram_backend.mapping_quality import assess_mapping_quality
6 +from aram_backend.mapping_store import MappingStore
7 +from aram_backend.mapping_workflow import MappingDecision, MappingWorkflowError
8 +
9 +
10 +def decision(code="0010", mapping_id="M1", status="Draft"):
11 + return MappingDecision(mapping_id, "001", 1405, code, "BS", "Assets",
12 + "01", None, 1, status, None, "Manual")
13 +
14 +
15 +def test_backup_restore_to_fresh_store_and_no_overwrite(tmp_path):
16 + store = MappingStore(tmp_path / "original.db")
17 + state, revision = store.load("001", 1405)
18 + state.propose(decision(), actor="maker")
19 + store.save(state, revision)
20 + target = tmp_path / "backup.db"
21 + store.backup_to(target)
22 + restored = MappingStore(target)
23 + restored.verify_integrity()
24 + assert restored.load("001", 1405)[0].decisions == (decision(),)
25 + assert restored.audit_log("001", 1405) == store.audit_log("001", 1405)
26 + with pytest.raises(MappingWorkflowError, match="new"):
27 + store.backup_to(target)
28 +
29 +
30 +def test_detects_direct_audit_tamper(tmp_path):
31 + path = tmp_path / "tamper.db"
32 + store = MappingStore(path)
33 + state, rev = store.load("001", 1405)
34 + state.propose(decision(), actor="maker")
35 + store.save(state, rev)
36 + with sqlite3.connect(path) as db:
37 + db.execute("DELETE FROM mapping_audit")
38 + with pytest.raises(MappingWorkflowError, match="audit/state mismatch"):
39 + store.verify_integrity()
40 +
41 +
42 +def test_quality_never_auto_approves_ambiguous_accounts():
43 + draft = decision()
44 + approved = replace(draft, status="Approved", version=3)
45 + conflict = replace(approved, mapping_id="M2")
46 + report = assess_mapping_quality(["0010", "0020"], [approved, conflict],
47 + company_code="001", fiscal_year=1405)
48 + assert report.conflicting_accounts == ("0010",)
49 + assert report.unmapped_accounts == ("0020",)
50 + assert not report.ready
51 + report = assess_mapping_quality(["0010"], [approved],
52 + company_code="001", fiscal_year=1405)
53 + assert report.ready and report.approved_accounts == ("0010",)
54 + report = assess_mapping_quality(["0010"], [draft],
55 + company_code="001", fiscal_year=1405)
56 + assert report.pending_accounts == ("0010",) and not report.ready
57 + with pytest.raises(MappingWorkflowError, match="foreign"):
58 + assess_mapping_quality(["0010"], [replace(draft, company_code="002")],
59 + company_code="001", fiscal_year=1405)
60 +
61 +
62 +def test_workbook_mapping_notes_preserved_on_roundtrip():
63 + from io import BytesIO
64 +
65 + from aram_backend.mapping_workflow import (
66 + export_pilot_mapping_workbook,
67 + import_mapping_workbook,
68 + )
69 + from aram_backend.pilot_workbook import SHEET_HEADERS
70 + from openpyxl import load_workbook
71 + from test_pilot_workbook import valid_rows, workbook_bytes
72 +
73 + wb = load_workbook(BytesIO(workbook_bytes(valid_rows())))
74 + columns = SHEET_HEADERS["Mapping"]
75 + wb["Mapping"].cell(2, columns.index("notes") + 1, "Manual financial review")
76 + data = BytesIO()
77 + wb.save(data)
78 + wb.close()
79 + decisions = import_mapping_workbook(data.getvalue(), "001", 1405)
80 + output = export_pilot_mapping_workbook(data.getvalue(), decisions,
81 + company_code="001", fiscal_year=1405)
82 + result = load_workbook(BytesIO(output), read_only=True)
83 + try:
84 + assert result["Mapping"].cell(2, columns.index("notes") + 1).value == "Manual financial review"
85 + finally:
86 + result.close()
docs/GATE3_PACKAGE4_REVIEW.md new
+42
@@ -0,0 +1,42 @@
1 +# Gate 3 — Package 4 acceptance review (2026-11-01)
2 +
3 +## Starting evidence
4 +- Accepted base: source-data-cleanup @ 7dc864fd032f0c4ae4d650d89304a01286a6d914.
5 +- Isolated branch: feat/gate3-governed-mapping-20261101; starting head 73f5b22e29c6cb926fda7dc1e1af5eb952aa4c19.
6 +- PR: https://github.com/davoodmehraban89/Aram/pull/82 (Draft).
7 +- Starting CI: https://github.com/davoodmehraban89/Aram/actions/runs/41336195717 (success).
8 +- Independent GitHub review approvals at start: zero.
9 +- No production financial data, canonical XLSX/PDF or production DB touched.
10 +
11 +## Review A — Functional/financial (self-review, not independent)
12 +- Existing scoped mapping lifecycle, maker/reviewer/approver separation, carry-forward, unknown-account queue and re-import tested.
13 +- Found export of newly added detailed account mapping defaulted to General; fixed by deriving account level from actual hierarchy.
14 +- Found existing Mapping.notes could be lost on roundtrip; fixed by retaining source notes.
15 +- Added conservative ambiguity classification: unmapped, pending, conflicting and approved account groups. Multiple mappings for one account always conflict even if individually approved. No automatic approval.
16 +- Limitation: no authorized real-ledger input was supplied for reconciliation; synthetic fixtures are NOT proof of financial correctness. Financial sign-off pending.
17 +
18 +## Review B — Security/architecture (self-review, not independent)
19 +- Added MappingAccess with server-provided authenticated identity resolver, company scope and maker/reviewer/approver roles. Usernames supplied by callers are not accepted as identity by this facade.
20 +- Resolver MUST be wired to a trusted external authentication service in the API. Direct MappingWorkspace calls bypass facade; this is not a completed production auth integration.
21 +- SQLite backup_to uses SQLite online backup API, creates a new target and verifies snapshot; verify_integrity checks SQLite quick_check, audit/state consistency, chain versions and orphan events.
22 +- SQLite hash/HMAC external integrity anchor is NOT present. Privileged DB writers could alter both tables; integrity check detects mismatches, not coordinated tampering. No claim of tamper-proof storage.
23 +
24 +## Review C — Adversarial/operational (self-review, not independent)
25 +- Added tests for unauthorized, missing, cross-company identities and maker approving own mapping.
26 +- Added backup/restore-to-fresh-file test, duplicate-backup rejection, direct audit table tampering and ambiguous-account fail-closed.
27 +- Existing optimistic concurrency tests cover two competing writers. No power-loss injection or large-scale multi-process stress performed.
28 +- Additional tests for mapping notes preservation and full workbook roundtrip.
29 +- Recovery drill is synthetic and non-production; no live disaster recovery performed.
30 +
31 +## Required evidence and acceptance
32 +- Full local backend pytest, scoped Ruff and compileall are required after changes.
33 +- GitHub Actions must succeed on the exact final commit. Record run URL in PR.
34 +- No independent reviewer has been represented by these three passes. Independent review must be provided by an actual distinct reviewer, recording identity, commit SHA, risks and decision.
35 +- Production blockers: real authentication integration, privileged-DB tamper-evidence policy, approved real-ledger reconciliation, independent review and operational recovery evidence.
36 +- Decision: **CHANGES REQUESTED / GATE 3 NOT ACCEPTED** until these blockers close.
37 +- Rollback: revert the isolated PR commits; no production migration executed.
38 +
39 +## Gate 4 preparation
40 +- Next phase must start only after Gate 3 acceptance; otherwise work may be planned but not promoted.
41 +- Integration prerequisites: trusted identity provider contract, company/role claims, transaction service API, audited mapping snapshot and approved real financial sample.
42 +- Do not infer approval or classification from imported workbook statuses without trusted review provenance.
docs/PROJECT_LOG.md
+7
@@ -287,3 +287,10 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
287 - Three sequential adversarial self-audits documented in docs/GATE3_REVIEW_82.md. No claim of independent reviewers.
288 - Formal decision: CHANGES REQUESTED, Gate 3 not accepted; independent reviewer and material operational/security controls outstanding.
289 - Rollback: revert Package 3 commits on isolated feature branch; no production schema/data migration.
290 +
291 +## 2026-11-01 — Gate 3 Package 4
292 +- Approved scope: harden mapping lifecycle, access, audit, workbook roundtrip, ambiguity handling, recovery tests, three-perspective review, CI and handoff.
293 +- Changes: mapping_access.py and tests; mapping_quality.py and tests; MappingStore.verify_integrity/backup_to; Excel mapping hierarchy and notes preservation.
294 +- Three sequential self-audits in docs/GATE3_PACKAGE4_REVIEW.md; not independent review.
295 +- No financial-data or canonical artifact modification; no production database migrations.
296 +- Formal status CHANGES REQUESTED pending independent review and remaining security/financial/operational evidence. Rollback by reverting focused feature-branch commits.