@davoodmehraban89 / Aram-2 Mirror · read-only / commits / 1856de1
Fork 0

Mirrored from https://github.com/davoodmehraban89/Aram.git

Synced Dec 4, 00:30 UTC

fix(gate3): fail closed on identity outages and test external audit receipt archive

Davood Mehraban committed Nov 1, 2026 at 22:23 UTC 1856de1beaf32073932a4d9c17b6364438a603e1
6 files changed +182 -1
PROJECT_STATUS.md
+7
@@ -114,3 +114,10 @@ The accepted branch does not include PR #7 desktop/release work, PR #16 alternat
114 - Synthetic HTTP, audit tamper, backup/restore and financial mapping tests added; no authorized real financial data or production DR drill performed.
115 - Three perspective-based self-audits, NOT three independent reviewers. See docs/GATE3_PACKAGE5_ACCEPTANCE.md.
116 - Decision: NO-GO / CHANGES REQUESTED. Do not merge, release or begin Gate 4 until policy prerequisites satisfied.
117 +
118 +## 2026-11-01 — Gate 3 Package 6 (latest)
119 +- Branch feat/gate3-governed-mapping-20261101, PR #82 Draft, base source-data-cleanup@7dc864fd032f0c4ae4d650d89304a01286a6d914.
120 +- Fail-closed resolver exceptions and separate-directory experimental audit receipt archive with exclusive creation, fsync, verification and tamper tests.
121 +- Full local backend suite, scoped Ruff and CI evidence are in PR #82; see docs/GATE3_PACKAGE6_FINAL.md for final acceptance matrix.
122 +- Three self-audit perspectives are not independent reviewers. Real IdP, protected external anchor, authorized financial reconciliation, operational DR drill and independent signoffs remain external prerequisites.
123 +- **NO-GO — Gate 3 NOT accepted.** No Merge, Release, production data edits or Gate 4 implementation.
backend/src/aram_backend/mapping_access.py
+4 -1
@@ -34,7 +34,10 @@ class MappingAccess:
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)
37 + try:
38 + principal = self._resolve(credential)
39 + except Exception as exc:
40 + raise MappingWorkflowError("mapping access denied") from exc
41 if (principal is None or not isinstance(principal, AuthenticatedPrincipal)
42 or not principal.subject.strip()
43 or workspace.company_code not in principal.company_scopes
backend/src/aram_backend/mapping_receipts.py new
+57
@@ -0,0 +1,57 @@
1 +"""Experimental off-database audit receipt store.
2 +
3 +The configured directory MUST reside on a separately administered, protected
4 +volume for any security claim. A local directory is only a test double.
5 +"""
6 +from __future__ import annotations
7 +
8 +import json
9 +import os
10 +from pathlib import Path
11 +
12 +from aram_backend.mapping_store import MappingStore
13 +from aram_backend.mapping_workflow import MappingWorkflowError
14 +
15 +
16 +class ReceiptArchive:
17 + def __init__(self, directory: str | Path):
18 + self.directory = Path(directory)
19 + if not self.directory.is_dir():
20 + raise MappingWorkflowError("receipt archive directory must already exist")
21 +
22 + def _path(self, company: str, year: int, revision: int) -> Path:
23 + if not company.isalnum() or not isinstance(year, int) or not isinstance(revision, int):
24 + raise MappingWorkflowError("invalid receipt identity")
25 + if year <= 0 or revision < 0:
26 + raise MappingWorkflowError("invalid receipt version")
27 + return self.directory / f"{company}-{year}-{revision}.json"
28 +
29 + def record(self, store: MappingStore, company: str, year: int) -> Path:
30 + receipt = store.audit_receipt(company, year)
31 + path = self._path(company, year, receipt["revision"])
32 + data = (json.dumps(receipt, ensure_ascii=False, sort_keys=True) + "\n").encode("utf-8")
33 + try:
34 + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
35 + except FileExistsError as exc:
36 + raise MappingWorkflowError("receipt already exists; overwrite forbidden") from exc
37 + try:
38 + with os.fdopen(fd, "wb") as handle:
39 + handle.write(data)
40 + handle.flush()
41 + os.fsync(handle.fileno())
42 + except Exception:
43 + path.unlink(missing_ok=True)
44 + raise
45 + return path
46 +
47 + def verify(self, store: MappingStore, company: str, year: int, revision: int) -> None:
48 + path = self._path(company, year, revision)
49 + try:
50 + receipt = json.loads(path.read_text(encoding="utf-8"))
51 + except (OSError, ValueError) as exc:
52 + raise MappingWorkflowError("trusted audit receipt missing or invalid") from exc
53 + if (receipt.get("company_code"), receipt.get("fiscal_year"), receipt.get("revision")) != (
54 + company, year, revision
55 + ):
56 + raise MappingWorkflowError("trusted audit receipt identity mismatch")
57 + store.verify_external_receipt(receipt)
backend/tests/test_mapping_receipts.py new
+58
@@ -0,0 +1,58 @@
1 +import sqlite3
2 +
3 +import pytest
4 +from aram_backend.mapping_access import MappingAccess
5 +from aram_backend.mapping_receipts import ReceiptArchive
6 +from aram_backend.mapping_store import MappingStore
7 +from aram_backend.mapping_workflow import (
8 + MappingDecision,
9 + MappingWorkflowError,
10 + MappingWorkspace,
11 +)
12 +
13 +
14 +def decision():
15 + return MappingDecision("M1", "001", 1405, "0010", "BS", "Assets",
16 + "01", None, 1, "Draft", None, "Manual")
17 +
18 +
19 +def test_separate_receipt_archive_backup_and_tamper(tmp_path):
20 + store = MappingStore(tmp_path / "state.db")
21 + workspace, revision = store.load("001", 1405)
22 + workspace.propose(decision(), actor="maker")
23 + store.save(workspace, revision)
24 + directory = tmp_path / "separate-archive"
25 + directory.mkdir()
26 + archive = ReceiptArchive(directory)
27 + path = archive.record(store, "001", 1405)
28 + archive.verify(store, "001", 1405, 1)
29 + with pytest.raises(MappingWorkflowError, match="overwrite forbidden"):
30 + archive.record(store, "001", 1405)
31 + backup = tmp_path / "restored.db"
32 + store.backup_to(backup)
33 + archive.verify(MappingStore(backup), "001", 1405, 1)
34 + with sqlite3.connect(store.path) as db:
35 + db.execute("UPDATE mapping_audit_hash SET digest=?", ("f" * 64,))
36 + with pytest.raises(MappingWorkflowError, match="hash chain mismatch"):
37 + archive.verify(store, "001", 1405, 1)
38 + path.write_text('{"broken":true}', encoding="utf-8")
39 + with pytest.raises(MappingWorkflowError, match="identity mismatch"):
40 + archive.verify(MappingStore(backup), "001", 1405, 1)
41 +
42 +
43 +def test_receipt_archive_rejects_traversal_and_missing_directory(tmp_path):
44 + with pytest.raises(MappingWorkflowError, match="already exist"):
45 + ReceiptArchive(tmp_path / "absent")
46 + directory = tmp_path / "receipts"
47 + directory.mkdir()
48 + archive = ReceiptArchive(directory)
49 + with pytest.raises(MappingWorkflowError, match="invalid receipt identity"):
50 + archive._path("../other", 1405, 1)
51 +
52 +
53 +def test_resolver_error_fails_closed():
54 + def unavailable(_):
55 + raise RuntimeError("identity service unavailable")
56 +
57 + with pytest.raises(MappingWorkflowError, match="access denied"):
58 + MappingAccess(unavailable).propose("token", MappingWorkspace("001", 1405), decision())
docs/GATE3_PACKAGE6_FINAL.md new
+48
@@ -0,0 +1,48 @@
1 +# Gate 3 Package 6 — Final technical handoff / acceptance decision
2 +
3 +Date: 2026-11-01
4 +Base: source-data-cleanup@7dc864fd032f0c4ae4d650d89304a01286a6d914
5 +Feature: feat/gate3-governed-mapping-20261101
6 +PR: https://github.com/davoodmehraban89/Aram/pull/82 (Draft)
7 +Starting SHA: 9368fd24798af52fe65acdffb46f43dd390303ed
8 +
9 +## Scope completed
10 +- Reviewed mapping HTTP API and existing fail-closed behavior. Corrected identity resolver exception path: outages now deny authorization without leaking resolver exceptions.
11 +- Implemented a separately configurable receipt archive *test adapter*, requiring an existing directory, exclusive creation and fsync, rejecting overwrite and invalid receipt paths. Tests verify backup/restore, missing archive, privileged DB digest modification and corrupted receipts.
12 +- IMPORTANT: local receipt directory is not a security boundary; production deployment must use an independently administered immutable/WORM repository with independent credentials, retention, anchoring and monitoring. No such external service was configured.
13 +- Reviewed existing account conflict, company/year scope, Draft/Reviewed/Approved, unknown-account queue, Excel roundtrip and carry-forward tests. No real financial data was available for authorized reconciliation.
14 +- Reviewed existing SQLite online backup, optimistic concurrency, audit hash chain and recovery tests. Synthetic recovery is not a real operational drill.
15 +- All work confined to isolated feature branch; no Merge, Release, real data modification or production migration.
16 +
17 +## Three adversarial perspectives — self-audits only
18 +1. Financial: account mapping ambiguity, hierarchy, scope, approval provenance, Excel reimport. Synthetic PASS; real-ledger signoff BLOCKED.
19 +2. Security: fail-closed identity resolver, role segregation, audit receipt exclusive writes, external anchor trust boundary. Test PASS; real IdP and independently administered anchor BLOCKED.
20 +3. Operations: SQLite backup/restore, concurrent stale writers, audit corruption, archive overwrite and recovery. Synthetic PASS; staging/production recovery exercise BLOCKED.
21 +These perspectives were performed by the same assistant. They do NOT constitute independent reviewer approvals.
22 +
23 +## Acceptance matrix
24 +| Criterion | State | Evidence / owner |
25 +| --- | --- | --- |
26 +| Isolated branch, approved base, no unrelated modifications | PASS | Git/PR |
27 +| Mapping HTTP fail-closed and company/role enforcement | PASS (synthetic) | mapping_api.py, mapping_access.py and tests |
28 +| Trusted production IdP integration and issuer/audience/expiry verification | BLOCKED | Deployment identity administrator |
29 +| SHA-256 chain and receipt verification | PASS (synthetic) | mapping_integrity.py, mapping_store.py and tests |
30 +| Protected external immutable anchor with independent credentials | BLOCKED | Security/operations administrator |
31 +| Conflict, approval workflow, Excel roundtrip and year scope | PASS (synthetic) | mapping_workflow.py, mapping_quality.py and tests |
32 +| Approved real-ledger reconciliation and mapping owner signoff | BLOCKED | Financial process owner |
33 +| Synthetic SQLite backup/restore and stale-writer tests | PASS | MappingStore and tests |
34 +| Operational staging recovery drill, RPO/RTO evidence | BLOCKED | Operations owner |
35 +| Three independent reviewers / required external signoffs | BLOCKED | Independent reviewers in GitHub |
36 +| Final-head full test, lint, CI | PENDING until CI final SHA | GitHub Actions |
37 +
38 +## Concrete external actions to close Gate 3
39 +1. Identity owner: supply authorized IdP integration contract, JWKS/issuer/audience validation, role/company claims, key rotation and revocation behavior; run integration tests in staging.
40 +2. Security owner: provision separate immutable receipt repository, restricted credentials and automated comparison against SQLite snapshots; record tamper drill evidence.
41 +3. Finance owner: supply approved non-production or anonymized real-ledger sample with source hashes, mapping decisions, unresolved exception disposition and signed reconciliation.
42 +4. Operations owner: conduct staging restore and simulated failure with agreed RPO/RTO and independent evidence.
43 +5. Independent reviewers: inspect exact final commit, verify test/CI and document reviewer identities, findings and approval per docs/ACCEPTANCE_POLICY.md.
44 +
45 +## Decision
46 +**NO-GO — Gate 3 not accepted.** Technical development may be handed off for review but Gate 4 implementation must not begin. PR remains Draft. No Merge/Release.
47 +
48 +Rollback: revert isolated feature commits; no production migration or data mutation occurred. No implicit backfill of historical audit hashes is authorized.
docs/PROJECT_LOG.md
+8
@@ -303,3 +303,11 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
303 - Acceptance evidence and Gate 4 handoff: docs/GATE3_PACKAGE5_ACCEPTANCE.md.
304 - No canonical XLSX/PDF, financial data, production database, Merge or Release changed. Rollback: revert feature-branch commits.
305 - Decision NO-GO pending external IdP, external audit anchor, authorized financial reconciliation, operational DR drill and independent review.
306 +
307 +## 2026-11-01 — Gate 3 Package 6
308 +- Rechecked approved base, PR #82 Draft, starting SHA and clean isolated branch.
309 +- Hardened mapping_access.py resolver exception path; added mapping_receipts.py for separately configured exclusive-write receipt archive and test_mapping_receipts.py for backup, tamper, invalid path and outage.
310 +- Three sequential self-review perspectives; no claim of independent reviewers or production security boundary.
311 +- Final technical handoff, acceptance matrix and external-owner action list in docs/GATE3_PACKAGE6_FINAL.md.
312 +- NO-GO until IdP, independently administered anchor, financial signoff, operational recovery evidence and independent reviews exist.
313 +- No production migration, Merge, Release or canonical financial artifact edits. Rollback via isolated commit revert.