@davoodmehraban89 / Aram / commits / 00ca58e
Fork 0

feat(db): locked-year immutability triggers + hash-chained audit + reopen (D-07)

- DB triggers (SQLite + PostgreSQL) block INSERT/UPDATE/DELETE on year-owned tables when the year is LOCKED, enforced even via raw SQL (P-08, D3) - Lifecycle trigger: Draft->Approved->Locked; Locked->Approved only with an approved ReopenRequest; protected years cannot be deleted - AuditEntry append-only (trigger) + hash chain (verify_chain detects tampering independently of the trigger); ReopenRequest model + ORM guard exemption - ADR-016 reopen/immutability model; migration 20261203_04 installs tables+triggers - ensure_triggers() helper; conftest installs triggers for all tests Tests: raw-SQL insert/update/delete blocked on locked year, draft writes allowed, reopen with/without approved request (ORM + raw SQL), audit chain build/verify/ tamper-detection/append-only. 195 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>

davoodmehraban89 committed Dec 3, 2026 at 09:25 UTC 00ca58e41c280f56238a7d4f802cbf40720c5395
8 files changed +698 -2
backend/migrations/versions/20261203_04_immutability_audit.py new
+54
@@ -0,0 +1,54 @@
1 +"""Locked-year immutability triggers + hash-chained audit + reopen (D-07).
2 +
3 +Revision ID: 20261203_04
4 +Revises: 20261203_03
5 +"""
6 +
7 +import sqlalchemy as sa
8 +from alembic import op
9 +
10 +from aram_backend.db_triggers import install_triggers
11 +from aram_backend.models import AuditEntry, ReopenRequest
12 +
13 +revision = "20261203_04"
14 +down_revision = "20261203_03"
15 +branch_labels = None
16 +depends_on = None
17 +
18 +
19 +def upgrade() -> None:
20 + bind = op.get_bind()
21 + inspector = sa.inspect(bind)
22 + tables = inspector.get_table_names()
23 + if "reopen_requests" not in tables:
24 + ReopenRequest.__table__.create(bind=bind)
25 + if "audit_entries" not in tables:
26 + AuditEntry.__table__.create(bind=bind)
27 + install_triggers(bind)
28 +
29 +
30 +def downgrade() -> None:
31 + bind = op.get_bind()
32 + dialect = bind.dialect.name
33 + from aram_backend.db_triggers import _YEAR_TABLES
34 +
35 + names = [
36 + f"aram_lock_{t}_{op}"
37 + for t in _YEAR_TABLES
38 + for op in ("insert", "update", "delete")
39 + ]
40 + names += ["aram_audit_update", "aram_audit_delete",
41 + "aram_fiscal_year_transition", "aram_fiscal_year_no_delete"]
42 + for name in names:
43 + if dialect == "sqlite":
44 + bind.execute(sa.text(f"DROP TRIGGER IF EXISTS {name}"))
45 + else:
46 + # Postgres triggers are table-scoped; drop via IF EXISTS on each table.
47 + for t in list(_YEAR_TABLES) + ["audit_entries", "fiscal_years"]:
48 + bind.execute(sa.text(f"DROP TRIGGER IF EXISTS {name} ON {t}"))
49 + inspector = sa.inspect(bind)
50 + tables = inspector.get_table_names()
51 + if "audit_entries" in tables:
52 + op.drop_table("audit_entries")
53 + if "reopen_requests" in tables:
54 + op.drop_table("reopen_requests")
backend/src/aram_backend/database.py
+11
@@ -28,6 +28,17 @@ def build_engine(database_url: str | None = None) -> Engine:
28 return engine
29
30
31 +def ensure_triggers(engine: Engine) -> None:
32 + """Install DB-level immutability/audit triggers (D-07), idempotent.
33 +
34 + Call after the schema exists (post create_all / alembic upgrade). Safe to
35 + call repeatedly; triggers are dropped and recreated.
36 + """
37 + from aram_backend.db_triggers import install_on_engine
38 +
39 + install_on_engine(engine)
40 +
41 +
42 def _enable_sqlite_foreign_keys(dbapi_connection, _connection_record) -> None:
43 cursor = dbapi_connection.cursor()
44 cursor.execute("PRAGMA foreign_keys=ON")
backend/src/aram_backend/db_triggers.py new
+256
@@ -0,0 +1,256 @@
1 +"""Dialect-specific DB triggers for locked-year immutability and audit (D-07).
2 +
3 +These run inside the database so raw SQL cannot bypass them (P-08). They are
4 +installed idempotently (DROP IF EXISTS + CREATE) and work on SQLite and
5 +PostgreSQL. The application-level guards in ``database.py`` remain as a first
6 +line; these are the database-level guarantee.
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +from sqlalchemy import text
12 +from sqlalchemy.engine import Connection, Engine
13 +
14 +# Year-owned tables and how to resolve their owning fiscal-year id from a row.
15 +# ``alias`` is the row reference in the trigger body.
16 +_YEAR_TABLES: dict[str, str] = {
17 + "ledger_balances": "{alias}.year_id",
18 + "account_versions": "{alias}.year_id",
19 + "note_definitions": "{alias}.year_id",
20 + "mapping_rules": "{alias}.year_id",
21 + "financial_statements": "{alias}.year_id",
22 + "source_documents": "{alias}.year_id",
23 + "note_rows": (
24 + "(SELECT nd.year_id FROM note_definitions nd WHERE nd.id = {alias}.note_id)"
25 + ),
26 + "statement_lines": (
27 + "(SELECT fs.year_id FROM financial_statements fs "
28 + "WHERE fs.id = {alias}.statement_id)"
29 + ),
30 +}
31 +
32 +
33 +def _locked_check_sqlite(table: str, alias: str) -> str:
34 + year_expr = _YEAR_TABLES[table].format(alias=alias)
35 + return (
36 + f"SELECT RAISE(ABORT, 'fiscal year is locked; row is immutable') "
37 + f"WHERE (SELECT status FROM fiscal_years WHERE id = {year_expr}) = 'LOCKED'"
38 + )
39 +
40 +
41 +def install_triggers(conn: Connection) -> None:
42 + """Install immutability + audit triggers (idempotent)."""
43 + dialect = conn.dialect.name
44 + if dialect == "sqlite":
45 + _install_sqlite(conn)
46 + elif dialect == "postgresql":
47 + _install_postgresql(conn)
48 +
49 +
50 +def _install_sqlite(conn: Connection) -> None:
51 + for table in _YEAR_TABLES:
52 + for op, alias in (("INSERT", "NEW"), ("UPDATE", "NEW"), ("DELETE", "OLD")):
53 + name = f"aram_lock_{table}_{op.lower()}"
54 + conn.execute(text(f"DROP TRIGGER IF EXISTS {name}"))
55 + check = _locked_check_sqlite(table, alias)
56 + conn.execute(
57 + text(
58 + f"CREATE TRIGGER {name} BEFORE {op} ON {table} "
59 + f"BEGIN {check}; END"
60 + )
61 + )
62 + # Audit log is append-only.
63 + for op in ("UPDATE", "DELETE"):
64 + name = f"aram_audit_{op.lower()}"
65 + conn.execute(text(f"DROP TRIGGER IF EXISTS {name}"))
66 + conn.execute(
67 + text(
68 + f"CREATE TRIGGER {name} BEFORE {op} ON audit_entries "
69 + f"BEGIN SELECT RAISE(ABORT, 'audit log is append-only'); END"
70 + )
71 + )
72 + _install_lifecycle_sqlite(conn)
73 +
74 +
75 +def _install_lifecycle_sqlite(conn: Connection) -> None:
76 + conn.execute(text("DROP TRIGGER IF EXISTS aram_fiscal_year_transition"))
77 + conn.execute(
78 + text(
79 + """
80 + CREATE TRIGGER aram_fiscal_year_transition
81 + BEFORE UPDATE OF status ON fiscal_years
82 + BEGIN
83 + SELECT RAISE(ABORT, 'invalid fiscal-year transition')
84 + WHERE NOT (
85 + (OLD.status = 'DRAFT' AND NEW.status = 'APPROVED')
86 + OR (OLD.status = 'APPROVED' AND NEW.status = 'LOCKED')
87 + OR (OLD.status = 'LOCKED' AND NEW.status = 'APPROVED'
88 + AND EXISTS (SELECT 1 FROM reopen_requests
89 + WHERE year_id = OLD.id AND status = 'approved'))
90 + );
91 + END
92 + """
93 + )
94 + )
95 + conn.execute(text("DROP TRIGGER IF EXISTS aram_fiscal_year_no_delete"))
96 + conn.execute(
97 + text(
98 + """
99 + CREATE TRIGGER aram_fiscal_year_no_delete
100 + BEFORE DELETE ON fiscal_years
101 + BEGIN
102 + SELECT RAISE(ABORT, 'approved or locked fiscal year cannot be deleted')
103 + WHERE OLD.status IN ('APPROVED', 'LOCKED');
104 + END
105 + """
106 + )
107 + )
108 +
109 +
110 +def _install_postgresql(conn: Connection) -> None:
111 + conn.execute(
112 + text(
113 + """
114 + CREATE OR REPLACE FUNCTION aram_guard_locked() RETURNS trigger AS $$
115 + DECLARE yid integer; ystatus varchar;
116 + BEGIN
117 + IF TG_TABLE_NAME = 'note_rows' THEN
118 + SELECT year_id INTO yid FROM note_definitions WHERE id = NEW.note_id;
119 + ELSIF TG_TABLE_NAME = 'statement_lines' THEN
120 + SELECT year_id INTO yid FROM financial_statements WHERE id = NEW.statement_id;
121 + ELSE
122 + yid := NEW.year_id;
123 + END IF;
124 + SELECT status INTO ystatus FROM fiscal_years WHERE id = yid;
125 + IF ystatus = 'LOCKED' THEN
126 + RAISE EXCEPTION 'fiscal year is locked; row is immutable';
127 + END IF;
128 + RETURN NEW;
129 + END;
130 + $$ LANGUAGE plpgsql
131 + """
132 + )
133 + )
134 + for table in _YEAR_TABLES:
135 + # DELETE uses OLD; route via a separate function for OLD reference.
136 + for op in ("INSERT", "UPDATE"):
137 + name = f"aram_lock_{table}_{op.lower()}"
138 + conn.execute(text(f"DROP TRIGGER IF EXISTS {name} ON {table}"))
139 + conn.execute(
140 + text(
141 + f"CREATE TRIGGER {name} BEFORE {op} ON {table} "
142 + f"FOR EACH ROW EXECUTE FUNCTION aram_guard_locked()"
143 + )
144 + )
145 + conn.execute(
146 + text(
147 + """
148 + CREATE OR REPLACE FUNCTION aram_guard_locked_delete() RETURNS trigger AS $$
149 + DECLARE yid integer; ystatus varchar;
150 + BEGIN
151 + IF TG_TABLE_NAME = 'note_rows' THEN
152 + SELECT year_id INTO yid FROM note_definitions WHERE id = OLD.note_id;
153 + ELSIF TG_TABLE_NAME = 'statement_lines' THEN
154 + SELECT year_id INTO yid FROM financial_statements WHERE id = OLD.statement_id;
155 + ELSE
156 + yid := OLD.year_id;
157 + END IF;
158 + SELECT status INTO ystatus FROM fiscal_years WHERE id = yid;
159 + IF ystatus = 'LOCKED' THEN
160 + RAISE EXCEPTION 'fiscal year is locked; row is immutable';
161 + END IF;
162 + RETURN OLD;
163 + END;
164 + $$ LANGUAGE plpgsql
165 + """
166 + )
167 + )
168 + for table in _YEAR_TABLES:
169 + name = f"aram_lock_{table}_delete"
170 + conn.execute(text(f"DROP TRIGGER IF EXISTS {name} ON {table}"))
171 + conn.execute(
172 + text(
173 + f"CREATE TRIGGER {name} BEFORE DELETE ON {table} "
174 + f"FOR EACH ROW EXECUTE FUNCTION aram_guard_locked_delete()"
175 + )
176 + )
177 + conn.execute(
178 + text(
179 + """
180 + CREATE OR REPLACE FUNCTION aram_audit_append_only() RETURNS trigger AS $$
181 + BEGIN
182 + RAISE EXCEPTION 'audit log is append-only';
183 + END;
184 + $$ LANGUAGE plpgsql
185 + """
186 + )
187 + )
188 + for op in ("UPDATE", "DELETE"):
189 + name = f"aram_audit_{op.lower()}"
190 + conn.execute(text(f"DROP TRIGGER IF EXISTS {name} ON audit_entries"))
191 + conn.execute(
192 + text(
193 + f"CREATE TRIGGER {name} BEFORE {op} ON audit_entries "
194 + f"FOR EACH ROW EXECUTE FUNCTION aram_audit_append_only()"
195 + )
196 + )
197 + _install_lifecycle_postgresql(conn)
198 +
199 +
200 +def _install_lifecycle_postgresql(conn: Connection) -> None:
201 + conn.execute(
202 + text(
203 + """
204 + CREATE OR REPLACE FUNCTION aram_fiscal_year_transition() RETURNS trigger AS $$
205 + BEGIN
206 + IF NOT (
207 + (OLD.status = 'DRAFT' AND NEW.status = 'APPROVED')
208 + OR (OLD.status = 'APPROVED' AND NEW.status = 'LOCKED')
209 + OR (OLD.status = 'LOCKED' AND NEW.status = 'APPROVED'
210 + AND EXISTS (SELECT 1 FROM reopen_requests
211 + WHERE year_id = OLD.id AND status = 'approved'))
212 + ) THEN
213 + RAISE EXCEPTION 'invalid fiscal-year transition';
214 + END IF;
215 + RETURN NEW;
216 + END;
217 + $$ LANGUAGE plpgsql
218 + """
219 + )
220 + )
221 + conn.execute(text("DROP TRIGGER IF EXISTS aram_fiscal_year_transition ON fiscal_years"))
222 + conn.execute(
223 + text(
224 + "CREATE TRIGGER aram_fiscal_year_transition BEFORE UPDATE OF status "
225 + "ON fiscal_years FOR EACH ROW EXECUTE FUNCTION aram_fiscal_year_transition()"
226 + )
227 + )
228 + conn.execute(
229 + text(
230 + """
231 + CREATE OR REPLACE FUNCTION aram_fiscal_year_no_delete() RETURNS trigger AS $$
232 + BEGIN
233 + IF OLD.status IN ('APPROVED', 'LOCKED') THEN
234 + RAISE EXCEPTION 'approved or locked fiscal year cannot be deleted';
235 + END IF;
236 + RETURN OLD;
237 + END;
238 + $$ LANGUAGE plpgsql
239 + """
240 + )
241 + )
242 + conn.execute(text("DROP TRIGGER IF EXISTS aram_fiscal_year_no_delete ON fiscal_years"))
243 + conn.execute(
244 + text(
245 + "CREATE TRIGGER aram_fiscal_year_no_delete BEFORE DELETE ON fiscal_years "
246 + "FOR EACH ROW EXECUTE FUNCTION aram_fiscal_year_no_delete()"
247 + )
248 + )
249 +
250 +
251 +def install_on_engine(engine: Engine) -> None:
252 + with engine.begin() as conn:
253 + install_triggers(conn)
254 +
255 +
256 +__all__ = ["install_triggers", "install_on_engine"]
backend/src/aram_backend/models.py
+56 -1
@@ -78,6 +78,43 @@ class YearOwnedMixin:
78 year_id: Mapped[int] = mapped_column(ForeignKey("fiscal_years.id", ondelete="RESTRICT"), index=True)
79
80
81 +class ReopenRequest(TimestampMixin, YearOwnedMixin, Base):
82 + """A controlled request to reopen a LOCKED year (D-07, booklet §7).
83 +
84 + LOCKED -> APPROVED is permitted only when an ``approved`` request exists.
85 + Reopening versions the output; it never edits locked rows in place.
86 + """
87 +
88 + __tablename__ = "reopen_requests"
89 + id: Mapped[int] = mapped_column(primary_key=True)
90 + reason: Mapped[str] = mapped_column(Text)
91 + requested_by: Mapped[str] = mapped_column(String(128), default="")
92 + approved_by: Mapped[str | None] = mapped_column(String(128), nullable=True)
93 + status: Mapped[str] = mapped_column(String(16), default="pending")
94 +
95 +
96 +class AuditEntry(Base):
97 + """Append-only, hash-chained audit log (D-07, booklet §12).
98 +
99 + chain_hash = SHA256(previous_hash || payload_hash). UPDATE/DELETE are blocked
100 + by triggers; verify_chain detects any tampering with past entries.
101 + """
102 +
103 + __tablename__ = "audit_entries"
104 + id: Mapped[int] = mapped_column(primary_key=True)
105 + year_id: Mapped[int | None] = mapped_column(
106 + ForeignKey("fiscal_years.id", ondelete="RESTRICT"), nullable=True, index=True
107 + )
108 + actor: Mapped[str] = mapped_column(String(128), default="")
109 + action: Mapped[str] = mapped_column(String(64))
110 + payload_hash: Mapped[str] = mapped_column(String(64))
111 + previous_hash: Mapped[str] = mapped_column(String(64))
112 + chain_hash: Mapped[str] = mapped_column(String(64))
113 + created_at: Mapped[datetime] = mapped_column(
114 + DateTime(timezone=True), default=utc_now
115 + )
116 +
117 +
118 class SourceFile(TimestampMixin, Base):
119 """Content-addressed source bytes stored on disk (D-06, booklet §5).
120
@@ -303,12 +340,26 @@ def enforce_audit_invariants(session: Session, _flush_context, _instances) -> No
340 allowed = {
341 FiscalYearStatus.DRAFT: {FiscalYearStatus.APPROVED},
342 FiscalYearStatus.APPROVED: {FiscalYearStatus.LOCKED},
306 - FiscalYearStatus.LOCKED: set(),
343 + FiscalYearStatus.LOCKED: {FiscalYearStatus.APPROVED},
344 }
345 if obj.status not in allowed[old_status]:
346 raise ValueError(
347 f"Invalid fiscal-year transition: {old_status.value} -> {obj.status.value}"
348 )
349 + if (
350 + old_status == FiscalYearStatus.LOCKED
351 + and obj.status == FiscalYearStatus.APPROVED
352 + ):
353 + approved_reopen = session.scalar(
354 + select(ReopenRequest.id).where(
355 + ReopenRequest.year_id == obj.id,
356 + ReopenRequest.status == "approved",
357 + ).limit(1)
358 + )
359 + if approved_reopen is None:
360 + raise ValueError(
361 + f"Fiscal year {obj.id} is locked; reopening requires an approved ReopenRequest"
362 + )
363
364 protected_metadata_changed = state.attrs.company.history.has_changes() or any(
365 state.attrs[field].history.has_changes() for field in ("company_id", "year")
@@ -332,6 +383,10 @@ def enforce_audit_invariants(session: Session, _flush_context, _instances) -> No
383 for obj in protected:
384 if isinstance(obj, FiscalYear):
385 continue
386 + # A ReopenRequest is the authorized mechanism to act on a locked year
387 + # (ADR-016); creating/approving it must not be blocked by the year guard.
388 + if isinstance(obj, ReopenRequest):
389 + continue
390 year_id = _year_id_for(obj, session)
391 if year_id is None:
392 continue
backend/src/aram_backend/services/audit.py new
+75
@@ -0,0 +1,75 @@
1 +"""Hash-chained audit log (D-07, booklet §12).
2 +
3 +Each entry's chain_hash = SHA256(previous_hash || payload_hash). The first entry
4 +chains from a fixed genesis hash. ``verify_chain`` recomputes the whole chain and
5 +detects any tampering with past entries (which the append-only triggers also
6 +block at the database level).
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +import hashlib
12 +import json
13 +
14 +from sqlalchemy import select
15 +from sqlalchemy.orm import Session
16 +
17 +from aram_backend.models import AuditEntry
18 +
19 +GENESIS_HASH = "0" * 64
20 +
21 +
22 +def _payload_hash(action: str, actor: str, year_id: int | None, payload: dict) -> str:
23 + canonical = json.dumps(
24 + {"action": action, "actor": actor, "year_id": year_id, "payload": payload},
25 + sort_keys=True,
26 + ensure_ascii=False,
27 + separators=(",", ":"),
28 + )
29 + return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
30 +
31 +
32 +def _chain_hash(previous_hash: str, payload_hash: str) -> str:
33 + return hashlib.sha256(f"{previous_hash}{payload_hash}".encode("ascii")).hexdigest()
34 +
35 +
36 +def append_entry(
37 + session: Session,
38 + *,
39 + action: str,
40 + actor: str = "",
41 + year_id: int | None = None,
42 + payload: dict | None = None,
43 +) -> AuditEntry:
44 + """Append a new audit entry, chaining from the current head."""
45 + payload = payload or {}
46 + head = session.scalar(select(AuditEntry).order_by(AuditEntry.id.desc()).limit(1))
47 + previous_hash = head.chain_hash if head is not None else GENESIS_HASH
48 + payload_hash = _payload_hash(action, actor, year_id, payload)
49 + entry = AuditEntry(
50 + year_id=year_id,
51 + actor=actor,
52 + action=action,
53 + payload_hash=payload_hash,
54 + previous_hash=previous_hash,
55 + chain_hash=_chain_hash(previous_hash, payload_hash),
56 + )
57 + session.add(entry)
58 + session.flush()
59 + return entry
60 +
61 +
62 +def verify_chain(session: Session) -> bool:
63 + """Return True iff the entire audit chain is intact."""
64 + previous_hash = GENESIS_HASH
65 + entries = session.scalars(select(AuditEntry).order_by(AuditEntry.id.asc())).all()
66 + for entry in entries:
67 + if entry.previous_hash != previous_hash:
68 + return False
69 + if entry.chain_hash != _chain_hash(previous_hash, entry.payload_hash):
70 + return False
71 + previous_hash = entry.chain_hash
72 + return True
73 +
74 +
75 +__all__ = ["append_entry", "verify_chain", "GENESIS_HASH"]
backend/tests/conftest.py
+2 -1
@@ -2,7 +2,7 @@ import pytest
2 from fastapi.testclient import TestClient
3 from sqlalchemy.orm import Session, sessionmaker
4
5 -from aram_backend.database import Base, build_engine
5 +from aram_backend.database import Base, build_engine, ensure_triggers
6 from aram_backend.main import app
7
8
@@ -10,6 +10,7 @@ from aram_backend.main import app
10 def session(tmp_path) -> Session:
11 engine = build_engine(f"sqlite:///{tmp_path / 'test.db'}")
12 Base.metadata.create_all(engine)
13 + ensure_triggers(engine)
14 factory = sessionmaker(bind=engine, expire_on_commit=False)
15 with factory() as db:
16 yield db
backend/tests/test_immutability.py new
+188
@@ -0,0 +1,188 @@
1 +"""D-07 acceptance: locked-year immutability via DB triggers, reopen, audit chain.
2 +
3 +The key guarantee (booklet D3, P-08): a LOCKED year is immutable even through raw
4 +SQL, bypassing the ORM. These tests issue raw statements to prove the database
5 +itself enforces the rule.
6 +"""
7 +
8 +from __future__ import annotations
9 +
10 +import pytest
11 +from sqlalchemy import text
12 +from sqlalchemy.exc import IntegrityError
13 +
14 +from aram_backend.models import (
15 + AuditEntry,
16 + Company,
17 + FiscalYear,
18 + FiscalYearStatus,
19 + LedgerBalance,
20 + ReopenRequest,
21 +)
22 +from aram_backend.services.audit import append_entry, verify_chain
23 +
24 +
25 +def _locked_year(session):
26 + company = Company(code="IMM", name="شرکت")
27 + session.add(company)
28 + session.flush()
29 + year = FiscalYear(company_id=company.id, year=1404)
30 + session.add(year)
31 + session.flush()
32 + year.status = FiscalYearStatus.APPROVED
33 + session.commit()
34 + year.status = FiscalYearStatus.LOCKED
35 + session.commit()
36 + return year
37 +
38 +
39 +def _draft_year(session):
40 + company = Company(code="IMM", name="شرکت")
41 + session.add(company)
42 + session.flush()
43 + year = FiscalYear(company_id=company.id, year=1404)
44 + session.add(year)
45 + session.commit()
46 + return year
47 +
48 +
49 +def _lock(session, year):
50 + year.status = FiscalYearStatus.APPROVED
51 + session.commit()
52 + year.status = FiscalYearStatus.LOCKED
53 + session.commit()
54 +
55 +
56 +def _seed_balance(session, year):
57 + session.execute(
58 + text(
59 + "INSERT INTO source_documents (year_id, filename, file_hash, document_type, uploaded_at, created_at, updated_at) "
60 + "VALUES (:y, 'l.xlsx', 'h1', 'general_ledger', '2026-01-01', '2026-01-01', '2026-01-01')"
61 + ),
62 + {"y": year.id},
63 + )
64 + sd_id = session.execute(text("SELECT id FROM source_documents WHERE year_id=:y"), {"y": year.id}).scalar()
65 + session.execute(
66 + text(
67 + "INSERT INTO ledger_balances (year_id, source_document_id, source_sheet, source_row, import_version, "
68 + "account_full_code, general_code, subsidiary_code, detail1_code, detail2_code, detail3_code, detail4_code, "
69 + "account_name, opening, debit, credit, closing, entry_type, created_at, updated_at) "
70 + "VALUES (:y, :sd, 'Source', 3, 1, '148348', '14', '8348', '', '', '', '', "
71 + "'نمونه', 0, 100, 0, 100, 'O', '2026-01-01', '2026-01-01')"
72 + ),
73 + {"y": year.id, "sd": sd_id},
74 + )
75 + session.commit()
76 +
77 +
78 +class TestRawSqlImmutability:
79 + def test_locked_year_blocks_raw_insert(self, session):
80 + year = _locked_year(session)
81 + with pytest.raises(IntegrityError, match="locked"):
82 + session.execute(
83 + text(
84 + "INSERT INTO ledger_balances (year_id, source_document_id, source_sheet, source_row, "
85 + "import_version, account_full_code, account_name, opening, debit, credit, closing, created_at, updated_at) "
86 + "VALUES (:y, 1, 'Source', 4, 1, '148349', 'x', 0, 0, 0, 0, '2026-01-01', '2026-01-01')"
87 + ),
88 + {"y": year.id},
89 + )
90 + session.rollback()
91 +
92 + def test_locked_year_blocks_raw_update(self, session):
93 + year = _draft_year(session)
94 + _seed_balance(session, year)
95 + _lock(session, year)
96 + with pytest.raises(IntegrityError, match="locked"):
97 + session.execute(
98 + text("UPDATE ledger_balances SET debit = 999 WHERE year_id = :y"),
99 + {"y": year.id},
100 + )
101 + session.rollback()
102 + # Value unchanged.
103 + assert session.execute(
104 + text("SELECT debit FROM ledger_balances WHERE year_id=:y"), {"y": year.id}
105 + ).scalar() == 100
106 +
107 + def test_locked_year_blocks_raw_delete(self, session):
108 + year = _draft_year(session)
109 + _seed_balance(session, year)
110 + _lock(session, year)
111 + with pytest.raises(IntegrityError, match="locked"):
112 + session.execute(text("DELETE FROM ledger_balances WHERE year_id = :y"), {"y": year.id})
113 + session.rollback()
114 + assert session.execute(
115 + text("SELECT COUNT(*) FROM ledger_balances WHERE year_id=:y"), {"y": year.id}
116 + ).scalar() == 1
117 +
118 + def test_draft_year_allows_writes(self, session):
119 + company = Company(code="DFT", name="x")
120 + session.add(company)
121 + session.flush()
122 + year = FiscalYear(company_id=company.id, year=1404)
123 + session.add(year)
124 + session.commit()
125 + session.execute(
126 + text(
127 + "INSERT INTO source_documents (year_id, filename, file_hash, document_type, uploaded_at, created_at, updated_at) "
128 + "VALUES (:y, 'l.xlsx', 'h2', 'general_ledger', '2026-01-01', '2026-01-01', '2026-01-01')"
129 + ),
130 + {"y": year.id},
131 + )
132 + session.commit() # must not raise
133 +
134 +
135 +class TestReopen:
136 + def test_reopen_without_request_blocked(self, session):
137 + year = _locked_year(session)
138 + year.status = FiscalYearStatus.APPROVED
139 + with pytest.raises(ValueError, match="ReopenRequest"):
140 + session.commit()
141 + session.rollback()
142 +
143 + def test_reopen_with_approved_request_allowed(self, session):
144 + year = _locked_year(session)
145 + req = ReopenRequest(year_id=year.id, reason="اصلاح", status="approved", approved_by="owner")
146 + session.add(req)
147 + session.commit()
148 + year.status = FiscalYearStatus.APPROVED
149 + session.commit()
150 + assert year.status == FiscalYearStatus.APPROVED
151 +
152 + def test_reopen_via_raw_sql_requires_request(self, session):
153 + year = _locked_year(session)
154 + with pytest.raises(IntegrityError, match="transition"):
155 + session.execute(
156 + text("UPDATE fiscal_years SET status='APPROVED' WHERE id=:y"), {"y": year.id}
157 + )
158 + session.rollback()
159 +
160 +
161 +class TestAuditChain:
162 + def test_chain_builds_and_verifies(self, session):
163 + append_entry(session, action="import", actor="u", payload={"rows": 10})
164 + append_entry(session, action="approve", actor="u", payload={})
165 + session.commit()
166 + assert verify_chain(session) is True
167 +
168 + def test_tamper_detected(self, session):
169 + append_entry(session, action="import", actor="u", payload={"rows": 10})
170 + append_entry(session, action="approve", actor="u", payload={})
171 + session.commit()
172 + # Simulate an attacker with DB access who disables the append-only trigger
173 + # and corrupts a past payload hash. verify_chain must still detect it —
174 + # an independent tamper-evidence layer beyond the trigger.
175 + session.execute(text("DROP TRIGGER aram_audit_update"))
176 + session.execute(text("UPDATE audit_entries SET payload_hash='deadbeef' WHERE id=1"))
177 + session.commit()
178 + assert verify_chain(session) is False
179 +
180 + def test_audit_append_only_via_raw_sql(self, session):
181 + append_entry(session, action="import", actor="u", payload={})
182 + session.commit()
183 + with pytest.raises(IntegrityError, match="append-only"):
184 + session.execute(text("UPDATE audit_entries SET actor='hacker' WHERE id=1"))
185 + session.rollback()
186 + with pytest.raises(IntegrityError, match="append-only"):
187 + session.execute(text("DELETE FROM audit_entries WHERE id=1"))
188 + session.rollback()
docs/adr/ADR-016-reopen-and-immutability.md new
+56
@@ -0,0 +1,56 @@
1 +# ADR-016 — Reopen model and locked-year immutability
2 +
3 +- Status: Accepted (Phase 0, D-07)
4 +- Date: 2026-12-03
5 +- Booklet: §7 (Reopen), §12 (D-07), P-07/P-08; §5
6 +
7 +## Context
8 +
9 +A LOCKED fiscal year must be immutable even against raw SQL. Reopening must be a
10 +controlled, audited act that never silently rewrites locked data. The database
11 +already enforces the DRAFT→APPROVED→LOCKED lifecycle via triggers
12 +(`protect_fiscal_year_transition`); D-07 adds the row-level guards.
13 +
14 +## Decision
15 +
16 +### Locked-year immutability (D-07)
17 +
18 +Database triggers block INSERT/UPDATE/DELETE on every year-owned financial table
19 +when the owning fiscal year is LOCKED: `ledger_balances`, `account_versions`,
20 +`note_definitions`, `note_rows`, `mapping_rules`, `financial_statements`,
21 +`statement_lines`, `source_documents`. The owning year is resolved directly
22 +(`year_id`) or through the parent (note→definition, line→statement), matching the
23 +application-level `_year_id_for` guard. Triggers run for SQLite and PostgreSQL via
24 +dialect-specific generation, so raw SQL cannot bypass them (P-08).
25 +
26 +### Reopen
27 +
28 +- LOCKED → APPROVED is allowed **only** when a `ReopenRequest` with status
29 + `approved` exists for the year. Without it, the transition trigger blocks the
30 + change. The existing transition trigger is extended to permit this path.
31 +- Reopening never edits locked rows: it produces a **new statement version**
32 + (`FinancialStatement.version + 1`) and the changes are recorded as adjustments
33 + with a reason. The original locked snapshot remains queryable.
34 +- Every reopen and every adjustment is written to the hash-chained audit log
35 + (D-07): `AuditEntry(previous_hash, payload_hash, chain_hash)` where
36 + `chain_hash = SHA256(previous_hash || payload_hash)`. Any edit to a past entry
37 + breaks the chain and is detected by `verify_chain`.
38 +
39 +### Audit log
40 +
41 +`AuditEntry` is append-only: triggers block UPDATE and DELETE. The chain is
42 +verified on demand and before final approval. Actor and timestamp are recorded.
43 +
44 +## Consequences
45 +
46 +- Raw SQL cannot mutate a locked year; the only path is an approved reopen that
47 + versions the output and leaves an audited adjustment trail.
48 +- The audit chain gives tamper evidence independent of the database's own
49 + integrity.
50 +- Phase 7 builds the full ReopenRequest workflow and adjustment layer on this
51 + foundation; Phase 0 establishes the model, triggers, and chain.
52 +
53 +## Rejected alternatives
54 +
55 +- Application-only immutability: bypassable by raw SQL (violates P-08).
56 +- Mutable audit rows with a "deleted" flag: breaks tamper evidence.