Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 04:15 UTC
source-data-cleanup
add-index-html-10623938925177053894
arena/094f314c-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
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
| 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 create_backup(session: Session, dest: str | Path, *, store_root: str | Path) -> dict[str, Any]: |
| 50 | """Write a consistent backup directory and return its manifest.""" |
| 51 | dest = Path(dest) |
| 52 | if dest.exists() and any(dest.iterdir()): |
| 53 | raise BackupError(f"backup destination '{dest}' is not empty") |
| 54 | dest.mkdir(parents=True, exist_ok=True) |
| 55 | |
| 56 | db_path = _database_path(session) |
| 57 | backup_db = dest / "aram.db" |
| 58 | # Online backup API: a consistent snapshot even with concurrent writers. |
| 59 | source_conn = sqlite3.connect(str(db_path)) |
| 60 | try: |
| 61 | target_conn = sqlite3.connect(str(backup_db)) |
| 62 | try: |
| 63 | source_conn.backup(target_conn) |
| 64 | finally: |
| 65 | target_conn.close() |
| 66 | finally: |
| 67 | source_conn.close() |
| 68 | |
| 69 | store_src = Path(store_root) |
| 70 | store_dest = dest / "source_store" |
| 71 | source_hashes: dict[str, str] = {} |
| 72 | if store_src.exists(): |
| 73 | shutil.copytree(store_src, store_dest) |
| 74 | for file in sorted(store_dest.rglob("*")): |
| 75 | if file.is_file(): |
| 76 | rel = file.relative_to(store_dest).as_posix() |
| 77 | source_hashes[rel] = _sha256_file(file) |
| 78 | else: |
| 79 | store_dest.mkdir() |
| 80 | |
| 81 | chain_ok = verify_chain(session) |
| 82 | manifest: dict[str, Any] = { |
| 83 | "format": "aram-backup-1", |
| 84 | "created_at": datetime.now(UTC).isoformat(), |
| 85 | "database_sha256": _sha256_file(backup_db), |
| 86 | "source_store_sha256": source_hashes, |
| 87 | "audit_chain_valid": chain_ok, |
| 88 | } |
| 89 | (dest / "manifest.json").write_text( |
| 90 | json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8" |
| 91 | ) |
| 92 | if not chain_ok: |
| 93 | raise BackupError("audit chain is not intact; backup refused") |
| 94 | return manifest |
| 95 | |
| 96 | |
| 97 | def verify_backup(backup_dir: str | Path) -> dict[str, Any]: |
| 98 | """Recompute every recorded hash and re-check the audit chain in the snapshot.""" |
| 99 | backup_dir = Path(backup_dir) |
| 100 | manifest_path = backup_dir / "manifest.json" |
| 101 | if not manifest_path.exists(): |
| 102 | raise BackupError("manifest.json is missing") |
| 103 | manifest = json.loads(manifest_path.read_text(encoding="utf-8")) |
| 104 | |
| 105 | db_path = backup_dir / "aram.db" |
| 106 | if not db_path.exists(): |
| 107 | raise BackupError("aram.db is missing from the backup") |
| 108 | if _sha256_file(db_path) != manifest.get("database_sha256"): |
| 109 | raise BackupError("database hash mismatch; backup is corrupt") |
| 110 | |
| 111 | store_dest = backup_dir / "source_store" |
| 112 | recorded: dict[str, str] = manifest.get("source_store_sha256", {}) |
| 113 | for rel, expected in recorded.items(): |
| 114 | file = store_dest / rel |
| 115 | if not file.exists() or _sha256_file(file) != expected: |
| 116 | raise BackupError(f"source file '{rel}' is missing or corrupt") |
| 117 | |
| 118 | # Re-verify the audit chain directly inside the backed-up database. |
| 119 | conn = sqlite3.connect(str(db_path)) |
| 120 | try: |
| 121 | rows = conn.execute( |
| 122 | "SELECT previous_hash, payload_hash, chain_hash FROM audit_entries ORDER BY id ASC" |
| 123 | ).fetchall() |
| 124 | finally: |
| 125 | conn.close() |
| 126 | previous = "0" * 64 |
| 127 | for prev_hash, payload_hash, chain_hash in rows: |
| 128 | if prev_hash != previous: |
| 129 | raise BackupError("audit chain break detected in backup") |
| 130 | expected = hashlib.sha256(f"{previous}{payload_hash}".encode("ascii")).hexdigest() |
| 131 | if chain_hash != expected: |
| 132 | raise BackupError("audit chain hash mismatch in backup") |
| 133 | previous = chain_hash |
| 134 | |
| 135 | return { |
| 136 | "valid": True, |
| 137 | "database_sha256": manifest["database_sha256"], |
| 138 | "source_files": len(recorded), |
| 139 | "audit_entries": len(rows), |
| 140 | } |
| 141 | |
| 142 | |
| 143 | __all__ = ["BackupError", "create_backup", "verify_backup"] |