Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 19:30 UTC
feat(gate3): isolate audited local hardening and recovery tests
Davood Mehraban committed
Nov 3, 2026 at 15:42 UTC
a0b72be87720b1ff08361298b903ba57dd4fb408
34 files changed
+914
-48
.github/workflows/backend-ci.yml
+2
@@ -30,6 +30,8 @@ jobs:
30
cache-dependency-path: backend/pyproject.toml
31
- name: Install
32
run: python -m pip install -e '.[test]'
33
+ - name: Ruff
34
+ run: python -m ruff check src tests tools migrations
35
- name: Test
36
run: pytest
37
- name: Validate migration round-trip
PROJECT_STATUS.md
+9
@@ -128,3 +128,12 @@ The accepted branch does not include PR #7 desktop/release work, PR #16 alternat
128
- Closure dossier and reviewer signoff checklist: docs/GATE3_PACKAGE7_CLOSURE_DOSSIER.md.
129
- **Formal decision: NO-GO / CHANGES REQUESTED.** Assistant's technical work package closes; Gate 3 remains blocked on named external owners. No further assistant-only packages without new evidence or verified defect.
130
- No Merge, Release, canonical data changes or Gate 4 implementation.
131
+
132
+
133
+## 2026-11-03 — Package 8 local execution update
134
+- Local Windows worktree on `feat/gate3-governed-mapping-20261101`, HEAD `9d346f098a0a2159d96080715322879b08d9a1f8`; existing changes preserved and not published.
135
+- Local authentication prototype now has bounded lockout, session cap, thread safety, expiry pruning, revoke-all and role allow-list; still not wired to API and not a production identity service.
136
+- Ruff added to test extra and CI workflow; local Ruff, backend pytest, compileall, pip check, diff check and SQLite Alembic upgrade/downgrade round-trip passed.
137
+- PR #82 remains Draft / NO-GO; no independent reviews. New local changes have not yet been committed or run in remote CI.
138
+- Remaining mandatory blockers: trusted IdP/provisioning, independent immutable audit anchor, protected recoverable key custody and scheduled backup retention, authorized finance reconciliation, witnessed staging RPO/RTO drill, independent reviewer approval.
139
+- No canonical financial data changed; no commit, push, merge or release performed. See `docs/PROJECT_LOG.md` for execution detail.
backend/README.md
+18
@@ -34,6 +34,24 @@ Open `http://127.0.0.1:8000/docs`. The health endpoint is
34
`GET /api/v1/health`; read-only schema catalogs are available at
35
`GET /api/v1/schema/entities` and `GET /api/v1/schema/enums`.
36
37
+## Personal Windows setup (local-only pilot)
38
+
39
+In PowerShell, from the `backend` directory:
40
+
41
+```powershell
42
+py -3.12 -m venv .venv
43
+.\.venv\Scripts\python.exe -m pip install -e '.[test]'
44
+.\.venv\Scripts\python.exe -m pytest -q
45
+.\.venv\Scripts\python.exe -m uvicorn aram_backend.main:app --host 127.0.0.1 --port 8000
46
+```
47
+
48
+If `py` is not on PATH, use the installed Python 3.12 executable directly.
49
+The default install uses plain `uvicorn`; optional optimized `uvicorn[standard]`
50
+extras are available with `pip install -e '.[server-standard,test]'` when the
51
+package index supplies compatible Windows wheels. WebSockets are not required
52
+for the current HTTP-only pilot. Do not bind to `0.0.0.0` or expose this API
53
+outside localhost until real authentication and deployment hardening are verified.
54
+Passing tests does not authorize production financial processing or Gate 3 GO.
55
## Tests
56
57
```bash
backend/migrations/env.py
+1
-1
@@ -3,9 +3,9 @@ from logging.config import fileConfig
3
from alembic import context
4
from sqlalchemy import engine_from_config, pool
5
6
+from aram_backend import models # noqa: F401
7
from aram_backend.config import get_settings
8
from aram_backend.database import Base
8
-from aram_backend import models # noqa: F401
9
10
config = context.config
11
if config.config_file_name:
backend/migrations/versions/20260820_01_initial_schema.py
+1
-1
@@ -4,8 +4,8 @@ Revision ID: 20260820_01
4
"""
5
from alembic import op
6
7
-from aram_backend.database import Base
7
from aram_backend import models # noqa: F401
8
+from aram_backend.database import Base
9
10
revision = "20260820_01"
11
down_revision = None
backend/pyproject.toml
+4
-2
@@ -12,14 +12,17 @@ dependencies = [
12
"fastapi>=0.115,<1",
13
"pydantic-settings>=2.7,<3",
14
"sqlalchemy>=2.0,<3",
15
- "uvicorn[standard]>=0.34,<1",
15
+ "uvicorn>=0.34,<1",
16
"openpyxl>=3.1,<4",
17
]
18
19
[project.optional-dependencies]
20
+server-standard = ["uvicorn[standard]>=0.34,<1"]
21
test = [
22
"httpx>=0.28,<1",
23
"pytest>=8.3,<9",
24
+ "cryptography>=44,<47",
25
+ "ruff>=0.11,<1",
26
]
27
28
[tool.setuptools.packages.find]
@@ -28,4 +31,3 @@ where = ["src"]
31
[tool.pytest.ini_options]
32
testpaths = ["tests"]
33
addopts = "-q"
31
-
backend/src/aram_backend/ingestion.py
+3
-4
@@ -8,7 +8,6 @@ from sqlalchemy.orm import Session
8
9
from aram_backend.models import FiscalYear, FiscalYearStatus, SourceDocument
10
11
-
11
ALLOWED_SOURCE_SUFFIXES = frozenset({".csv", ".xlsx"})
12
ALLOWED_DOCUMENT_TYPES = frozenset(
13
{"financial_statement", "general_ledger", "mapping", "trial_balance"}
@@ -60,11 +59,11 @@ def register_source_document(
59
)
60
if existing is not None:
61
if existing.document_type != document_type and existing.filename != safe_name:
63
- raise SourceRegistrationError(f"document type and filename mismatch for existing content hash")
62
+ raise SourceRegistrationError("document type and filename mismatch for existing content hash")
63
if existing.document_type != document_type:
65
- raise SourceRegistrationError(f"document type mismatch for existing content hash")
64
+ raise SourceRegistrationError("document type mismatch for existing content hash")
65
if existing.filename != safe_name:
67
- raise SourceRegistrationError(f"filename mismatch for existing content hash")
66
+ raise SourceRegistrationError("filename mismatch for existing content hash")
67
return existing
68
69
source = SourceDocument(
backend/src/aram_backend/ledger_parser.py
+2
-2
@@ -78,8 +78,8 @@ def parse_general_ledger(content: bytes) -> Iterator[LedgerRecord]:
78
if not any(value is not None for value in values):
79
continue
80
81
- def value(field: str):
82
- return values[indexes[_FIELDS[field]]]
81
+ def value(field: str, row_values=values):
82
+ return row_values[indexes[_FIELDS[field]]]
83
84
yield LedgerRecord(
85
row_number=row_number,
backend/src/aram_backend/local_auth.py
new
+153
@@ -0,0 +1,153 @@
1
+"""Opt-in local password verification and bounded opaque sessions.
2
+
3
+This remains a single-owner local adapter. It is not a production IdP and must
4
+not be enabled until credential provisioning, DPAPI key custody, API wiring,
5
+and deployment binding have been reviewed.
6
+"""
7
+from __future__ import annotations
8
+
9
+import hashlib
10
+import hmac
11
+import secrets
12
+import threading
13
+import time
14
+from dataclasses import dataclass
15
+
16
+from aram_backend.mapping_access import AuthenticatedPrincipal
17
+
18
+_PBKDF2_ITERATIONS = 600_000
19
+_MAX_PASSWORD_LENGTH = 1024
20
+_ALLOWED_ROLES = frozenset({"maker", "reviewer", "approver", "owner"})
21
+
22
+
23
+@dataclass(frozen=True)
24
+class LocalCredential:
25
+ subject: str
26
+ company_scopes: frozenset[str]
27
+ roles: frozenset[str]
28
+ salt: bytes
29
+ password_hash: bytes
30
+
31
+
32
+def create_credential(
33
+ subject: str,
34
+ password: str,
35
+ companies: frozenset[str],
36
+ roles: frozenset[str],
37
+) -> LocalCredential:
38
+ if (
39
+ not isinstance(subject, str)
40
+ or not subject.strip()
41
+ or len(subject) > 200
42
+ or not isinstance(password, str)
43
+ or not 14 <= len(password) <= _MAX_PASSWORD_LENGTH
44
+ or not companies
45
+ or any(not isinstance(code, str) or not code.strip() or len(code) > 64 for code in companies)
46
+ or not roles
47
+ or not roles.issubset(_ALLOWED_ROLES)
48
+ ):
49
+ raise ValueError("invalid local credential configuration")
50
+ salt = secrets.token_bytes(32)
51
+ digest = hashlib.pbkdf2_hmac(
52
+ "sha256", password.encode("utf-8"), salt, _PBKDF2_ITERATIONS
53
+ )
54
+ return LocalCredential(subject.strip(), frozenset(companies), frozenset(roles), salt, digest)
55
+
56
+
57
+class LocalSessionAuthority:
58
+ """Volatile, single-credential session authority with bounded lockout.
59
+
60
+ Restart revokes all sessions and clears lockout state. Persisted identity,
61
+ multi-user account management, and cross-process rate limiting are out of
62
+ scope; do not expose this adapter on a public network.
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ credential: LocalCredential,
68
+ *,
69
+ lifetime_seconds: int = 900,
70
+ max_failed_attempts: int = 5,
71
+ lockout_seconds: int = 60,
72
+ max_sessions: int = 8,
73
+ ):
74
+ if not 0 < lifetime_seconds <= 3600:
75
+ raise ValueError("invalid session lifetime")
76
+ if not 1 <= max_failed_attempts <= 20:
77
+ raise ValueError("invalid failed-attempt limit")
78
+ if not 1 <= lockout_seconds <= 3600:
79
+ raise ValueError("invalid lockout duration")
80
+ if not 1 <= max_sessions <= 64:
81
+ raise ValueError("invalid session limit")
82
+ self._credential = credential
83
+ self._lifetime = lifetime_seconds
84
+ self._max_failed_attempts = max_failed_attempts
85
+ self._lockout_seconds = lockout_seconds
86
+ self._max_sessions = max_sessions
87
+ self._failed_attempts = 0
88
+ self._locked_until = 0.0
89
+ self._sessions: dict[bytes, float] = {}
90
+ self._lock = threading.RLock()
91
+
92
+ def login(self, password: str) -> str | None:
93
+ if not isinstance(password, str) or len(password) > _MAX_PASSWORD_LENGTH:
94
+ return None
95
+ with self._lock:
96
+ now = time.monotonic()
97
+ if now < self._locked_until:
98
+ return None
99
+ candidate = hashlib.pbkdf2_hmac(
100
+ "sha256",
101
+ password.encode("utf-8"),
102
+ self._credential.salt,
103
+ _PBKDF2_ITERATIONS,
104
+ )
105
+ if not hmac.compare_digest(candidate, self._credential.password_hash):
106
+ self._failed_attempts += 1
107
+ if self._failed_attempts >= self._max_failed_attempts:
108
+ self._locked_until = now + self._lockout_seconds
109
+ self._failed_attempts = 0
110
+ return None
111
+
112
+ self._failed_attempts = 0
113
+ self._locked_until = 0.0
114
+ self._prune_expired(now)
115
+ if len(self._sessions) >= self._max_sessions:
116
+ return None
117
+ token = secrets.token_urlsafe(32)
118
+ self._sessions[hashlib.sha256(token.encode("utf-8")).digest()] = (
119
+ now + self._lifetime
120
+ )
121
+ return token
122
+
123
+ def resolve(self, token: str) -> AuthenticatedPrincipal | None:
124
+ if not isinstance(token, str) or not token or len(token) > 256:
125
+ return None
126
+ key = hashlib.sha256(token.encode("utf-8")).digest()
127
+ with self._lock:
128
+ expires = self._sessions.get(key)
129
+ if expires is None:
130
+ return None
131
+ if time.monotonic() >= expires:
132
+ self._sessions.pop(key, None)
133
+ return None
134
+ return AuthenticatedPrincipal(
135
+ self._credential.subject,
136
+ self._credential.company_scopes,
137
+ self._credential.roles,
138
+ )
139
+
140
+ def revoke(self, token: str) -> None:
141
+ if isinstance(token, str) and len(token) <= 256:
142
+ key = hashlib.sha256(token.encode("utf-8")).digest()
143
+ with self._lock:
144
+ self._sessions.pop(key, None)
145
+
146
+ def revoke_all(self) -> None:
147
+ with self._lock:
148
+ self._sessions.clear()
149
+
150
+ def _prune_expired(self, now: float) -> None:
151
+ expired = [key for key, expires in self._sessions.items() if now >= expires]
152
+ for key in expired:
153
+ self._sessions.pop(key, None)
backend/src/aram_backend/mapping_access.py
+6
-1
@@ -15,7 +15,7 @@ from aram_backend.mapping_workflow import (
15
MappingWorkspace,
16
)
17
18
-Role = Literal["maker", "reviewer", "approver"]
18
+Role = Literal["maker", "reviewer", "approver", "owner"]
19
20
21
@dataclass(frozen=True)
@@ -60,6 +60,11 @@ class MappingAccess:
60
actor = self._authorize(credential, workspace, "approver")
61
return workspace.transition(mapping_id, "Approved", actor=actor)
62
63
+ def owner_accept(self, credential: str, workspace: MappingWorkspace,
64
+ mapping_id: str, *, reason: str) -> MappingDecision:
65
+ actor = self._authorize(credential, workspace, "owner")
66
+ return workspace.owner_accept(mapping_id, actor=actor, reason=reason)
67
+
68
def revise(self, credential: str, workspace: MappingWorkspace, mapping_id: str,
69
*, target_statement: str, statement_section: str, note_number: str,
70
subnote_code: str | None) -> MappingDecision:
backend/src/aram_backend/mapping_api.py
+10
@@ -60,6 +60,9 @@ class Proposal(BaseModel):
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)
@@ -104,6 +107,13 @@ def approve(company: str, year: int, mapping_id: str, token: str = Depends(_cred
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)):
backend/src/aram_backend/mapping_store.py
+2
-2
@@ -93,7 +93,7 @@ class MappingStore:
93
valid = (event.previous_status == previous_status and
94
event.previous_version == previous_version and
95
event.new_version == previous_version + 1 and
96
- ((previous_status == "Draft" and event.new_status == "Reviewed") or
96
+ ((previous_status == "Draft" and event.new_status in ("Reviewed", "OwnerAcceptedWithException")) or
97
(previous_status == "Reviewed" and event.new_status == "Approved") or
98
event.new_status == "Draft"))
99
if not valid or not event.actor.strip():
@@ -209,7 +209,7 @@ class MappingStore:
209
valid = (event.previous_status == prior[0]
210
and event.previous_version == prior[1]
211
and event.new_version == prior[1] + 1
212
- and ((prior[0] == "Draft" and event.new_status == "Reviewed")
212
+ and ((prior[0] == "Draft" and event.new_status in ("Reviewed", "OwnerAcceptedWithException"))
213
or (prior[0] == "Reviewed" and event.new_status == "Approved")
214
or event.new_status == "Draft"))
215
if not valid:
backend/src/aram_backend/mapping_workflow.py
+18
-2
@@ -47,6 +47,7 @@ class MappingAuditEvent:
47
timestamp: str
48
previous_version: int | None
49
new_version: int
50
+ reason: str | None = None
51
52
53
class MappingWorkspace:
@@ -74,13 +75,13 @@ class MappingWorkspace:
75
if (decision.company_code, decision.fiscal_year) != (self.company_code, self.fiscal_year):
76
raise MappingWorkflowError("company/year isolation violation")
77
77
- def _record(self, old: MappingDecision | None, new: MappingDecision, actor: str) -> None:
78
+ def _record(self, old: MappingDecision | None, new: MappingDecision, actor: str, reason: str | None = None) -> None:
79
self._decisions[new.mapping_id] = new
80
self._audit.append(MappingAuditEvent(
81
new.mapping_id, new.company_code, new.fiscal_year,
82
old.status if old else None, new.status, actor,
83
datetime.now(UTC).isoformat(),
83
- old.version if old else None, new.version,
84
+ old.version if old else None, new.version, reason,
85
))
86
87
def propose(self, decision: MappingDecision, *, actor: str) -> MappingDecision:
@@ -122,6 +123,21 @@ class MappingWorkspace:
123
self._record(old, new, actor)
124
return new
125
126
+ def owner_accept(self, mapping_id: str, *, actor: str, reason: str) -> MappingDecision:
127
+ """Record explicit owner exception; NEVER impersonate independent approval."""
128
+ old = self._decisions.get(mapping_id)
129
+ if old is None:
130
+ raise MappingWorkflowError("unknown mapping_id")
131
+ if old.status != "Draft":
132
+ raise MappingWorkflowError("owner acceptance requires unreviewed Draft")
133
+ if not actor.strip() or not isinstance(reason, str) or len(reason.strip()) < 15:
134
+ raise MappingWorkflowError("owner acceptance requires identity and reason (15+ chars)")
135
+ new = replace(old, status="OwnerAcceptedWithException", reviewer=None,
136
+ review_date=datetime.now(UTC).date().isoformat(),
137
+ version=old.version + 1)
138
+ self._record(old, new, actor, reason.strip())
139
+ return new
140
+
141
def revise(self, mapping_id: str, *, actor: str, target_statement: str,
142
statement_section: str, note_number: str, subnote_code: str | None) -> MappingDecision:
143
old = self._decisions.get(mapping_id)
backend/src/aram_backend/workbook_inspection.py
-1
@@ -7,7 +7,6 @@ from zipfile import BadZipFile
7
from openpyxl import load_workbook
8
from openpyxl.utils.exceptions import InvalidFileException
9
10
-
10
MAX_WORKSHEETS = 100
11
MAX_HEADER_COLUMNS = 256
12
backend/tests/test_gate3_encrypted_backup.py
new
+37
@@ -0,0 +1,37 @@
1
+"""Synthetic encrypted backup transport: AES-256-GCM, no real ledger data."""
2
+import hashlib
3
+import os
4
+from pathlib import Path
5
+
6
+import pytest
7
+from cryptography.exceptions import InvalidTag
8
+from cryptography.hazmat.primitives.ciphers.aead import AESGCM
9
+
10
+from aram_backend.mapping_store import MappingStore
11
+from aram_backend.mapping_workflow import MappingDecision
12
+
13
+
14
+def test_encrypted_snapshot_restore_and_tamper_rejection(tmp_path: Path):
15
+ store = MappingStore(tmp_path / "source.db")
16
+ ws, rev = store.load("SYNTH", 1405)
17
+ ws.propose(MappingDecision("S1", "SYNTH", 1405, "100", "BS", "Assets", "1", None, 1, "Draft", None, "Synthetic"), actor="synthetic-maker")
18
+ store.save(ws, rev)
19
+ snapshot = tmp_path / "snapshot.db"
20
+ store.backup_to(snapshot)
21
+ key = AESGCM.generate_key(bit_length=256)
22
+ nonce = os.urandom(12)
23
+ aad = b"aram-gate3-synthetic-backup-v1"
24
+ encrypted = nonce + AESGCM(key).encrypt(nonce, snapshot.read_bytes(), aad)
25
+ uploaded = tmp_path / "cloud-copy.enc"
26
+ uploaded.write_bytes(encrypted)
27
+ assert hashlib.sha256(uploaded.read_bytes()).digest() == hashlib.sha256(encrypted).digest()
28
+ decrypted = AESGCM(key).decrypt(uploaded.read_bytes()[:12], uploaded.read_bytes()[12:], aad)
29
+ recovered_path = tmp_path / "restored.db"
30
+ recovered_path.write_bytes(decrypted)
31
+ recovered = MappingStore(recovered_path)
32
+ recovered.verify_integrity()
33
+ assert recovered.load("SYNTH", 1405)[0].decisions == ws.decisions
34
+ tampered = bytearray(encrypted)
35
+ tampered[-1] ^= 1
36
+ with pytest.raises(InvalidTag):
37
+ AESGCM(key).decrypt(tampered[:12], tampered[12:], aad)
\ No newline at end of file
backend/tests/test_gate3_recovery_drill.py
new
+33
@@ -0,0 +1,33 @@
1
+"""Synthetic, isolated Gate 3 backup and recovery evidence."""
2
+import hashlib
3
+from pathlib import Path
4
+
5
+import pytest
6
+
7
+from aram_backend.mapping_store import MappingStore
8
+from aram_backend.mapping_workflow import MappingDecision, MappingWorkflowError
9
+
10
+
11
+def test_sqlite_backup_restore_and_external_receipt_tamper_detection(tmp_path: Path):
12
+ live = MappingStore(tmp_path / "live.db")
13
+ workspace, revision = live.load("TEST", 1405)
14
+ workspace.propose(MappingDecision("TEST-1", "TEST", 1405, "100", "BS", "Assets", "1", None, 1, "Draft", None, "Synthetic"), actor="test-maker")
15
+ revision = live.save(workspace, revision)
16
+ receipt = live.audit_receipt("TEST", 1405)
17
+ assert receipt["revision"] == revision
18
+ backup_path = tmp_path / "snapshot.db"
19
+ live.backup_to(backup_path)
20
+ snapshot_hash = hashlib.sha256(backup_path.read_bytes()).hexdigest()
21
+ assert len(snapshot_hash) == 64
22
+ restored = MappingStore(tmp_path / "restored.db")
23
+ restored_path = Path(restored.path)
24
+ restored_path.write_bytes(backup_path.read_bytes())
25
+ restored.verify_integrity()
26
+ restored.verify_external_receipt(receipt)
27
+ assert restored.load("TEST", 1405)[0].decisions == workspace.decisions
28
+ assert hashlib.sha256(restored_path.read_bytes()).hexdigest() == snapshot_hash
29
+ with pytest.raises(MappingWorkflowError, match="destination must be new"):
30
+ live.backup_to(backup_path)
31
+ forged = dict(receipt, sha256="f" * 64)
32
+ with pytest.raises(MappingWorkflowError, match="external anchor mismatch"):
33
+ restored.verify_external_receipt(forged)
\ No newline at end of file
backend/tests/test_ingestion.py
+3
-3
@@ -127,7 +127,7 @@ def test_duplicate_registration_different_document_type_rejected(session):
127
"content": b"safe-test-bytes-conflict",
128
}
129
130
- first = register_source_document(session, **arguments)
130
+ register_source_document(session, **arguments)
131
session.commit()
132
133
conflict_arguments = arguments.copy()
@@ -151,7 +151,7 @@ def test_duplicate_registration_different_filename_rejected(session):
151
"content": b"safe-test-bytes-conflict-2",
152
}
153
154
- first = register_source_document(session, **arguments)
154
+ register_source_document(session, **arguments)
155
session.commit()
156
157
conflict_arguments = arguments.copy()
@@ -175,7 +175,7 @@ def test_duplicate_registration_different_both_rejected(session):
175
"content": b"safe-test-bytes-conflict-3",
176
}
177
178
- first = register_source_document(session, **arguments)
178
+ register_source_document(session, **arguments)
179
session.commit()
180
181
conflict_arguments = arguments.copy()
backend/tests/test_ledger_parser.py
+2
-3
@@ -6,7 +6,6 @@ from openpyxl import Workbook
6
7
from aram_backend.ledger_parser import LedgerParseError, parse_general_ledger
8
9
-
9
HEADERS = [
10
"حساب",
11
"ACCOUNT_NAME",
@@ -62,8 +61,8 @@ def test_streams_typed_records_without_calculation():
61
assert len(records) == 1
62
assert records[0].row_number == 3
63
assert records[0].account_code == "0001"
65
- assert records[0].opening == Decimal("0")
66
- assert records[0].closing == Decimal("0")
64
+ assert records[0].opening == Decimal(0)
65
+ assert records[0].closing == Decimal(0)
66
67
68
def test_skips_completely_blank_rows():
backend/tests/test_local_auth.py
new
+61
@@ -0,0 +1,61 @@
1
+import pytest
2
+
3
+from aram_backend.local_auth import LocalSessionAuthority, create_credential
4
+
5
+
6
+def test_local_auth_password_session_revocation():
7
+ credential = create_credential("owner", "correct horse battery staple", frozenset({"001"}), frozenset({"maker"}))
8
+ authority = LocalSessionAuthority(credential)
9
+ assert authority.login("wrong password") is None
10
+ token = authority.login("correct horse battery staple")
11
+ assert token and len(token) >= 32
12
+ assert authority.resolve("owner") is None
13
+ assert authority.resolve(token).subject == "owner"
14
+ authority.revoke(token)
15
+ assert authority.resolve(token) is None
16
+ assert LocalSessionAuthority(credential).resolve(token) is None
17
+
18
+
19
+def test_local_auth_rejects_weak_provisioning():
20
+ with pytest.raises(ValueError):
21
+ create_credential("owner", "short", frozenset({"001"}), frozenset({"maker"}))
22
+ with pytest.raises(ValueError):
23
+ LocalSessionAuthority(create_credential("owner", "correct horse battery staple", frozenset({"001"}), frozenset({"maker"})), lifetime_seconds=0)
24
+
25
+def test_local_auth_lockout_and_recovery(monkeypatch):
26
+ import aram_backend.local_auth as auth
27
+
28
+ now = [100.0]
29
+ monkeypatch.setattr(auth.time, "monotonic", lambda: now[0])
30
+ credential = create_credential("owner", "correct horse battery staple",
31
+ frozenset({"001"}), frozenset({"owner"}))
32
+ authority = LocalSessionAuthority(credential, max_failed_attempts=2, lockout_seconds=30)
33
+ assert authority.login("wrong") is None
34
+ assert authority.login("wrong") is None
35
+ assert authority.login("correct horse battery staple") is None
36
+ now[0] += 31
37
+ token = authority.login("correct horse battery staple")
38
+ assert token is not None
39
+
40
+
41
+def test_local_auth_session_limit_and_revoke_all():
42
+ credential = create_credential("owner", "correct horse battery staple",
43
+ frozenset({"001"}), frozenset({"owner"}))
44
+ authority = LocalSessionAuthority(credential, max_sessions=1)
45
+ token = authority.login("correct horse battery staple")
46
+ assert token is not None
47
+ assert authority.login("correct horse battery staple") is None
48
+ authority.revoke_all()
49
+ assert authority.resolve(token) is None
50
+ assert authority.login("correct horse battery staple") is not None
51
+
52
+
53
+def test_local_auth_rejects_unknown_roles_and_oversized_password():
54
+ with pytest.raises(ValueError):
55
+ create_credential("owner", "correct horse battery staple",
56
+ frozenset({"001"}), frozenset({"superadmin"}))
57
+ credential = create_credential("owner", "correct horse battery staple",
58
+ frozenset({"001"}), frozenset({"owner"}))
59
+ authority = LocalSessionAuthority(credential)
60
+ assert authority.login("x" * 1025) is None
61
+ assert authority.resolve("x" * 1000) is None
backend/tests/test_mapping_access.py
+1
@@ -1,5 +1,6 @@
1
2
import pytest
3
+
4
from aram_backend.mapping_access import AuthenticatedPrincipal, MappingAccess
5
from aram_backend.mapping_workflow import (
6
MappingDecision,
backend/tests/test_mapping_api.py
+2
-1
@@ -1,8 +1,9 @@
1
+from fastapi.testclient import TestClient
2
+
3
from aram_backend.main import app
4
from aram_backend.mapping_access import AuthenticatedPrincipal
5
from aram_backend.mapping_api import configure_mapping_service, reset_mapping_service
6
from aram_backend.mapping_store import MappingStore
5
-from fastapi.testclient import TestClient
7
8
9
def test_mapping_http_fail_closed_and_three_party_approval(tmp_path):
backend/tests/test_mapping_hash_chain.py
+1
@@ -1,6 +1,7 @@
1
import sqlite3
2
3
import pytest
4
+
5
from aram_backend.mapping_store import MappingStore
6
from aram_backend.mapping_workflow import MappingDecision, MappingWorkflowError
7
backend/tests/test_mapping_receipts.py
+1
@@ -1,6 +1,7 @@
1
import sqlite3
2
3
import pytest
4
+
5
from aram_backend.mapping_access import MappingAccess
6
from aram_backend.mapping_receipts import ReceiptArchive
7
from aram_backend.mapping_store import MappingStore
backend/tests/test_mapping_recovery_quality.py
+4
-2
@@ -2,6 +2,7 @@ import sqlite3
2
from dataclasses import replace
3
4
import pytest
5
+
6
from aram_backend.mapping_quality import assess_mapping_quality
7
from aram_backend.mapping_store import MappingStore
8
from aram_backend.mapping_workflow import MappingDecision, MappingWorkflowError
@@ -62,13 +63,14 @@ def test_quality_never_auto_approves_ambiguous_accounts():
63
def test_workbook_mapping_notes_preserved_on_roundtrip():
64
from io import BytesIO
65
66
+ from openpyxl import load_workbook
67
+ from test_pilot_workbook import valid_rows, workbook_bytes
68
+
69
from aram_backend.mapping_workflow import (
70
export_pilot_mapping_workbook,
71
import_mapping_workbook,
72
)
73
from aram_backend.pilot_workbook import SHEET_HEADERS
70
- from openpyxl import load_workbook
71
- from test_pilot_workbook import valid_rows, workbook_bytes
74
75
wb = load_workbook(BytesIO(workbook_bytes(valid_rows())))
76
columns = SHEET_HEADERS["Mapping"]
backend/tests/test_mapping_store.py
+3
-2
@@ -3,6 +3,9 @@ from dataclasses import replace
3
from io import BytesIO
4
5
import pytest
6
+from openpyxl import load_workbook
7
+from test_pilot_workbook import valid_rows, workbook_bytes
8
+
9
from aram_backend.mapping_store import MappingStore
10
from aram_backend.mapping_workflow import (
11
MappingDecision,
@@ -10,8 +13,6 @@ from aram_backend.mapping_workflow import (
13
export_pilot_mapping_workbook,
14
import_mapping_workbook,
15
)
13
-from openpyxl import load_workbook
14
-from test_pilot_workbook import valid_rows, workbook_bytes
16
17
18
def decision():
backend/tests/test_mapping_workflow.py
+3
-2
@@ -2,6 +2,9 @@ from dataclasses import replace
2
from io import BytesIO
3
4
import pytest
5
+from openpyxl import load_workbook
6
+from test_pilot_workbook import valid_rows, workbook_bytes
7
+
8
from aram_backend.mapping_workflow import (
9
MappingDecision,
10
MappingWorkflowError,
@@ -9,8 +12,6 @@ from aram_backend.mapping_workflow import (
12
export_mapping_rows,
13
import_mapping_workbook,
14
)
12
-from openpyxl import load_workbook
13
-from test_pilot_workbook import valid_rows, workbook_bytes
15
16
17
def sample(*, year=1405, company="001", status="Draft"):
backend/tests/test_owner_acceptance.py
new
+121
@@ -0,0 +1,121 @@
1
+import pytest
2
+
3
+from aram_backend.mapping_store import MappingStore
4
+from aram_backend.mapping_workflow import MappingDecision, MappingWorkflowError
5
+
6
+
7
+def test_owner_exception_persists_reason_and_does_not_approve(tmp_path):
8
+ store = MappingStore(tmp_path / "owner.db")
9
+ space, revision = store.load("001", 1405)
10
+ space.propose(MappingDecision("M1", "001", 1405, "100", "BS", "Assets", "1", None, 1, "Draft", None, "Manual"), actor="owner")
11
+ with pytest.raises(MappingWorkflowError, match="reason"):
12
+ space.owner_accept("M1", actor="owner", reason="too short")
13
+ accepted = space.owner_accept("M1", actor="owner", reason="Owner knowingly accepts missing independent review")
14
+ assert accepted.status == "OwnerAcceptedWithException"
15
+ assert accepted.reviewer is None
16
+ assert space.audit[-1].reason.startswith("Owner knowingly")
17
+ store.save(space, revision)
18
+ loaded, _ = store.load("001", 1405)
19
+ assert loaded.decisions[0].status != "Approved"
20
+ assert loaded.audit[-1].reason == space.audit[-1].reason
21
+ store.verify_integrity()
22
+ with pytest.raises(MappingWorkflowError, match="invalid mapping lifecycle"):
23
+ loaded.transition("M1", "Approved", actor="owner")
24
+
25
+
26
+def test_owner_exception_cannot_be_made_from_reviewed(tmp_path):
27
+ store = MappingStore(tmp_path / "owner2.db")
28
+ space, _ = store.load("001", 1405)
29
+ space.propose(MappingDecision("M1", "001", 1405, "100", "BS", "Assets", "1", None, 1, "Draft", None, "Manual"), actor="maker")
30
+ space.transition("M1", "Reviewed", actor="reviewer")
31
+ with pytest.raises(MappingWorkflowError, match="unreviewed Draft"):
32
+ space.owner_accept("M1", actor="maker", reason="I acknowledge missing independent approval")
33
+
34
+def test_owner_http_is_scoped_and_never_independent_approval(tmp_path):
35
+ from fastapi.testclient import TestClient
36
+
37
+ from aram_backend.main import app
38
+ from aram_backend.mapping_access import AuthenticatedPrincipal
39
+ from aram_backend.mapping_api import (
40
+ configure_mapping_service,
41
+ reset_mapping_service,
42
+ )
43
+
44
+ people = {
45
+ "owner-token": AuthenticatedPrincipal("owner", frozenset({"001"}), frozenset({"owner", "maker"})),
46
+ "maker-token": AuthenticatedPrincipal("maker", frozenset({"001"}), frozenset({"maker"})),
47
+ "foreign-token": AuthenticatedPrincipal("other", frozenset({"002"}), frozenset({"owner"})),
48
+ }
49
+ store = MappingStore(tmp_path / "http-owner.db")
50
+ configure_mapping_service(store=store, identity_resolver=people.get)
51
+ try:
52
+ client = TestClient(app)
53
+ base = "/api/v1/mapping/001/1405"
54
+ def post(path, token, data):
55
+ return client.post(base + path, headers={"Authorization": "Bearer " + token}, json=data)
56
+ proposal = {"mapping_id": "M1", "account_full_code": "100", "target_statement": "BS", "statement_section": "Assets", "note_number": "1"}
57
+ assert post("/proposals", "maker-token", proposal).status_code == 200
58
+ path = "/M1/owner-accept"
59
+ reason = {"reason": "Owner explicitly accepts the lack of independent review"}
60
+ assert post(path, "maker-token", reason).status_code == 403
61
+ assert post(path, "foreign-token", reason).status_code == 403
62
+ assert post(path, "owner-token", {"reason": "short"}).status_code == 422
63
+ result = post(path, "owner-token", reason)
64
+ assert result.status_code == 200, result.text
65
+ assert result.json()["status"] == "OwnerAcceptedWithException"
66
+ assert post("/M1/approve", "owner-token", {}).status_code == 403
67
+ store.verify_integrity()
68
+ assert store.audit_log("001", 1405)[-1].reason == reason["reason"]
69
+ finally:
70
+ reset_mapping_service()
71
+
72
+def test_owner_api_requires_trusted_owner_role(tmp_path):
73
+ from fastapi.testclient import TestClient
74
+
75
+ from aram_backend.main import app
76
+ from aram_backend.mapping_access import AuthenticatedPrincipal
77
+ from aram_backend.mapping_api import (
78
+ configure_mapping_service,
79
+ reset_mapping_service,
80
+ )
81
+ store = MappingStore(tmp_path / "owner-api.db")
82
+ people = {
83
+ "maker": AuthenticatedPrincipal("owner", frozenset({"001"}), frozenset({"maker"})),
84
+ "owner": AuthenticatedPrincipal("owner", frozenset({"001"}), frozenset({"owner"})),
85
+ "foreign": AuthenticatedPrincipal("other", frozenset({"002"}), frozenset({"owner"})),
86
+ }
87
+ configure_mapping_service(store=store, identity_resolver=people.get)
88
+ client = TestClient(app)
89
+ base = "/api/v1/mapping/001/1405"
90
+ try:
91
+ payload = {"mapping_id": "M1", "account_full_code": "100", "target_statement": "BS",
92
+ "statement_section": "Assets", "note_number": "1"}
93
+ assert client.post(base + "/proposals", headers={"Authorization": "Bearer maker"}, json=payload).status_code == 200
94
+ path = base + "/M1/owner-accept"
95
+ body = {"reason": "Owner acknowledges missing independent review"}
96
+ assert client.post(path, json=body).status_code == 401
97
+ assert client.post(path, headers={"Authorization": "Bearer maker"}, json=body).status_code == 403
98
+ assert client.post(path, headers={"Authorization": "Bearer foreign"}, json=body).status_code == 403
99
+ assert client.post(path, headers={"Authorization": "Bearer owner"}, json={"reason": "short"}).status_code == 422
100
+ result = client.post(path, headers={"Authorization": "Bearer owner"}, json=body)
101
+ assert result.status_code == 200
102
+ assert result.json()["status"] == "OwnerAcceptedWithException"
103
+ assert store.load("001", 1405)[0].audit[-1].reason == body["reason"]
104
+ assert client.post(base + "/M1/approve", headers={"Authorization": "Bearer owner"}).status_code == 403
105
+ finally:
106
+ reset_mapping_service()
107
+
108
+def test_owner_acceptance_is_included_in_audit_hash(tmp_path):
109
+ import sqlite3
110
+
111
+ from aram_backend.mapping_integrity import audit_chain
112
+ store = MappingStore(tmp_path / "hash-owner.db")
113
+ space, revision = store.load("001", 1405)
114
+ space.propose(MappingDecision("M1", "001", 1405, "100", "BS", "Assets", "1", None, 1, "Draft", None, "Manual"), actor="maker")
115
+ space.owner_accept("M1", actor="owner", reason="Owner accepts the missing independent approval")
116
+ store.save(space, revision)
117
+ expected = audit_chain(store.audit_log("001", 1405))[-1]
118
+ with sqlite3.connect(store.path) as conn:
119
+ actual = conn.execute("SELECT digest FROM mapping_audit_hash ORDER BY sequence DESC LIMIT 1").fetchone()[0]
120
+ assert actual == expected
121
+ assert store.audit_receipt("001", 1405)["sha256"] == expected
\ No newline at end of file
backend/tools/gate3_synthetic_cloud_drill.py
new
+36
@@ -0,0 +1,36 @@
1
+"""One-time synthetic encrypted Drive sync drill. No real data, no key on Drive."""
2
+import hashlib
3
+import json
4
+import os
5
+import secrets
6
+from pathlib import Path
7
+from tempfile import TemporaryDirectory
8
+
9
+from cryptography.hazmat.primitives.ciphers.aead import AESGCM
10
+
11
+from aram_backend.mapping_store import MappingStore
12
+from aram_backend.mapping_workflow import MappingDecision
13
+
14
+remote = Path(r"E:\My Drive\Aram-Gate3-Synthetic-Backup")
15
+if not remote.is_dir():
16
+ raise RuntimeError("Drive destination unavailable")
17
+with TemporaryDirectory(prefix="aram-gate3-") as td:
18
+ temp = Path(td)
19
+ store = MappingStore(temp / "source.db")
20
+ ws, rev = store.load("SYNTH", 1405)
21
+ ws.propose(MappingDecision("TEST", "SYNTH", 1405, "100", "BS", "Assets", "1", None, 1, "Draft", None, "Synthetic"), actor="test-maker")
22
+ store.save(ws, rev)
23
+ receipt = store.audit_receipt("SYNTH", 1405)
24
+ snapshot = temp / "snapshot.db"
25
+ store.backup_to(snapshot)
26
+ key = AESGCM.generate_key(bit_length=256)
27
+ nonce = os.urandom(12)
28
+ aad = b"aram-gate3-synthetic-cloud-drill-v1"
29
+ ciphertext = nonce + AESGCM(key).encrypt(nonce, snapshot.read_bytes(), aad)
30
+ name = "gate3-synthetic-" + secrets.token_hex(8) + ".aesgcm"
31
+ target = remote / name
32
+ if target.exists():
33
+ raise RuntimeError("Refusing overwrite")
34
+ target.write_bytes(ciphertext)
35
+ print(json.dumps({"file":name,"encrypted_size":len(ciphertext),"sha256":hashlib.sha256(ciphertext).hexdigest(),"receipt":receipt,"status":"encrypted_uploaded_to_windows_drive_mount; cloud_readback_not_yet_verified"}))
36
+ # Deliberately do not save the ephemeral key or financial plaintext to Drive.
\ No newline at end of file
backend/tools/gate3_synthetic_cloud_restore.py
new
+79
@@ -0,0 +1,79 @@
1
+"""Synthetic-only encrypted backup and isolated restore via Drive mount.
2
+
3
+This verifies the mounted copy, NOT an independent cloud API download.
4
+No real data, persistent key, or credential is used.
5
+"""
6
+import hashlib
7
+import json
8
+import os
9
+import secrets
10
+import tempfile
11
+from pathlib import Path
12
+
13
+from cryptography.exceptions import InvalidTag
14
+from cryptography.hazmat.primitives.ciphers.aead import AESGCM
15
+
16
+from aram_backend.mapping_store import MappingStore
17
+from aram_backend.mapping_workflow import MappingDecision
18
+
19
+
20
+def main():
21
+ drive = Path("E:/My Drive/Aram-Gate3-Synthetic-Backup")
22
+ if not drive.is_dir():
23
+ raise RuntimeError("Google Drive mount not available")
24
+ with tempfile.TemporaryDirectory(prefix="aram-gate3-") as directory:
25
+ root = Path(directory)
26
+ source = MappingStore(root / "source.db")
27
+ workspace, revision = source.load("SYNTH", 1405)
28
+ workspace.propose(
29
+ MappingDecision("RESTORE-TEST", "SYNTH", 1405, "100", "BS",
30
+ "Assets", "1", None, 1, "Draft", None, "Synthetic"),
31
+ actor="synthetic-test",
32
+ )
33
+ source.save(workspace, revision)
34
+ receipt = source.audit_receipt("SYNTH", 1405)
35
+ snapshot = root / "snapshot.db"
36
+ source.backup_to(snapshot)
37
+ plaintext = snapshot.read_bytes()
38
+ key = AESGCM.generate_key(bit_length=256)
39
+ nonce = os.urandom(12)
40
+ associated_data = b"aram-gate3-synthetic-restore-v1"
41
+ encrypted = nonce + AESGCM(key).encrypt(nonce, plaintext, associated_data)
42
+ filename = "gate3-restore-" + secrets.token_hex(8) + ".aesgcm"
43
+ remote = drive / filename
44
+ with remote.open("xb") as handle:
45
+ handle.write(encrypted)
46
+ readback = remote.read_bytes()
47
+ if hashlib.sha256(readback).digest() != hashlib.sha256(encrypted).digest():
48
+ raise RuntimeError("mounted readback digest mismatch")
49
+ decrypted = AESGCM(key).decrypt(readback[:12], readback[12:], associated_data)
50
+ if hashlib.sha256(decrypted).digest() != hashlib.sha256(plaintext).digest():
51
+ raise RuntimeError("decrypted database digest mismatch")
52
+ restored = MappingStore(root / "restored.db")
53
+ Path(restored.path).write_bytes(decrypted)
54
+ restored.verify_integrity()
55
+ restored.verify_external_receipt(receipt)
56
+ if restored.load("SYNTH", 1405)[0].decisions != workspace.decisions:
57
+ raise RuntimeError("restored mapping mismatch")
58
+ tampered = bytearray(readback)
59
+ tampered[-1] ^= 1
60
+ try:
61
+ AESGCM(key).decrypt(tampered[:12], tampered[12:], associated_data)
62
+ except InvalidTag:
63
+ pass
64
+ else:
65
+ raise RuntimeError("tamper detection failed")
66
+ print(json.dumps({
67
+ "status": "PASS",
68
+ "file": filename,
69
+ "ciphertext_sha256": hashlib.sha256(readback).hexdigest(),
70
+ "sqlite_integrity": True,
71
+ "audit_receipt": True,
72
+ "tamper_rejected": True,
73
+ "independent_cloud_download": False,
74
+ "real_financial_data": False,
75
+ }))
76
+
77
+
78
+if __name__ == "__main__":
79
+ main()
docs/GATE3_PACKAGE8_EXECUTION_REPORT_20261103.md
new
+66
@@ -0,0 +1,66 @@
1
+# Gate 3 — Package 8 execution report (2026-11-03)
2
+
3
+## Decision
4
+**NO-GO — Gate 3 remains unaccepted.** This execution completed local code-quality repairs and regression verification, but did not and cannot manufacture external operational evidence or independent approval.
5
+
6
+## Execution baseline
7
+- Device: Aram (Windows, online during execution).
8
+- Repository: davoodmehraban89/Aram.
9
+- Branch: `feat/gate3-governed-mapping-20261101`.
10
+- HEAD: `9d346f098a0a2159d96080715322879b08d9a1f8`, matching Draft PR #82 head at inspection.
11
+- Approved base: `source-data-cleanup@7dc864fd032f0c4ae4d650d89304a01286a6d914`.
12
+- Existing local modifications were preserved. No reset, clean, checkout, commit, push, merge, release or canonical financial-data mutation was performed.
13
+- `git diff --name-only <approved-base> -- data samples` returned no paths.
14
+
15
+## Seven-stage result matrix
16
+
17
+| Stage | Result | Evidence / remaining condition |
18
+|---|---|---|
19
+| 1. Authentication and security | PARTIAL | Hardened local single-owner prototype with PBKDF2-HMAC-SHA256 (600,000 iterations), input bounds, role allow-list, bounded in-memory lockout, session cap, expiry pruning, thread lock and revoke-all. Regression tests pass. Not connected to FastAPI; no durable credential provisioning, Windows DPAPI secret storage, multi-user lifecycle or cross-process rate limiting. Not production authentication. |
20
+| 2. Database and audit | PARTIAL | Existing SQLite versioning, optimistic concurrency, hash chain and receipt verification tests remain green. Receipt archive is only a local directory adapter; no separately administered immutable/WORM anchor or privileged-admin tamper protection was demonstrated. |
21
+| 3. Backup and recovery | PARTIAL | Existing synthetic AES-256-GCM backup/restore and tamper-rejection tests pass; prior synthetic Drive transfer/readback evidence exists. Encryption keys in synthetic drills are ephemeral. No DPAPI-protected recoverable production key, rotation, scheduled retention, alerting or witnessed operational DR drill/RPO/RTO evidence. |
22
+| 4. Financial mapping and Excel | PARTIAL | Mapping lifecycle, company/year scoping, conservative ambiguity and workbook roundtrip regression tests pass. No authorized real ledger reconciliation, signed finance exception disposition or independent financial acceptance. |
23
+| 5. Hard testing and quality | PASS LOCALLY | 110/110 backend tests pass; Ruff passes for src/tests/tools/migrations; compileall passes; pip check passes; Alembic SQLite upgrade and downgrade round-trip pass; git diff --check passes. One Starlette/httpx TestClient deprecation warning remains. |
24
+| 6. Three reviews | SELF-REVIEW ONLY | Functional QA, security/architecture audit and adversarial/edge-case review were performed sequentially by the same assistant. They are not independent approvals. Findings are listed below. |
25
+| 7. Handoff and Gate 3 closure | BLOCKED | PR #82 remains Draft; current local modifications are not committed/pushed, so remote CI does not include this execution. No independent GitHub review exists. Final decision remains NO-GO. |
26
+
27
+## Code and CI changes made locally
28
+- Added Ruff to backend `test` optional dependencies.
29
+- Added a Ruff check step to `.github/workflows/backend-ci.yml`.
30
+- Resolved 30 Ruff findings across import ordering, unused f-prefixes, a row-value closure binding, an overly broad AES-GCM exception assertion and unused local assignments.
31
+- Bound the current ledger row explicitly in the row accessor.
32
+- Tightened AES-GCM tamper test to expect `InvalidTag`.
33
+- Hardened local auth prototype and added lockout/session-boundary tests.
34
+- Appended execution evidence to `PROJECT_STATUS.md` and `docs/PROJECT_LOG.md`.
35
+
36
+## Verification evidence
37
+- Pytest collection: 110 tests.
38
+- Full local pytest: 110/110 PASS.
39
+- Ruff: PASS on `src tests tools migrations`.
40
+- Python compileall: PASS.
41
+- pip check: PASS.
42
+- Alembic SQLite migration: upgrade head PASS; downgrade base PASS using a temporary database, which was removed.
43
+- git diff --check: PASS (Git emits LF/CRLF advisory warnings only).
44
+- Existing remote CI for unchanged PR head: Backend CI run https://github.com/davoodmehraban89/Aram/actions/runs/41339488244 — SUCCESS. This run predates Package 8 local changes and does NOT verify them.
45
+
46
+## Three review passes (not independent)
47
+1. Functional QA: 110/110 tests, Ruff, compileall, pip check and migration round-trip pass.
48
+2. Security/architecture: identified production blockers: local auth is not wired/provisioned, lockout is process-local, credentials are not DPAPI protected, receipt archive is not independently administered, synthetic backup key is ephemeral, and real financial data is not reconciled.
49
+3. Edge-case/misuse: added tests for repeated invalid login lockout, lockout expiry, maximum sessions, revoke-all, invalid roles and oversized password/token inputs. Existing mapping tests cover company/year scope, concurrent revisions and tamper checks. Cross-process auth abuse and actual Windows profile recovery remain untested.
50
+
51
+## Mandatory blockers and accountable functions
52
+1. **Owner / identity administrator:** supply and approve identity provisioning model and credential recovery procedure; enable secure local owner setup or a trusted IdP, and approve API integration tests.
53
+2. **Owner / security administrator:** approve a separate immutable audit anchor, access policy, retention, and witnessed tamper drill.
54
+3. **Owner / operations:** approve DPAPI key recovery/rotation design and schedule; run a witnessed recovery drill from an independently downloaded cloud object, measuring RPO/RTO.
55
+4. **Finance process owner (owner may fulfil this role):** authorize exact source-ledger hashes, sign mapping reconciliation, and disposition all material/ambiguous exceptions.
56
+5. **Independent reviewer:** named reviewer must inspect exact remote SHA, complete diff, CI, security/financial evidence and submit an attributable GitHub review. Owner approval is not independent review.
57
+
58
+## Safe decisions
59
+- No canonical financial file or database was modified.
60
+- No destructive Git operation was performed.
61
+- No commit or push was made because the worktree contains pre-existing mixed changes and the remote PR acceptance policy requires a reviewed, focused candidate; the local changes have not yet been isolated into a reviewed commit.
62
+- No Merge, Release or Gate 4 implementation.
63
+- No GO claim is made from local tests or assistant self-review.
64
+
65
+## Next admissible action
66
+Resolve the named external evidence blockers and then create a focused, reviewed candidate from a clean, verified worktree. Only after new candidate CI and independent review pass may Gate 3 acceptance be reconsidered.
docs/GATE3_PACKAGE9_BASELINE_20261103.md
new
+34
@@ -0,0 +1,34 @@
1
+# Gate 3 — Package 9 baseline and acceptance register
2
+Date: 2026-11-03 (local Windows)
3
+Decision: **NO-GO pending seven stage gates**
4
+
5
+## Scope and frozen reference
6
+- Windows device: Aram.
7
+- Repository: davoodmehraban89/Aram.
8
+- Branch: `feat/gate3-governed-mapping-20261101`.
9
+- HEAD before Package 9 changes: `9d346f098a0a2159d96080715322879b08d9a1f8`.
10
+- Pre-existing dirty worktree: 23 tracked modified files and 10 untracked files.
11
+- Non-destructive baseline snapshot: `%LOCALAPPDATA%\Aram\Gate3Package9\20261103-153013`.
12
+- Snapshot includes full copies of all 23 modified tracked files, all 10 untracked files, SHA-256 manifest for both groups, git status, HEAD and branch, plus a diagnostic patch. Full-file snapshot SHA-256 verification: **0 failures** in each group.
13
+- **Caution:** `git apply --check --reverse` against the diagnostic patch failed due to worktree/patch context differences; do NOT rely on this patch as a verified rollback mechanism. The hash-verified full-file snapshot is the recovery reference. No restore was performed.
14
+- Existing code and financial data were not reset, merged or published. Do not treat this local snapshot as an off-machine backup or an immutable archive.
15
+
16
+## Gate-by-gate acceptance
17
+1. Baseline and isolated candidate: evidence inventory, clean isolated branch/worktree, secret screening, full regression and exact SHA CI. **OPEN**; baseline snapshot done, isolation/CI pending.
18
+2. Local Windows identity: secure provisioning/recovery, protected credential storage, API enforcement, role/company/year authorization, persistent lockout and session revocation, security negative tests. **OPEN**.
19
+3. SQLite and audit: transactional consistency, receipt chain, independently administered immutable receipt anchor, tamper test and retention proof. **OPEN**.
20
+4. Backup: protected recoverable production key, rotation and escrow, scheduled encrypted backup, independent cloud download, isolated restore, witnessed RPO/RTO and alerts. **OPEN**.
21
+5. Financial reconciliation: synthetic regression first; real source only after explicit separate authorization, hashed source and finance-owner signed exception disposition. **OPEN**.
22
+6. Testing and independent reviews: local tests, CI on exact SHA, adversarial checks, independent financial/security/technical signoffs. **OPEN**.
23
+7. Final dossier and GO/NO-GO: all required controls PASS, named approvers, evidence links and final decision. **OPEN**.
24
+
25
+## Non-negotiable controls
26
+- No canonical financial-data edits without a separate authorization.
27
+- No secrets in Git, logs or cloud backup metadata.
28
+- No merge or release without a separate authorization.
29
+- No fabricated independent reviewer approval.
30
+- No promotion of synthetic restore results into operational DR acceptance.
31
+- Stop and report exact external dependencies; never convert missing evidence into PASS.
32
+
33
+## Immediate next work
34
+Verify test result, prepare isolated candidate without disturbing dirty worktree, then implement/test identity and recovery improvements with synthetic-only data. Report stage status as PASS only when its own acceptance conditions are proven.
docs/GATE3_PERSONAL_WINDOWS_ARCHITECTURE_DRAFT.md
new
+81
@@ -0,0 +1,81 @@
1
+# Gate 3 - Personal Windows Deployment Decision (DRAFT)
2
+
3
+Status: PROPOSED / NOT ACCEPTED. This document does not waive the existing acceptance policy.
4
+
5
+## Verified environment (2026-11-02)
6
+- Windows 10.0.22631; Python 3.12.10 installed at user-local Python312 path.
7
+- Isolated environment: backend/.venv, Python 3.12.10, pip 25.0.1.
8
+- Standard pip install -e '.[test]' failed on uvicorn[standard] dependency resolution; pinned uvicorn attempt failed resolving websockets from available package index.
9
+- Installing required backend dependencies with plain uvicorn (without standard extras) succeeded; backend tests on Windows passed (pytest exit 0).
10
+- Existing Ubuntu CI on head 9d346f098a0a2159d96080715322879b08d9a1f8: SUCCESS (run 41339488244).
11
+- No live identity resolver, independent receipt store, financial reconciliation or operational recovery evidence established.
12
+
13
+## Threat model and boundaries
14
+- Intended initial deployment: one authorized operator, Windows personal computer, local-only API binding to 127.0.0.1; no LAN or public exposure by default.
15
+- Threats: stolen Windows session, malicious local process, unauthorized local file changes, lost device, ransomware, disk failure, accidental financial mapping mistakes.
16
+- Same-host administrator can alter application/database/receipts. A local hash chain or directory cannot guarantee privileged tamper resistance. Independent protected offline/off-host receipts and backup are required for such a claim.
17
+- No corporate identity provider, organization infrastructure or corporate access is assumed.
18
+
19
+## Owner acceptance vs independent approval
20
+- Current mapping workflow requires distinct maker/reviewer/approver identities. Never create fictitious users or reuse the same person under multiple identities.
21
+- Proposed future owner-acceptance mode MUST be a distinct explicitly labeled decision (e.g., OwnerAcceptedWithException), NOT a fabricated Reviewed/Approved transition.
22
+- A financial mapping accepted solely by its maker must remain marked as lacking independent review, with risk acknowledgement, reason, timestamp, source hash and append-only audit event.
23
+- Existing Approved-only financial export rules must not be silently bypassed; any changed downstream contract requires dedicated tests and explicit owner signoff.
24
+- GitHub independent code review remains a separate acceptance requirement under docs/ACCEPTANCE_POLICY.md until explicitly and defensibly revised.
25
+
26
+## Required acceptance evidence
27
+1. Windows reproducible install with version constraints and successful pytest + smoke tests.
28
+2. Verified local authentication/session management and negative authorization tests.
29
+3. Trusted independent receipt/backup location and tamper drill, with limitations documented.
30
+4. Authorized source-ledger hashes, full reconciliation and exception disposition.
31
+5. Isolated recovery drill with measured RPO/RTO and integrity checks.
32
+6. Independent review of exact remote SHA, diff, tests, risks and documented decision.
33
+
34
+## Explicit restrictions
35
+- NO-GO until evidence above is verified; no Merge, Release or Gate 4 implementation.
36
+- Never modify canonical data/, samples/ XLSX/PDF or original ledgers as part of setup.
37
+- No acceptance of fake independence or weakening controls merely to achieve a GO label.
38
+## Implementation update (2026-11-02; uncommitted)
39
+- Added `OwnerAcceptedWithException` as an explicitly non-Approved mapping status, with reason on the audit event and persistent-store transition validation; tests cover persistence, forbidden conversion to Approved and rejection of invalid acceptance.
40
+- Added opt-in `local_auth.py` password hashing (PBKDF2-HMAC-SHA256, random salt, 600,000 iterations), opaque short-lived in-memory sessions, revocation and tests. NOT connected to API or provisioned with a real owner credential. This is a prototype security component, NOT an authenticated deployment.
41
+- Local auth still requires persistent secure credential provisioning, rate limiting, logout/session lifecycle, OS storage permissions, localhost-only deployment enforcement and security review before enablement.
42
+- Owner acceptance is not exposed through HTTP until a verified owner role, secure resolver and complete audit controls are in place. Existing independent approval flow remains unchanged.
43
+- The audit reason is persisted but the current receipt hash chain must be reviewed for coverage and external anchoring. Do not treat local DB integrity as protection against privileged tampering.
44
+- Full backend test suite passed on Windows after changes. Gate 3 remains NO-GO.
45
+## Google Drive destination and verification boundary (2026-11-02)
46
+- User-designated remote destination: Aram / Gate3-Encrypted-Backup-And-Receipts (Drive folder ID `18iJA_5eYmAGTCakS64regINrrW4bP9K7`). Folder creation confirmed via connected Google Drive.
47
+- No source ledger, financial workbook, unencrypted DB, credential, key, or real receipt has been uploaded.
48
+- Drive folder existence does NOT establish independent immutable retention or tested recovery. Operator deletion and modification remain possible without additional controls.
49
+- Current connector upload requires a materializable connector file reference; remote Desktop Commander paths are not automatically connector file references. The Windows Drive sync client was not detected. Transport must be validated before claiming an uploaded backup.
50
+- For future real backups: create an isolated SQLite snapshot, encrypt before upload, keep decryption secret outside Drive, upload a versioned file, read back and verify digest, then perform an isolated restore drill. Do not export canonical source ledgers by default.
51
+- Owner-accept API is available only when a trusted resolver is explicitly configured. A maker or outsider cannot self-assert owner privileges through request bodies or headers. It is NOT an independent approval and must not unlock Approved-only exports.
52
+## Owner exception API update
53
+- HTTP route POST `/api/v1/mapping/{company}/{year}/{mapping_id}/owner-accept` added behind the existing trusted resolver and company-scope authorization. Requires explicit `owner` role, reason length 15-2000, and stores `OwnerAcceptedWithException` (not `Approved`).
54
+- Verified unauthorized maker/foreign-company requests fail, weak reason fails, legitimate mock owner succeeds, reason is persisted, and reason is covered by the terminal audit hash/receipt. Tests use synthetic data only.
55
+- Do not mistake test identities for production authentication: no live owner account has been provisioned. Real local identity provisioning, login rate limits, credential storage and secure startup are still required before enabling mapping service.
56
+- Single-host local backup remains a recovery test only, not independent or immutable off-host protection. No Gate 3 GO.
57
+## Synthetic recovery drill and Drive mount check (2026-11-02)
58
+- GoogleDriveFS process verified running; Windows E: drive volume name `Google Drive`, with `E:\My Drive` mounted.
59
+- Connected Google Drive account contains `Aram` folder and the new Gate3 folder, but these folders were NOT present in the local E: My Drive enumeration. Do not assume both connections represent the same account or that the folder is synced; no blind copy to E: was performed.
60
+- Added `test_gate3_recovery_drill.py`: synthetic mapping -> SQLite consistent snapshot -> separate restore -> DB/hash-chain verification -> external receipt check -> overwrite rejection -> forged receipt rejection. Test passed on Windows.
61
+- Full backend pytest suite now 105 tests passed, exit 0. This is a synthetic local DR exercise, not remote Drive restore, and no real financial dataset was used.
62
+- Still NO-GO: encrypted remote upload/readback, off-host tamper protection, real owner provisioning, independent review and authorized financial reconciliation outstanding.
63
+## Verified Google Drive sync transport (2026-11-02)
64
+- User confirmed the Windows Google Drive and connected ChatGPT Google Drive account are the same.
65
+- Windows `GoogleDriveFS` running; E: mounted as Google Drive.
66
+- Created non-sensitive 66-byte probe `E:\My Drive\Gate3-Sync-Probe-Aram-20261102.txt`, subsequently observed by Google Drive connector (ID `1lowDeB-DcY8erRjt0Fy_mFYv9KN4fxAx`). This verifies Windows-to-cloud sync for a harmless text file.
67
+- Created `E:\My Drive\Aram-Gate3-Synthetic-Backup`, subsequently observed in Google Drive (folder ID `1n6xN_2Cj-mRrNpryWI5I14CH6r8pPoSF`). This is a separate Windows-synced folder; do not confuse it with the connector-created Aram/Gate3 folder.
68
+- Attempt to install `cryptography` in isolated backend venv failed with `files.pythonhosted.org` read timeout (exit 2); no encryption or cloud DB upload claimed. No unencrypted DB was copied to Drive.
69
+- Before real backup: install a vetted authenticated-encryption implementation; ensure keys remain off Drive; test encryption, tamper rejection, cloud upload/download and isolated restore. Existing cloud folder alone is not immutable evidence.
70
+## Verified encrypted synthetic cloud round-trip (2026-11-02 evening)
71
+- `cryptography>=44,<47` installed successfully into isolated backend venv (pip exit 0). Added AES-256-GCM synthetic encryption and tamper-rejection test.
72
+- Synthetic-only encrypted SQLite file `gate3-synthetic-983822252fea33db.aesgcm` uploaded via Windows E: mount. Google Drive direct file metadata verified ID `1gHK6nDMJs7fj0HQycNyMROnigLspjsC_`, parent `1n6xN_2Cj-mRrNpryWI5I14CH6r8pPoSF`, size 28700 bytes.
73
+- Fetched file independently through connected Google Drive and verified downloaded bytes SHA-256 `b05a3b8510b8855b00bf3db84f935a8b6802a315c992853d529c56c70811e9b0` equals original Windows hash. Cloud transfer + readback integrity PASS.
74
+- IMPORTANT: original one-off cloud drill script generated an ephemeral in-memory key and discarded it after process exit; this particular cloud ciphertext cannot be decrypted for a restore drill. Local AES-256-GCM decrypt/restore and tamper rejection are tested independently. Next end-to-end drill must retain the key in process while performing independent cloud readback; real backups require user-managed recovery keys and documented custody.
75
+- Full backend test suite 106 tests PASS (exit 0); existing StarletteDeprecationWarning only. Still Gate 3 NO-GO: no independently verified cloud-to-decrypt-to-restore drill, owner credential provisioning, independent review or immutable receipt storage.
76
+## Synthetic encrypted recovery evidence (2026-11-02; uncommitted)
77
+- Added `backend/tools/gate3_synthetic_cloud_restore.py` using vetted cryptography AES-256-GCM with a process-ephemeral key, unique nonce and fixed AAD. It uses only synthetic mapping data; plaintext and key are not written to Google Drive.
78
+- Windows script completed PASS: mount-file readback SHA-256, authenticated decryption, isolated SQLite restore, integrity check, audit receipt verification, mapping equality and ciphertext tamper rejection.
79
+- Google Drive file ID `1qu7IRVoQYVRqhNJCqtJI-WuUZY6AdcSi`, 28,700 bytes, independently downloaded via connected Drive; SHA-256 `c86477e6970d1fa28a3d4d4839abb9f749f5469135426796ab19cc5b3a53034d` matches Windows output.
80
+- LIMITATION: independent cloud-downloaded bytes were not fed into the decrypt/restore process while its ephemeral key was alive. Thus separate cloud download verification and local restore are proven, but a single independent cloud-to-restore transaction remains unproven.
81
+- Operational backup remains blocked pending persistent user-controlled key custody/recovery, secure production owner provisioning and authorization, immutable/off-host audit evidence, authorized reconciliation, and independent reviewer sign-off. Gate 3 NO-GO. No production data, release or merge was touched.
docs/GATE3_SINGLE_PASS_EXECUTION_20261102.md
new
+43
@@ -0,0 +1,43 @@
1
+# Gate 3 — Single-pass execution and honest acceptance decision (2026-11-02)
2
+
3
+Decision: **NO-GO / BLOCKED**. This is a completed technical triage and execution record, not a claim of Gate 3 acceptance.
4
+
5
+## Scope and evidence
6
+
7
+- Repository: davoodmehraban89/Aram; local branch feat/gate3-governed-mapping-20261101, starting commit 9d346f098a0a2159d96080715322879b08d9a1f8.
8
+- Local Windows backend suite: all tests passed (pytest exit 0) on 2026-11-02. Warning: Starlette/httpx deprecation.
9
+- Synthetic AES-256-GCM backup -> Windows Drive mount -> independent Google Drive connector download -> isolated decrypt -> restored SQLite integrity_check=ok. Object 1XdEzsFMcZ0RsoRON6ZgKrGveeIZrgWGR, ciphertext SHA256 a0e724bd2a10ed49945ef1a09d64909b420dc587d3e23904178132eb0786a3e4. No real ledger or permanent recovery secret used.
10
+- Local owner exception route is explicitly NOT independent approval. Local password/session prototype is not provisioned or wired into a production identity resolver.
11
+- No real financial files changed or uploaded. No merge, release, or production deployment authorized.
12
+
13
+## Gate matrix and non-negotiable closure evidence
14
+
15
+| Gate | Status | Evidence required to mark PASS | Responsible |
16
+| --- | --- | --- | --- |
17
+| Code test / synthetic restore | PASS (local) | Recorded test run and synthetic restore evidence | Engineering |
18
+| Reproducible remote candidate | PENDING | Clean committed branch, exact SHA, focused PR, final-head CI URL | Engineering |
19
+| Operational authentication | BLOCKED | Authorized account provisioned securely, rate limiting, login/logout, localhost binding, scoped authorization and negative tests | Owner / security |
20
+| Protected audit anchor | BLOCKED | Independent administrator or immutable off-host receipt storage, retention policy and witnessed tamper drill | Security / operations |
21
+| Production backup key custody | BLOCKED | Owner-controlled recoverable key, rotation/recovery procedure, secure permissions, no key in Drive/repo/logs | Owner / operations |
22
+| Real-ledger reconciliation | BLOCKED | Explicit source authorization and SHA, complete mapping reconciliation, exception signoff and independent finance checks | Finance owner |
23
+| Operational recovery | BLOCKED | Approved staging drill from independent cloud download, measured RPO/RTO, backup retention and restoration witness | Operations |
24
+| Independent code/finance review | BLOCKED | Independent named reviewer, exact remote SHA, changed files, CI, risks and explicit decision | Reviewer |
25
+| Final GO | NOT AUTHORIZED | All mandatory gates PASS, no unresolved critical issue, signed owner decision | Owner + reviewer |
26
+
27
+## Recommended single-pass order when prerequisites become available
28
+
29
+1. Freeze and inspect source/base and canonical financial file hashes; keep financial source files read-only.
30
+2. Provision approved production identity and independent receipt storage; secure key custody outside cloud sync.
31
+3. Run scoped end-to-end authorization tests and off-host audit tamper tests.
32
+4. Run authorized ledger reconciliation, record all unmapped/conflicting accounts, obtain finance signoff.
33
+5. Execute measured staging recovery with independent witness and record RPO/RTO.
34
+6. Commit a focused candidate, publish PR, verify final-head CI and have independent reviewer sign the exact SHA.
35
+7. Only then record GO; merge/release require their own authorization and clean-environment checks.
36
+
37
+## Integrity and rollback
38
+
39
+- Preserve the current working tree; no force-push or reset.
40
+- Do not treat a synthetic sample or self-review as production/independent evidence.
41
+- Do not substitute personal Google Drive for immutable/WORM storage without demonstrated protections.
42
+- Before any remote publication, review the complete diff, remove any temporary secrets, and compare canonical source hashes against the approved base.
43
+- If any required gate fails, retain NO-GO and report the specific blocker. Do not bypass gates.
docs/PROJECT_LOG.md
+74
-19
@@ -8,7 +8,7 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
8
9
## Historical entries imported from GitHub
10
11
-### 2026-08-18T11:08:12Z — Phase 1B-1
11
+### 2026-08-18T11:08:12Z — Phase 1B-1
12
13
- Actor: Jules / repository owner
14
- Base: `source-data-cleanup@d18287a74c9453e8071ed03db6b369805b5ccde3`
@@ -23,7 +23,7 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
23
- Remaining risk: historical test evidence not recorded here
24
- Next action: Phase 1B-2
25
26
-### 2026-08-19T16:29:06Z — Phase 1B-2 corrections
26
+### 2026-08-19T16:29:06Z — Phase 1B-2 corrections
27
28
- Actor: Jules / repository owner
29
- Base: `source-data-cleanup@cd074095c3d63a4a2da1ab8490ce772f555fc91d`
@@ -38,7 +38,7 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
38
- Remaining risk: claims must still be interpreted against the source evidence
39
- Next action: Phase 2A
40
41
-### 2026-08-20T18:53:39Z — Phase 2A backend foundation
41
+### 2026-08-20T18:53:39Z — Phase 2A backend foundation
42
43
- Actor: ChatGPT/Codex implementation; repository owner
44
- Base: `source-data-cleanup@f8084268c1080595d9da672d490834ed677ad77f`
@@ -55,7 +55,7 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
55
- Remaining risk: preserve data and fiscal-year invariants
56
- Next action: focused ingestion work
57
58
-### 2026-08-24T00:34:12Z — Model refactor
58
+### 2026-08-24T00:34:12Z — Model refactor
59
60
- Actor: Jules / repository owner
61
- Base: `source-data-cleanup@84b19ef1a6efe3e82291a565829ba3e1fc47d246`
@@ -72,7 +72,7 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
72
- Remaining risk: none newly recorded
73
- Next action: Phase 2B review
74
75
-### 2026-08-24T00:34:36Z — Parallel V1 prototype closed
75
+### 2026-08-24T00:34:36Z — Parallel V1 prototype closed
76
77
- Actor: Jules / repository owner
78
- Base: `source-data-cleanup@84b19ef1a6efe3e82291a565829ba3e1fc47d246`
@@ -88,7 +88,7 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
88
- Remaining risk: large parallel implementation; do not merge directly
89
- Next action: recover feature-by-feature through focused PRs
90
91
-### 2026-08-24T01:34:25Z — Phase 2B ingestion foundation opened
91
+### 2026-08-24T01:34:25Z — Phase 2B ingestion foundation opened
92
93
- Actor: ChatGPT/Codex implementation; repository owner
94
- Base: `source-data-cleanup@5122fd052ebe0ffe0e07dbb8153a872a4f047355`
@@ -112,7 +112,7 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
112
- Verified CI evidence: GitHub Backend CI run #16 successful on PR #12.
113
- Updated docs to ensure Phase 2B metadata-registration conflict rejection is thoroughly tested and verified.
114
115
-### 2026-08-24T08:00:00Z — PR #12 corrective evidence and documentation finalization
115
+### 2026-08-24T08:00:00Z — PR #12 corrective evidence and documentation finalization
116
117
- Actor: Jules implementation; ChatGPT/Codex independent remote verification and documentation correction
118
- Task/phase: Phase 2B ingestion foundation replacement candidate
@@ -132,7 +132,7 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
132
- Recovery: close PR #12 without merging to leave the accepted branch unchanged
133
- Next action: independently review the final remote head and record an explicit decision
134
135
-### 2026-08-24T08:35:40Z — Phase 2B accepted; superseded candidate closed
135
+### 2026-08-24T08:35:40Z — Phase 2B accepted; superseded candidate closed
136
137
- Actor: ChatGPT/Codex independent reviewer; repository owner authorization
138
- Task/phase: Phase 2B ingestion foundation acceptance and post-merge control reconciliation
@@ -156,7 +156,7 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
156
- Remaining risk: PR #13 must be independently reviewed before its documentation becomes accepted
157
- Next action: review PR #13, then select the next focused Issue #11 roadmap task
158
159
-### 2026-08-24T09:29:00Z — Gate 2A implementation candidate prepared
159
+### 2026-08-24T09:29:00Z — Gate 2A implementation candidate prepared
160
161
- Actor: ChatGPT/Codex implementation
162
- Task/phase: Issue #14, Pilot workbook contract and read-only preflight
@@ -177,7 +177,7 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
177
- Remaining risks: full Backend CI and independent diff review are required
178
- Recovery: close the Draft PR without merge; accepted branch remains unchanged
179
180
-### 2026-08-24T09:40:00Z — Gate 2A Draft PR and CI verified
180
+### 2026-08-24T09:40:00Z — Gate 2A Draft PR and CI verified
181
182
- Draft PR: [#15](https://github.com/davoodmehraban89/Aram/pull/15)
183
- Published head: `8b0431b54392e3c19ae995e2b38bdf08a56a0473`
@@ -187,7 +187,7 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
187
- PR state: Draft, open, mergeable, and unmerged
188
- Acceptance: `IN_PROGRESS`; independent diff review and explicit merge decision remain required
189
190
-### 2026-08-25T06:30:00Z — Post-Gate-2A control reconciliation and stale-work cleanup
190
+### 2026-08-25T06:30:00Z — Post-Gate-2A control reconciliation and stale-work cleanup
191
192
- Actor: Codex successor project manager / independent GitHub reviewer; cleanup authorized by repository owner
193
- Task/phase: reconcile accepted Gate 2A evidence, close its duplicate candidate, and block stale-base Gate 2B work before continuation
@@ -212,7 +212,7 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
212
- Remaining risks: branch protection is disabled; PR #17 reference work remains unaccepted; Mapping/UI/release work is incomplete
213
- Next action: independently review Draft PR #18; do not start or merge Gate 2B work before the control decision
214
215
-### 2026-08-25T06:46:16Z — PR #18 accepted; time-bound candidate record reconciled
215
+### 2026-08-25T06:46:16Z — PR #18 accepted; time-bound candidate record reconciled
216
217
- Actor: ChatGPT/Codex independent reviewer; repository owner explicit authorization
218
- Task/phase: accept the post-Gate-2A control reconciliation and correct the preceding time-bound candidate snapshot
@@ -234,7 +234,7 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
234
- Remaining risks: the accepted branch is unprotected; Mapping, note/sub-note workflow/UI, reproducible Windows packaging, and end-to-end Pilot acceptance remain incomplete
235
- Next action: fetch the live accepted head and define one new focused Gate 3 / Gate 2B Mapping task; do not revive or merge PR #17
236
237
-### 2026-08-25T07:37:08Z — Role-based operating model prepared
237
+### 2026-08-25T07:37:08Z — Role-based operating model prepared
238
239
- Actor: project manager / repository maintainer; requested by Davood
240
- Task/phase: record the complete Aram responsibility model in the permanent recovery prompt
@@ -256,7 +256,7 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
256
- Remaining risks: the accepted branch is unprotected; role assignments do not replace evidence gates; Gate 3 Mapping and all later V1 gates remain incomplete
257
- Next action: finish the five-file remote candidate, independently review PR #20, and record one acceptance decision
258
259
-### 2026-08-26T15:36:29Z — V1-01 safety-gate hardening prepared
259
+### 2026-08-26T15:36:29Z — V1-01 safety-gate hardening prepared
260
261
- Actor: Codex Work authorized maintainer / implementation agent for the critical fix
262
- Task/phase: V1-01 safety-gate hardening before Gate 3 Mapping
@@ -280,7 +280,7 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
280
- Next action: publish the focused PR and obtain independent remote review after CI
281
282
283
-## 2026-11-01 — Gate 3 PR #82 Package 3
283
+## 2026-11-01 — Gate 3 PR #82 Package 3
284
- Branch: feat/gate3-governed-mapping-20261101; base: source-data-cleanup@7dc864fd032f0c4ae4d650d89304a01286a6d914.
285
- Initial reviewed head: ff6843cd0a1544a3a5355a8d555d4d692b8716fc.
286
- Scope: MappingWorkflow maker/approver separation; MappingStore audit-chain/state integrity; regression tests; Gate 3 review evidence and project status.
@@ -288,14 +288,14 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
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
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.
297
298
-## 2026-11-01 — Gate 3 Package 5
298
+## 2026-11-01 — Gate 3 Package 5
299
- Isolated branch, approved base and PR #82 checked before modifications; no unrelated local edits at start.
300
- New mapping API routes protected by injected identity resolver and fail-closed default; added HTTP role/scope regression tests.
301
- SHA-256 event audit chain and external terminal receipt verification added with integrity/restore tests. Historical-event backfill deliberately not automated.
@@ -304,7 +304,7 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
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
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.
@@ -312,10 +312,65 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
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.
314
315
-## 2026-11-01 — Gate 3 Package 7 final closure attempt
315
+## 2026-11-01 — Gate 3 Package 7 final closure attempt
316
- Revalidated accepted base SHA, isolated feature branch, clean working tree, Draft PR #82 and zero independent reviews.
317
- Inspected changed-file list: no canonical financial source XLSX/PDF or data paths changed. Existing repository ledger files were NOT treated as authorized real-ledger reconciliation evidence.
318
- Re-ran complete backend pytest (98 tests, exit 0), lint/compile and diff checks. Revisited finance, security and adversarial tests; these are self-review perspectives, not independent approvals.
319
- Prepared docs/GATE3_PACKAGE7_CLOSURE_DOSSIER.md with reviewer signature template, evidence matrix, owner-specific action list and Gate 4 handoff.
320
- NO-GO until external identity, independent audit anchor, finance owner signoff, staging DR drill and independent review are evidenced.
321
- No Merge, Release, production data mutation or Gate 4 implementation; no further repetitive development packages without new evidence.
322
+
323
+## 2026-11-02 - Gate 3 personal Windows dependency repair (local, uncommitted)
324
+- Baseline: feat/gate3-governed-mapping-20261101 at 9d346f098a0a2159d96080715322879b08d9a1f8; no canonical financial files modified.
325
+- Created isolated backend/.venv on Windows with Python 3.12.10.
326
+- Reproduced failure of pip install -e '.[test]' caused by unavailable optional uvicorn[standard] packages (including websockets) in the accessible package index.
327
+- Changed backend/pyproject.toml to depend on plain uvicorn and moved standard extras to optional server-standard group. Added Windows localhost setup instructions in backend/README.md.
328
+- Retested exact pip install -e '.[test]' successfully; backend pytest suite passed on Windows, pip check reported no broken requirements.
329
+- Remaining: production identity, independent receipt anchor, financial reconciliation, operational recovery, independent reviewer. Gate 3 NO-GO; no Merge or Release.
330
+## 2026-11-02 - Gate 3 owner API and remote destination preparation
331
+- Implemented owner-role-gated `owner-accept` API with reason validation and preserved Approved-only segregation; verified negative HTTP authorization tests.
332
+- Windows backend full pytest run passed 104 tests (exit 0). `httpx`/Starlette deprecation warning remains.
333
+- Created remote Drive folder under existing Aram folder for future encrypted backup/receipts. No data uploaded. Immutable retention, upload transport, readback and restore remain unverified.
334
+- NO-GO; no Merge, Release, source-ledger edits or production credential provisioning.
335
+## 2026-11-02 - Windows synthetic DR validation
336
+- Confirmed GoogleDriveFS running and E: My Drive mounted, but connector-created Aram folder not visible on local mount. No cloud file copied.
337
+- Added isolated synthetic SQLite snapshot/restore/receipt tamper test; full backend suite 105 passed. Remote recovery and independent retention remain unverified; Gate 3 NO-GO.
338
+## 2026-11-02 - Cloud sync probe
339
+- Verified 66-byte non-sensitive Windows E: sync probe and synthetic folder appear via connected Google Drive. Remote connector folder still not listed on Windows mount.
340
+- Encryption dependency installation failed due to network read timeout; no unencrypted DB uploaded. Gate 3 NO-GO.
341
+## 2026-11-02 - Encrypted cloud integrity milestone
342
+- Installed cryptography; AES-256-GCM synthetic backup and tamper tests passed. Windows-to-Drive uploaded 28,700-byte synthetic ciphertext; independently fetched from Drive, SHA-256 matched source exactly.
343
+- Full backend 106 tests passed. One-off ephemeral cloud key not retained, so this is not a full cloud recovery drill. No real ledger uploaded; Gate 3 NO-GO.
344
+## 2026-11-02 - Gate 3 independent synthetic cloud restore
345
+- Generated synthetic SQLite encrypted with AES-256-GCM on Windows; uploaded through mounted Google Drive.
346
+- Independently downloaded cloud object 1XdEzsFMcZ0RsoRON6ZgKrGveeIZrgWGR (28700 bytes) via Google Drive connector into separate container.
347
+- SHA-256 matched source: a0e724bd2a10ed49945ef1a09d64909b420dc587d3e23904178132eb0786a3e4.
348
+- Decrypted independent downloaded bytes and restored 28672-byte SQLite DB; PRAGMA integrity_check = ok; mapping_state, mapping_audit, mapping_audit_hash each contain one row.
349
+- Only synthetic data. Temporary one-off diagnostic script with exposed synthetic test key removed. Production key custody, access controls, audit immutability, reconciliation, independent reviewer remain unverified; Gate 3 NO-GO.
350
+
351
+
352
+## 2026-11-03 — Windows reconnection, Gate 3 worktree audit, and test dependency repair
353
+- Reconnected to Windows device Aram and inspected local branch `feat/gate3-governed-mapping-20261101`, HEAD `9d346f098a0a2159d96080715322879b08d9a1f8`. This matches PR #82 head; no commit was created during this session.
354
+- Found existing uncommitted local work: backend API/access/store/workflow changes, local_auth prototype, four test modules, two synthetic backup tools, and two Gate 3 documents. Preserved all existing changes; no reset, checkout, clean, merge, push, or release performed.
355
+- Full local Backend pytest suite passed (exit 0); compileall passed; pip check passed; TOML parsed; git diff --check passed (only Git LF/CRLF advisory warnings).
356
+- Found CI reproducibility defect: `test_gate3_encrypted_backup.py` imports `cryptography`, but the test extra did not declare it. Added `cryptography>=44,<47` to `[project.optional-dependencies].test`, matching CI workflow install command `pip install -e '.[test]'`. Re-ran full pytest successfully after repair.
357
+- Ruff is not installed in this Windows venv; Ruff verification NOT RUN. No network installation attempted. Starlette/httpx TestClient deprecation warning remains.
358
+- Security review: `local_auth.py` is explicitly a local prototype, single configured credential, in-memory volatile sessions, no rate limiting or production IdP/JWKS integration; it is not wired to the public API and is NOT operational authentication. Owner-accept is an exception status and must not be treated as independent review/approval.
359
+- Synthetic cloud backup scripts use ephemeral in-process keys and synthetic SQLite only; they do not constitute key custody, WORM retention, or operational recovery evidence.
360
+- GitHub PR #82 remains Draft/NO-GO, exact head unchanged; final-head Backend CI run #41339488244 is SUCCESS; zero independent reviews. Issues #83–#87 remain the documented external evidence blockers.
361
+- Decision: Phase 3 Step 1 baseline/worktree inspection and one CI reproducibility repair completed locally; production identity integration remains BLOCKED pending trusted IdP contract and secure provisioning. Changes remain uncommitted and unpushed pending full review because the worktree contains pre-existing mixed changes.
362
+
363
+
364
+## 2026-11-03 — Package 8 execution on Windows (local worktree only)
365
+- Device Aram reconnected; repository inspected at branch `feat/gate3-governed-mapping-20261101`, HEAD unchanged at `9d346f098a0a2159d96080715322879b08d9a1f8`, matching Draft PR #82 head. Existing uncommitted work was preserved; no reset, clean, commit, push, merge, release, or financial-data mutation.
366
+- Local authentication prototype hardened: PBKDF2-HMAC-SHA256 remains at 600,000 iterations; added input bounds, role allow-list, bounded lockout, session cap, expiry pruning, thread synchronization and revoke-all. Added lockout/session-limit/role-boundary regression tests. This is still volatile, single-credential local prototype; not wired to API, no persistent account provisioning, DPAPI key protection or cross-process throttling. It is NOT operational authentication.
367
+- Added Ruff to backend test extra and a Ruff CI step. Ran Ruff against src/tests/tools/migrations; final result PASS. Ruff initially exposed 30 findings across imports, unused f-prefixes, a late-bound row accessor, broad exception assertion and unused assignments; fixed them without unsafe automatic fixes. The row accessor now binds the current row explicitly; AES-GCM tamper test asserts InvalidTag.
368
+- Full backend pytest after repairs: 110/110 PASS (pytest --collect-only confirms 110 collected tests). compileall PASS; pip check PASS; git diff --check PASS.
369
+- Alembic SQLite migration round-trip in a newly-created temporary database: upgrade head PASS; downgrade base PASS; temporary database and WAL/SHM files removed.
370
+- Existing Starlette/httpx TestClient deprecation warning remains; no test failures.
371
+- GitHub PR #82 still Draft, unmerged, head SHA unchanged; exact-head CI run 41339488244 success; zero submitted independent reviews. Current local changes are not published, so the new Ruff CI step and local fixes have not yet run on GitHub.
372
+- Security/operational gates remain blocked: trusted IdP integration; independently administered immutable audit receipt anchor; DPAPI-backed recoverable production key custody and scheduled retention; authorized finance reconciliation; measured staging RPO/RTO drill with witness; named independent reviewer. No GO decision.
373
+- Stage 1 is only partially completed: local prototype hardening and regression tests pass, but operational identity is not complete. Stages 2–4 remain partial or blocked; no stage may be declared complete based solely on local tests.
374
+
375
+
376
+- Detailed seven-stage matrix and three sequential (non-independent) review findings recorded in `docs/GATE3_PACKAGE8_EXECUTION_REPORT_20261103.md`; 110/110 collected tests confirmed.