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

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

Synced Dec 4, 14:15 UTC

dependabot/github_actions/actions/setup-node-6
add-index-html-10623938925177053894 arena/094f314c-aram arena/2d4eda07-aram chatgpt-phase1b2-autopilot codex/adr-future-connectors-pi-v1 codex/aram-account-note-source-trace-20261031 codex/aram-actions-node24-maintenance-20261031 codex/aram-analyst-review-workbook-20261031 codex/aram-bs-candidate-statement-20261031 codex/aram-cash-flow-direct-candidate-20261031 codex/aram-clean-reference-year-integrity-20261030 codex/aram-cross-statement-controls-20261031 codex/aram-equity-changes-candidate-20261031 codex/aram-five-statement-cli-20261031 codex/aram-five-statement-integration-20261031 codex/aram-five-statement-orchestrator-20261031 codex/aram-gate3-coverage-target-guard-20261030 codex/aram-gate3-hidden-xlsx-guard-20261030 codex/aram-gate3-integration-validation-20261030 codex/aram-gate3-mapping-change-preview-20261030 codex/aram-gate3-stale-note-guard-20261030 codex/aram-income-statement-candidate-20261031 codex/aram-manifest-referential-integrity-20261031 codex/aram-mapping-source-parser-20261101 codex/aram-multidimensional-mapping-20261101 codex/aram-multistatement-mapping-20261031 codex/aram-pipeline-manifest-schema-20261031 codex/aram-readonly-mapping-coverage-20261031 codex/aram-reconciliation-review-gate-20261031 codex/aram-same-flush-fiscal-lock-20261030 codex/aram-synthetic-windows-demo-20261031 codex/aram-trial-balance-diagnostic-20261031 codex/aram-windows-background-detail-search-20261031 codex/aram-windows-detail-review-20261031 codex/aram-windows-five-statement-pilot-20261031 codex/aram-windows-statement-figures-20261031 codex/gate-2a-pilot-workbook codex/gate-2a-pilot-workbook-6864754244772568979 codex/gate3-authenticated-principal-boundary-20261030 codex/gate3-authored-draft-staging-20261030 codex/gate3-carry-forward-preview-20261023 codex/gate3-draft-staging-audit-20261030 codex/gate3-mapping-batch-freshness-20261030 codex/gate3-mapping-batch-review-20261030 codex/gate3-mapping-core codex/gate3-mapping-coverage-20261023 codex/gate3-mapping-excel-20261023 codex/gate3-note-mapping-review-20261023 codex/gate3-signed-year-scope-20261030 codex/gate3-unapproved-proposal-storage-20261030 codex/payvast-mapping-discovery-20261023 codex/phase-2a-backend-foundation codex/phase-2b-post-merge-record codex/phase-2b-source-registration codex/phase-2b-source-registration-12955190277775369594 codex/post-gate2a-control-reconciliation codex/post-pr18-acceptance-record codex/project-control-foundation codex/t1-repo-hygiene-20261023 codex/t2-ci-hardening-20261023 codex/t3-explicit-migrations-20261023 codex/t6a-readonly-diagnostics-20261023 codex/v1-01-safety-gate-hardening codex/v1-year-isolation-followup-20261023 codex/windows-native-pilot-shell-20261030 dependabot/github_actions/actions/checkout-7 dependabot/github_actions/actions/setup-node-6 dependabot/github_actions/actions/setup-python-7 dependabot/github_actions/actions/upload-artifact-7 dependabot/npm_and_yarn/frontend/eslint-plugin-react-hooks-7.1.1 dependabot/npm_and_yarn/frontend/globals-17.15.0 dependabot/npm_and_yarn/frontend/vite-8.4.0 dependabot/npm_and_yarn/frontend/vitest-5.1.2 dependabot/npm_and_yarn/frontend/vitest/coverage-v8-5.1.2 dependabot/pip/backend/mypy-gte-1.13-and-lt-3 dependabot/pip/backend/pytest-cov-gte-6.0-and-lt-8 dependabot/pip/backend/setuptools-gte-75-and-lt-85 docs/aram-master-control-plan-20261111 docs/aram-roadmap-dashboard-20261030 docs/financial-statement-reconciliation-1402-1404-20261110 feat/gate3-governed-mapping-20261101 feat/gate3-package9-1-security-20261103 feat/gate3-package9-isolated-20261103 fix/password-unicode-validation-20261111 governance/aram-5-1-3-controls-20261030 governance/role-based-operating-model jules-1168663913887856558-73b8a885 jules-gate-2b-mapping-workflow-foundation-4137724387867065330 phase-1b1-audit-report-7365389436990903239 phase-2a-backend-foundation-10237597358138521261 phase1b2-postmerge-metadata-fix refactor/drg-parent-year-id-15088443704684163304 source-data-cleanup
py 187 lines 6.78 KB
Raw
1 """Local backup and integrity verification (Phase 7, booklet §7/§12).
2
3 Creates a consistent snapshot of the SQLite database (sqlite3 online backup API,
4 safe while the app is running), copies the content-addressed source store, and
5 writes a manifest recording the SHA-256 of the database and every source file plus
6 the audit-chain verification result. ``verify_backup`` recomputes every hash and
7 re-checks the audit chain so a backup is provably intact before restore. Offline
8 desktop only: no runtime network; PostgreSQL deployments use native pg_dump.
9 """
10
11 from __future__ import annotations
12
13 import hashlib
14 import json
15 import shutil
16 import sqlite3
17 from datetime import UTC, datetime
18 from pathlib import Path
19 from typing import Any, cast
20
21 from sqlalchemy.engine import Engine
22 from sqlalchemy.orm import Session
23
24 from aram_backend.services.audit import verify_chain
25
26
27 class BackupError(ValueError):
28 """Raised when a backup cannot be created or verified safely."""
29
30
31 def _sha256_file(path: Path) -> str:
32 digest = hashlib.sha256()
33 with path.open("rb") as handle:
34 for chunk in iter(lambda: handle.read(1024 * 1024), b""):
35 digest.update(chunk)
36 return digest.hexdigest()
37
38
39 def _database_path(session: Session) -> Path:
40 url = cast(Engine, session.get_bind()).url
41 if url.get_backend_name() != "sqlite":
42 raise BackupError("local backup supports SQLite only; use pg_dump for PostgreSQL")
43 database = url.database
44 if not database or database == ":memory:":
45 raise BackupError("cannot back up an in-memory database")
46 return Path(database)
47
48
49 def allowed_backup_root(store_root: str | Path, backup_root: str | Path | None = None) -> Path:
50 """The only folder tree a backup may be written to (R1, booklet 2.1).
51
52 Defaults to the parent of the content-addressed source store, i.e. the local
53 data directory. ``ARAM_BACKUP_ROOT`` narrows it further.
54 """
55 if backup_root:
56 return Path(backup_root).expanduser().resolve()
57 return Path(store_root).expanduser().resolve().parent
58
59
60 def confine_dest(
61 dest: str | Path, *, store_root: str | Path, backup_root: str | Path | None = None
62 ) -> Path:
63 """Resolve ``dest`` and refuse anything outside the allowed data folder.
64
65 Relative paths are taken inside the allowed root; ``..`` traversal, absolute
66 paths elsewhere, and symlinks pointing out of the tree are all rejected
67 *after* resolution, so no spelling can escape.
68 """
69 root = allowed_backup_root(store_root, backup_root)
70 candidate = Path(dest).expanduser()
71 if not candidate.is_absolute():
72 candidate = root / candidate
73 resolved = candidate.resolve()
74 if resolved == root or not resolved.is_relative_to(root):
75 raise BackupError("مسیر پشتیبان باید داخل پوشهٔ دادهٔ مجاز باشد.")
76 return resolved
77
78
79 def create_backup(
80 session: Session,
81 dest: str | Path,
82 *,
83 store_root: str | Path,
84 backup_root: str | Path | None = None,
85 ) -> dict[str, Any]:
86 """Write a consistent backup directory and return its manifest."""
87 dest = confine_dest(dest, store_root=store_root, backup_root=backup_root)
88 if dest.exists() and any(dest.iterdir()):
89 raise BackupError(f"backup destination '{dest}' is not empty")
90 dest.mkdir(parents=True, exist_ok=True)
91
92 db_path = _database_path(session)
93 backup_db = dest / "aram.db"
94 # Online backup API: a consistent snapshot even with concurrent writers.
95 source_conn = sqlite3.connect(str(db_path))
96 try:
97 target_conn = sqlite3.connect(str(backup_db))
98 try:
99 source_conn.backup(target_conn)
100 finally:
101 target_conn.close()
102 finally:
103 source_conn.close()
104
105 store_src = Path(store_root)
106 store_dest = dest / "source_store"
107 source_hashes: dict[str, str] = {}
108 if store_src.exists():
109 shutil.copytree(store_src, store_dest)
110 for file in sorted(store_dest.rglob("*")):
111 if file.is_file():
112 rel = file.relative_to(store_dest).as_posix()
113 source_hashes[rel] = _sha256_file(file)
114 else:
115 store_dest.mkdir()
116
117 chain_ok = verify_chain(session)
118 manifest: dict[str, Any] = {
119 "format": "aram-backup-1",
120 "created_at": datetime.now(UTC).isoformat(),
121 "database_sha256": _sha256_file(backup_db),
122 "source_store_sha256": source_hashes,
123 "audit_chain_valid": chain_ok,
124 }
125 (dest / "manifest.json").write_text(
126 json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8"
127 )
128 if not chain_ok:
129 raise BackupError("audit chain is not intact; backup refused")
130 return manifest
131
132
133 def verify_backup(
134 backup_dir: str | Path,
135 *,
136 store_root: str | Path | None = None,
137 backup_root: str | Path | None = None,
138 ) -> dict[str, Any]:
139 """Recompute every recorded hash and re-check the audit chain in the snapshot."""
140 if store_root is not None or backup_root:
141 backup_dir = confine_dest(backup_dir, store_root=store_root or "", backup_root=backup_root)
142 else:
143 backup_dir = Path(backup_dir)
144 manifest_path = backup_dir / "manifest.json"
145 if not manifest_path.exists():
146 raise BackupError("manifest.json is missing")
147 manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
148
149 db_path = backup_dir / "aram.db"
150 if not db_path.exists():
151 raise BackupError("aram.db is missing from the backup")
152 if _sha256_file(db_path) != manifest.get("database_sha256"):
153 raise BackupError("database hash mismatch; backup is corrupt")
154
155 store_dest = backup_dir / "source_store"
156 recorded: dict[str, str] = manifest.get("source_store_sha256", {})
157 for rel, expected in recorded.items():
158 file = store_dest / rel
159 if not file.exists() or _sha256_file(file) != expected:
160 raise BackupError(f"source file '{rel}' is missing or corrupt")
161
162 # Re-verify the audit chain directly inside the backed-up database.
163 conn = sqlite3.connect(str(db_path))
164 try:
165 rows = conn.execute(
166 "SELECT previous_hash, payload_hash, chain_hash FROM audit_entries ORDER BY id ASC"
167 ).fetchall()
168 finally:
169 conn.close()
170 previous = "0" * 64
171 for prev_hash, payload_hash, chain_hash in rows:
172 if prev_hash != previous:
173 raise BackupError("audit chain break detected in backup")
174 expected = hashlib.sha256(f"{previous}{payload_hash}".encode("ascii")).hexdigest()
175 if chain_hash != expected:
176 raise BackupError("audit chain hash mismatch in backup")
177 previous = chain_hash
178
179 return {
180 "valid": True,
181 "database_sha256": manifest["database_sha256"],
182 "source_files": len(recorded),
183 "audit_entries": len(rows),
184 }
185
186
187 __all__ = ["BackupError", "allowed_backup_root", "confine_dest", "create_backup", "verify_backup"]