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()