1
+"""R4 (booklet 2.1): Alembic-only production schema path + backup restore flow.
2
+
3
+Proves the desktop init and the backup-restore flow go through
4
+``alembic upgrade head`` (never ``create_all`` in production), that fresh,
5
+versioned, and legacy ``create_all`` databases all converge to head with the
6
+full D-07 trigger set, and that a restored backup is migrated + trigger-checked
7
+before it is reported ready (ADR-035).
8
+"""
9
+
10
+from __future__ import annotations
11
+
12
+import sqlite3
13
+from pathlib import Path
14
+
15
+import pytest
16
+from sqlalchemy.orm import sessionmaker
17
+
18
+from aram_backend.database import Base, build_engine, ensure_triggers
19
+from aram_backend.db_triggers import expected_trigger_names, installed_trigger_names
20
+from aram_backend.desktop import initialize_database
21
+from aram_backend.services.backup import BackupError, create_backup, restore_backup
22
+from aram_backend.services.schema import (
23
+ SchemaError,
24
+ alembic_config,
25
+ current_revision,
26
+ migrations_dir,
27
+ missing_triggers,
28
+ require_triggers,
29
+ upgrade_to_head,
30
+)
31
+from conftest import make_user
32
+
33
+HEAD = "20261204_09"
34
+
35
+
36
+def _inspect(path: Path) -> dict:
37
+ conn = sqlite3.connect(str(path))
38
+ try:
39
+ try:
40
+ version = conn.execute("SELECT version_num FROM alembic_version").fetchone()[0]
41
+ except sqlite3.OperationalError:
42
+ version = None
43
+ tables = {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}
44
+ lb_cols = {r[1] for r in conn.execute("PRAGMA table_info(ledger_balances)")}
45
+ user_cols = {r[1] for r in conn.execute("PRAGMA table_info(users)")}
46
+ triggers = {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='trigger'")}
47
+ rows = conn.execute("SELECT COUNT(*) FROM ledger_balances").fetchone()[0]
48
+ finally:
49
+ conn.close()
50
+ return {
51
+ "version": version,
52
+ "tables": tables,
53
+ "lb_cols": lb_cols,
54
+ "user_cols": user_cols,
55
+ "triggers": triggers,
56
+ "rows": rows,
57
+ }
58
+
59
+
60
+def _legacy_create_all(path: Path) -> None:
61
+ """Simulate a pre-Alembic desktop install: create_all, no alembic_version."""
62
+ engine = build_engine(f"sqlite:///{path}")
63
+ Base.metadata.create_all(engine)
64
+ ensure_triggers(engine)
65
+ engine.dispose()
66
+
67
+
68
+# ----------------------------------------------------------- schema service
69
+
70
+
71
+def test_migrations_dir_exists_and_has_versions():
72
+ d = migrations_dir()
73
+ assert d.is_dir()
74
+ assert (d / "versions").is_dir()
75
+ assert (d / "env.py").exists()
76
+
77
+
78
+def test_alembic_config_targets_the_named_url(tmp_path):
79
+ url = f"sqlite:///{tmp_path / 'x.db'}"
80
+ cfg = alembic_config(url)
81
+ assert cfg.attributes["database_url"] == url
82
+ assert cfg.get_main_option("script_location") == str(migrations_dir())
83
+
84
+
85
+def test_current_revision_none_on_unversioned(tmp_path):
86
+ path = tmp_path / "legacy.db"
87
+ _legacy_create_all(path)
88
+ assert current_revision(f"sqlite:///{path}") is None
89
+
90
+
91
+def test_upgrade_to_head_on_fresh_db(tmp_path):
92
+ url = f"sqlite:///{tmp_path / 'fresh.db'}"
93
+ assert upgrade_to_head(url) == HEAD
94
+ info = _inspect(tmp_path / "fresh.db")
95
+ assert info["version"] == HEAD
96
+ assert "auth_sessions" in info["tables"]
97
+ assert "source_note" in info["lb_cols"]
98
+
99
+
100
+# ----------------------------------------------------------- desktop init (R4)
101
+
102
+
103
+def test_initialize_database_uses_alembic_not_create_all(tmp_path):
104
+ data_dir = tmp_path / "aram-data"
105
+ initialize_database(data_dir)
106
+ info = _inspect(data_dir / "aram.db")
107
+ # The production path now stamps an Alembic version (create_all never did).
108
+ assert info["version"] == HEAD
109
+ assert (data_dir / "source_store").is_dir()
110
+ assert expected_trigger_names() <= info["triggers"]
111
+
112
+
113
+def test_initialize_database_is_idempotent(tmp_path):
114
+ data_dir = tmp_path / "aram-data"
115
+ initialize_database(data_dir)
116
+ initialize_database(data_dir)
117
+ assert _inspect(data_dir / "aram.db")["version"] == HEAD
118
+
119
+
120
+def test_initialize_database_migrates_legacy_full_schema(tmp_path):
121
+ """A legacy create_all install (current schema, no version) converges to head."""
122
+ data_dir = tmp_path / "aram-data"
123
+ data_dir.mkdir()
124
+ _legacy_create_all(data_dir / "aram.db")
125
+ assert _inspect(data_dir / "aram.db")["version"] is None
126
+ initialize_database(data_dir)
127
+ info = _inspect(data_dir / "aram.db")
128
+ assert info["version"] == HEAD
129
+ assert expected_trigger_names() <= info["triggers"]
130
+
131
+
132
+def test_initialize_database_migrates_legacy_v100_era(tmp_path):
133
+ """A v1.0.0-era install (no auth_sessions/source_note/password_rounds) is upgraded."""
134
+ data_dir = tmp_path / "aram-data"
135
+ data_dir.mkdir()
136
+ db = data_dir / "aram.db"
137
+ _legacy_create_all(db)
138
+ conn = sqlite3.connect(str(db))
139
+ conn.execute("DROP TABLE auth_sessions")
140
+ conn.execute("ALTER TABLE ledger_balances RENAME TO lb_old")
141
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(lb_old)") if r[1] != "source_note"]
142
+ conn.execute(f"CREATE TABLE ledger_balances AS SELECT {','.join(cols)} FROM lb_old")
143
+ conn.execute("DROP TABLE lb_old")
144
+ for col in ("password_rounds", "failed_login_count", "locked_until"):
145
+ conn.execute(f"ALTER TABLE users DROP COLUMN {col}")
146
+ conn.commit()
147
+ conn.close()
148
+ before = _inspect(db)
149
+ assert "auth_sessions" not in before["tables"]
150
+ assert "source_note" not in before["lb_cols"]
151
+
152
+ initialize_database(data_dir)
153
+ after = _inspect(db)
154
+ assert after["version"] == HEAD
155
+ assert "auth_sessions" in after["tables"]
156
+ assert "source_note" in after["lb_cols"]
157
+ assert "password_rounds" in after["user_cols"]
158
+ assert expected_trigger_names() <= after["triggers"]
159
+
160
+
161
+def test_initialize_database_upgrades_stamp_08_to_09(tmp_path):
162
+ """A DB stamped at 08 (source_note absent) is upgraded to 09 by init."""
163
+ data_dir = tmp_path / "aram-data"
164
+ data_dir.mkdir()
165
+ db = data_dir / "aram.db"
166
+ url = f"sqlite:///{db}"
167
+ # Build at head, then rewind the stamp to 08 and drop source_note to mimic 08.
168
+ upgrade_to_head(url)
169
+ engine = build_engine(url)
170
+ Base.metadata.create_all(engine) # ensure all tables (no-op at head)
171
+ ensure_triggers(engine)
172
+ engine.dispose()
173
+ conn = sqlite3.connect(str(db))
174
+ conn.execute("UPDATE alembic_version SET version_num='20261204_08'")
175
+ conn.execute("ALTER TABLE ledger_balances RENAME TO lb_old")
176
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(lb_old)") if r[1] != "source_note"]
177
+ conn.execute(f"CREATE TABLE ledger_balances AS SELECT {','.join(cols)} FROM lb_old")
178
+ conn.execute("DROP TABLE lb_old")
179
+ conn.commit()
180
+ conn.close()
181
+
182
+ initialize_database(data_dir)
183
+ after = _inspect(db)
184
+ assert after["version"] == HEAD
185
+ assert "source_note" in after["lb_cols"]
186
+
187
+
188
+# ----------------------------------------------------------- trigger check
189
+
190
+
191
+def test_require_triggers_passes_on_complete_set(tmp_path):
192
+ url = f"sqlite:///{tmp_path / 't.db'}"
193
+ upgrade_to_head(url)
194
+ engine = build_engine(url)
195
+ ensure_triggers(engine)
196
+ try:
197
+ assert missing_triggers(engine) == frozenset()
198
+ require_triggers(engine) # must not raise
199
+ assert expected_trigger_names() <= installed_trigger_names(engine)
200
+ finally:
201
+ engine.dispose()
202
+
203
+
204
+def test_require_triggers_fails_when_one_is_missing(tmp_path):
205
+ url = f"sqlite:///{tmp_path / 't.db'}"
206
+ upgrade_to_head(url)
207
+ engine = build_engine(url)
208
+ ensure_triggers(engine)
209
+ with engine.begin() as conn:
210
+ from sqlalchemy import text
211
+
212
+ conn.execute(text("DROP TRIGGER aram_audit_update"))
213
+ try:
214
+ assert "aram_audit_update" in missing_triggers(engine)
215
+ with pytest.raises(SchemaError, match="aram_audit_update"):
216
+ require_triggers(engine)
217
+ finally:
218
+ engine.dispose()
219
+
220
+
221
+# ----------------------------------------------------------- backup restore (R4)
222
+
223
+
224
+def _make_backup(tmp_path: Path) -> Path:
225
+ """Create a real backup of a small populated DB inside the allowed root."""
226
+ store = tmp_path / "store"
227
+ store.mkdir()
228
+ db = tmp_path / "live.db"
229
+ url = f"sqlite:///{db}"
230
+ upgrade_to_head(url)
231
+ engine = build_engine(url)
232
+ ensure_triggers(engine)
233
+ factory = sessionmaker(bind=engine, expire_on_commit=False)
234
+ with factory() as session:
235
+ backup_dir = tmp_path / "bk"
236
+ create_backup(session, backup_dir, store_root=store)
237
+ engine.dispose()
238
+ return backup_dir
239
+
240
+
241
+def test_restore_backup_migrates_and_checks_triggers(tmp_path):
242
+ backup_dir = _make_backup(tmp_path)
243
+ target = tmp_path / "restored"
244
+ report = restore_backup(backup_dir, data_dir=target, store_root=tmp_path / "store")
245
+ assert report["valid"] is True
246
+ assert report["schema_revision"] == HEAD
247
+ assert report["triggers_ok"] is True
248
+ info = _inspect(target / "aram.db")
249
+ assert info["version"] == HEAD
250
+ assert expected_trigger_names() <= info["triggers"]
251
+ assert (target / "source_store").is_dir()
252
+
253
+
254
+def test_restore_backup_refuses_to_overwrite_existing_db(tmp_path):
255
+ backup_dir = _make_backup(tmp_path)
256
+ target = tmp_path / "restored"
257
+ target.mkdir()
258
+ (target / "aram.db").write_bytes(b"existing")
259
+ with pytest.raises(BackupError, match="already exists"):
260
+ restore_backup(backup_dir, data_dir=target, store_root=tmp_path / "store")
261
+
262
+
263
+def test_restore_backup_rejects_corrupt_snapshot(tmp_path):
264
+ backup_dir = _make_backup(tmp_path)
265
+ # Tamper with the backed-up database so its hash no longer matches.
266
+ (backup_dir / "aram.db").write_bytes(b"corrupt")
267
+ with pytest.raises(BackupError, match="hash mismatch"):
268
+ restore_backup(backup_dir, data_dir=tmp_path / "restored", store_root=tmp_path / "store")
269
+
270
+
271
+def test_restore_backup_upgrades_a_stale_snapshot(tmp_path):
272
+ """A backup whose DB is stamped at 08 is migrated to 09 on restore."""
273
+ backup_dir = _make_backup(tmp_path)
274
+ db = backup_dir / "aram.db"
275
+ conn = sqlite3.connect(str(db))
276
+ conn.execute("UPDATE alembic_version SET version_num='20261204_08'")
277
+ conn.execute("ALTER TABLE ledger_balances RENAME TO lb_old")
278
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(lb_old)") if r[1] != "source_note"]
279
+ conn.execute(f"CREATE TABLE ledger_balances AS SELECT {','.join(cols)} FROM lb_old")
280
+ conn.execute("DROP TABLE lb_old")
281
+ conn.commit()
282
+ conn.close()
283
+ # Re-hash so verify_backup passes (the manifest must match the edited file).
284
+ import hashlib
285
+ import json
286
+
287
+ digest = hashlib.sha256(db.read_bytes()).hexdigest()
288
+ manifest = json.loads((backup_dir / "manifest.json").read_text(encoding="utf-8"))
289
+ manifest["database_sha256"] = digest
290
+ (backup_dir / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")
291
+
292
+ report = restore_backup(backup_dir, data_dir=tmp_path / "restored", store_root=tmp_path / "store")
293
+ assert report["schema_revision"] == HEAD
294
+ assert "source_note" in _inspect(tmp_path / "restored" / "aram.db")["lb_cols"]
295
+
296
+
297
+# ----------------------------------------------------------- restore API (R4)
298
+
299
+
300
+def test_restore_api_admin_roundtrip(api_client, tmp_path):
301
+ created = api_client.post("/api/v1/backup", json={"dest": "bk"})
302
+ assert created.status_code == 200, created.text
303
+ restored = api_client.post("/api/v1/backup/restore", json={"dest": "bk", "target": "restored"})
304
+ assert restored.status_code == 200, restored.text
305
+ body = restored.json()
306
+ assert body["schema_revision"] == HEAD
307
+ assert body["triggers_ok"] is True
308
+ assert (tmp_path / "restored" / "aram.db").exists()
309
+
310
+
311
+def test_restore_api_rejects_path_escape(api_client):
312
+ api_client.post("/api/v1/backup", json={"dest": "bk"})
313
+ escape = api_client.post(
314
+ "/api/v1/backup/restore", json={"dest": "bk", "target": "../../etc"}
315
+ )
316
+ assert escape.status_code == 422
317
+
318
+
319
+def test_restore_api_requires_admin(api_client):
320
+ api_client.post("/api/v1/backup", json={"dest": "bk"})
321
+ token = make_user(api_client, "prep", "preparer")
322
+ api_client.headers.update({"Authorization": f"Bearer {token}"})
323
+ denied = api_client.post("/api/v1/backup/restore", json={"dest": "bk", "target": "restored"})
324
+ assert denied.status_code == 403
325
+
326
+
327
+def test_restore_api_unauthenticated_is_401(anon_client):
328
+ r = anon_client.post("/api/v1/backup/restore", json={"dest": "bk", "target": "restored"})
329
+ assert r.status_code == 401
330
+
331
+
332
+# ----------------------------------------------------------- production-path guard
333
+
334
+
335
+def test_no_create_all_in_production_source():
336
+ """The production path must not call create_all (R4); tests/migrations may."""
337
+ src = Path(__file__).resolve().parents[1] / "src" / "aram_backend"
338
+ offenders = []
339
+ for py in src.rglob("*.py"):
340
+ text = py.read_text(encoding="utf-8")
341
+ if ".create_all(" in text:
342
+ offenders.append(str(py.relative_to(src)))
343
+ assert offenders == [], f"create_all still in production source: {offenders}"