@davoodmehraban89 / LifeMate / commits / 29fa2c7
Fork 0

LifeMate — Personal, Family & Learning Companion

feat: rehearse encrypted personal recovery with synthetic SQLite only

Quinn White committed Oct 21, 2026 at 20:47 UTC 29fa2c7247847c4eadb7792daaa91379dd0f2367
11 files changed +1643
.github/workflows/personal-recovery-qa.yml new
+43
@@ -0,0 +1,43 @@
1 +name: LifeGuide synthetic recovery QA
2 +on:
3 + push:
4 + branches: [feat/personal-encrypted-recovery, test/personal-recovery-acceptance]
5 + pull_request:
6 + paths:
7 + - scripts/personal_recovery/**
8 + - scripts/personal_recovery_cli.py
9 + - scripts/tests/test_recovery*.py
10 + - requirements-personal-recovery.txt
11 + - .github/workflows/personal-recovery-qa.yml
12 + workflow_dispatch:
13 +permissions:
14 + contents: read
15 +jobs:
16 + host-synthetic-recovery:
17 + runs-on: ubuntu-latest
18 + steps:
19 + - uses: actions/checkout@v4
20 + - uses: actions/setup-python@v5
21 + with: {python-version: '3.11'}
22 + - name: Install pinned host QA dependency
23 + run: python -m pip install -r requirements-personal-recovery.txt
24 + - name: Run recovery refusal, integrity and filesystem tests
25 + run: python -m unittest discover -s scripts/tests -p 'test_recovery*.py' -v
26 + - name: Run existing APK and Android host guards
27 + run: python -m unittest discover -s apps/lifemate/tool -p '*_test.py' -v
28 + - name: Rehearse actual synthetic SQLite close and reopen
29 + shell: bash
30 + run: |
31 + python scripts/personal_recovery_cli.py demo --directory "$RUNNER_TEMP/synthetic-recovery" --acknowledge-synthetic-only > "$RUNNER_TEMP/recovery-verification.json"
32 + cat "$RUNNER_TEMP/recovery-verification.json"
33 + - name: Check tracked artifacts and naming
34 + run: |
35 + python scripts/check-tracked-secrets.py
36 + python scripts/audit-naming.py --check
37 + - uses: actions/upload-artifact@v4
38 + with:
39 + name: LifeGuide-synthetic-recovery-verification
40 + path: ${{ runner.temp }}/recovery-verification.json
41 + if-no-files-found: error
42 + retention-days: 14
43 + # Deliberately no upload of SQLite, archive, passphrase or APK files.
.gitignore
+9
@@ -33,3 +33,12 @@ deployment/tls/*
33
34 __pycache__/
35 *.pyc
36 +
37 +# Owner data and local synthetic recovery runs never belong in Git.
38 +*.lgrf
39 +*.sqlite
40 +*.sqlite3
41 +*.sqlite-wal
42 +*.sqlite-shm
43 +*.sqlite-journal
44 +.venv-recovery/
docs/operations/PERSONAL_SYNTHETIC_RECOVERY.md new
+42
@@ -0,0 +1,42 @@
1 +# LifeGuide — تمرین بازیابی رمزدار، فقط دادهٔ ساختگی
2 +
3 +این بسته ابزار QA است؛ پشتیبان‌گیری از گوشی یا اطلاعات مالک نیست. [ADR0018](../decisions/0018-offline-installed-data-rescue-options.md) فقط آماده‌سازی و آزمون ساختگی را مجاز می‌کند. **نسخهٔ نصب‌شده را حذف، clear-data یا با APK ناسازگار جایگزین نکنید.** کلید خصوصی امضای اولیه هنوز UNVERIFIED است؛ APK آن کلید را بازیابی نمی‌کند.
4 +
5 +## چه چیزی واقعاً آزمایش می‌شود
6 +
7 +Python3.11+، SQLite واقعی schema1، یک پروفایل خیالی، چهار نوع تکرار، سه ساعت هفتگی و چهار نوبت مستقل با تیک/ویرایش/بایگانی. خروجی JSON قابل‌حمل با تمام فیلدها در حافظه ساخته، با AES-256-GCM و Scrypt ثابت رمز می‌شود؛ salt و nonce هر بار تصادفی‌اند. سپس فایل رمزدار دوباره باز، اعتبارسنجی و به SQLite تازه بازسازی می‌شود. SQL مستقل و تطبیق همهٔ مقادیر پس از بسته‌شدن اتصال بررسی می‌شوند.
8 +
9 +فایل فقط اگر marker آزمایشی در هدر SQLite داشته باشد پذیرفته می‌شود. marker جلوی اشتباه معمول را می‌گیرد؛ **احراز اصالت یا اثبات ساختگی‌بودن نیست** و نباید برای عبور دادهٔ واقعی تنظیم شود. فایل بدون marker پیش از خواندن بدنهٔ رکوردها رد می‌شود. schema آینده، جدول/trigger/view ناشناخته، UUID/تاریخ/رابطهٔ نامعتبر، فایل حجیم، رمز اشتباه و تغییر ciphertext رد می‌شوند.
10 +
11 +این مرحله فقط SQLite **بسته‌شده، بدون WAL/SHM/journal و با هدر rollback** را می‌پذیرد. جمع‌آوری سازگار WAL از Android، نصب کناری و آپدیت بعدی app تازه آزمون جدا دارند. رد فایل به معنی پاک‌کردن sidecar یا reset دیتابیس نیست. برنامهٔ موجود و داده‌هایش دست‌نخورده بمانند.
12 +
13 +## اجرای محلی با اطلاعات خیالی
14 +
15 +از ریشهٔ شاخهٔ `feat/personal-encrypted-recovery`؛ نصب وابستگی اینترنت می‌خواهد، خود ابزار شبکه ندارد. پس از نصب وابستگی می‌توان شبکه را قطع کرد. روی Windows به‌جای `python3` از Python3.11+ نصب‌شده استفاده شود؛ Windows/USB/ACL واقعی مالک هنوز **UNVERIFIED** است.
16 +
17 +```bash
18 +python3 -m venv .venv-recovery
19 +.venv-recovery/bin/python -m pip install -r requirements-personal-recovery.txt
20 +.venv-recovery/bin/python -m unittest discover -s scripts/tests -p 'test_recovery*.py' -v
21 +.venv-recovery/bin/python scripts/personal_recovery_cli.py demo --directory /tmp/lifeguide-fictional-rehearsal --acknowledge-synthetic-only
22 +```
23 +
24 +مسیر demo باید تازه یا خالی باشد. گزارش فقط شمار رکوردها، hash و PASS/UNVERIFIED دارد؛ گذرواژهٔ تصادفی همین demo چاپ یا ذخیره نمی‌شود و فایل demo برای پشتیبان قابل اتکای مالک نیست. پوشه فقط نمونهٔ خیالی را نگه می‌دارد. خروجی موفق `result=PASS` است، خطا exit2 و لغو exit130. برای تکرار، پوشهٔ تازه انتخاب کنید؛ فایل موجود بازنویسی نمی‌شود.
25 +
26 +دستورهای جزئی فقط برای همین fixture ساختگی هستند. هر خروجی باید مسیر تازه باشد:
27 +
28 +```bash
29 +python3 scripts/personal_recovery_cli.py create-fixture --output /tmp/fictional-source.sqlite --acknowledge-synthetic-only
30 +python3 scripts/personal_recovery_cli.py pack --source /tmp/fictional-source.sqlite --output /tmp/fictional-transfer.lgrf --acknowledge-synthetic-only
31 +python3 scripts/personal_recovery_cli.py restore-fixture --source /tmp/fictional-transfer.lgrf --output /tmp/fictional-restored.sqlite --acknowledge-synthetic-only
32 +```
33 +
34 +pack/restore ترمینال تعاملی می‌خواهند؛ گذرواژه مخفی پرسیده می‌شود. آن را در خط فرمان، env، Git، پیام یا لاگ ننویسید. حداقل۱۲ نویسه فقط حداقل فنی است؛ برای دادهٔ واقعی در آینده عبارت طولانی و تصادفی با نگهداری امن لازم است. رمزگذاری، گذرواژهٔ ضعیف را امن نمی‌کند؛ طول ciphertext دیده می‌شود و پاک‌سازی تضمین‌شدهٔ حافظه در Python نداریم. ابزار فعلی مجوز استفاده از دادهٔ واقعی ندارد.
35 +
36 +فایل خروجی روی POSIX با mode0600، پس از تکمیل و fsync فایل، با hard-link اتمیک و بدون overwrite منتشر می‌شود. فایل‌سیستم فاقد hard-link با خطا متوقف می‌شود؛ fallback ناامن ندارد. قطع عملیات یا خطای شبیه‌سازی‌شدهٔ کمبود فضا پیش از انتشار، فایل نیمه‌کاره باقی نمی‌گذارد. دوام در قطع برق، ACL و رفتار Windows، دیسک پر واقعی و محیط گوشی **UNVERIFIED** هستند.
37 +
38 +## مرز تحویل بعدی
39 +
40 +این PR کلاینت، Backend، شناسهٔ نصب، baseline امضای قدیمی یا مجوز اعلان را تغییر نمی‌دهد و APK تازه نمی‌دهد. آزمون بعدی باید exact APK قدیمی را فقط روی شبیه‌ساز تازه با دادهٔ خیالی اجرا کند، نصب آزمایشی کناری و بازگشایی هر دو DB پیش‌فرض و سپس ارتقای همان نصب تازه را بررسی کند. APK fixture هرگز توزیع نمی‌شود. اعلان app تازه پیش‌فرض خاموش می‌ماند؛ رضایت/مجوز قدیمی منتقل نمی‌شود.
41 +
42 +انتقال واقعی بعد از پذیرش، فقط روی رایانه و گوشی مالک و با انتخاب قابل‌فهم خود کاربر فرزند دربارهٔ دامنه، مقصد و دارندهٔ رمز انجام‌پذیر خواهد بود. تیم DB، رمز، کلید یا اطلاعات خصوصی نمی‌گیرد. هیچ نمای والد، دسترسی خانوادگی، ارسال AI یا cloud backup اضافه نشده است.
scripts/personal_recovery/archive.py new
+70
@@ -0,0 +1,70 @@
1 +"""Bounded authenticated envelopes for the synthetic recovery preparation tool.
2 +
3 +Version 1 fixes the KDF parameters; archive bytes cannot choose their cost.
4 +This module only handles in-memory bytes and never logs or writes their content.
5 +"""
6 +
7 +import os
8 +
9 +from cryptography.exceptions import InvalidTag
10 +from cryptography.hazmat.primitives.ciphers.aead import AESGCM
11 +from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
12 +
13 +from .common import MAX_PAYLOAD_BYTES, RecoveryError
14 +
15 +
16 +_MAGIC = b"LGRF\x01"
17 +_SALT_BYTES = 16
18 +_NONCE_BYTES = 12
19 +_TAG_BYTES = 16
20 +_HEADER_BYTES = len(_MAGIC) + _SALT_BYTES + _NONCE_BYTES
21 +_MIN_ARCHIVE_BYTES = _HEADER_BYTES + _TAG_BYTES
22 +_MAX_ARCHIVE_BYTES = MAX_PAYLOAD_BYTES + _MIN_ARCHIVE_BYTES
23 +
24 +
25 +def _password_bytes(passphrase: str) -> bytes:
26 + # Bound characters before encoding, then enforce the UTF-8 byte limit.
27 + if not isinstance(passphrase, str) or not 12 <= len(passphrase) <= 1024:
28 + raise RecoveryError("invalid_passphrase")
29 + try:
30 + encoded = passphrase.encode("utf-8")
31 + except UnicodeEncodeError:
32 + raise RecoveryError("invalid_passphrase") from None
33 + if len(encoded) > 1024:
34 + raise RecoveryError("invalid_passphrase")
35 + return encoded
36 +
37 +
38 +def _derive_key(password: bytes, salt: bytes) -> bytes:
39 + return Scrypt(salt=salt, length=32, n=32768, r=8, p=1).derive(password)
40 +
41 +
42 +def seal(payload: bytes, passphrase: str) -> bytes:
43 + """Encrypt up to 8 MiB using a fresh salt and nonce for each envelope."""
44 + if not isinstance(payload, bytes) or len(payload) > MAX_PAYLOAD_BYTES:
45 + raise RecoveryError("invalid_payload")
46 + password = _password_bytes(passphrase)
47 + salt = os.urandom(_SALT_BYTES)
48 + nonce = os.urandom(_NONCE_BYTES)
49 + header = _MAGIC + salt + nonce
50 + ciphertext = AESGCM(_derive_key(password, salt)).encrypt(nonce, payload, header)
51 + return header + ciphertext
52 +
53 +
54 +def open_archive(archive: bytes, passphrase: str) -> bytes:
55 + """Authenticate before returning plaintext; reject invalid bounds before KDF."""
56 + if (
57 + not isinstance(archive, bytes)
58 + or not _MIN_ARCHIVE_BYTES <= len(archive) <= _MAX_ARCHIVE_BYTES
59 + or archive[: len(_MAGIC)] != _MAGIC
60 + ):
61 + raise RecoveryError("invalid_archive")
62 + password = _password_bytes(passphrase)
63 + salt = archive[len(_MAGIC) : len(_MAGIC) + _SALT_BYTES]
64 + nonce = archive[len(_MAGIC) + _SALT_BYTES : _HEADER_BYTES]
65 + try:
66 + return AESGCM(_derive_key(password, salt)).decrypt(
67 + nonce, archive[_HEADER_BYTES:], archive[:_HEADER_BYTES]
68 + )
69 + except InvalidTag:
70 + raise RecoveryError("archive_authentication_failed") from None
scripts/personal_recovery/files.py new
+69
@@ -0,0 +1,69 @@
1 +"""Bounded reads and no-overwrite publication for fictional QA files only."""
2 +
3 +import os
4 +from pathlib import Path
5 +import stat
6 +import tempfile
7 +
8 +from .common import RecoveryError
9 +
10 +
11 +def read_bounded(path: Path, limit: int, *, prefix_validator=None) -> bytes:
12 + """Refuse symlinks/nonregular files; never read unbounded input into memory."""
13 + path = Path(path)
14 + descriptor = None
15 + try:
16 + before = path.lstat()
17 + if not stat.S_ISREG(before.st_mode) or before.st_size > limit:
18 + raise RecoveryError("invalid_input_file")
19 + descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
20 + info = os.fstat(descriptor)
21 + if (not stat.S_ISREG(info.st_mode) or info.st_size > limit
22 + or (before.st_dev, before.st_ino) != (info.st_dev, info.st_ino)):
23 + raise RecoveryError("invalid_input_file")
24 + with os.fdopen(descriptor, "rb", buffering=0) as stream:
25 + descriptor = None
26 + prefix = stream.read(min(limit + 1, 100))
27 + if prefix_validator is not None:
28 + prefix_validator(prefix)
29 + data = prefix + stream.read(limit + 1 - len(prefix))
30 + if len(data) > limit:
31 + raise RecoveryError("invalid_input_file")
32 + return data
33 + except OSError:
34 + raise RecoveryError("file_io_error") from None
35 + finally:
36 + if descriptor is not None:
37 + os.close(descriptor)
38 +
39 +
40 +def publish_new(destination: Path, payload: bytes) -> None:
41 + """Link a complete mode0600 temp file atomically; existing paths always win.
42 +
43 + A hard-link-capable local filesystem is required. No overwrite fallback is
44 + permitted. fsync completes before publication; power-loss durability of the
45 + directory and platform-specific filesystem behavior are not asserted here.
46 + """
47 + destination = Path(destination)
48 + temporary = None
49 + descriptor = None
50 + try:
51 + if os.path.lexists(destination):
52 + raise RecoveryError("destination_exists")
53 + descriptor, name = tempfile.mkstemp(prefix=".lifeguide-qa-", dir=destination.parent)
54 + temporary = Path(name)
55 + with os.fdopen(descriptor, "wb") as stream:
56 + descriptor = None
57 + stream.write(payload)
58 + stream.flush()
59 + os.fsync(stream.fileno())
60 + os.link(temporary, destination)
61 + except FileExistsError:
62 + raise RecoveryError("destination_exists") from None
63 + except OSError:
64 + raise RecoveryError("file_io_error") from None
65 + finally:
66 + if descriptor is not None:
67 + os.close(descriptor)
68 + if temporary is not None:
69 + temporary.unlink(missing_ok=True)
scripts/personal_recovery/snapshot.py new
+365
@@ -0,0 +1,365 @@
1 +"""Portable, synthetic-only recovery snapshots of the standalone SQLite v1 store.
2 +
3 +The application_id marker is an accident-prevention gate, not authentication or
4 +proof of provenance: anyone can set it. This kit must never be used on owner data.
5 +Only closed rollback-journal fixtures without sidecars are accepted. WAL-mode
6 +headers are refused even after their sidecars have been removed.
7 +"""
8 +from datetime import date
9 +import json
10 +from pathlib import Path
11 +import re
12 +import sqlite3
13 +import uuid
14 +
15 +from .common import (
16 + FIXTURE_APPLICATION_ID, MAX_PAYLOAD_BYTES, MAX_ROWS, RecoveryError, SCHEMA_VERSION,
17 +)
18 +from .files import read_bounded
19 +
20 +FORMAT = 'LifeGuideSyntheticRecovery'
21 +# Fixed statements mirror StandaloneStore._migrate v1. Source SQL is never run.
22 +DDL = (
23 + """CREATE TABLE local_profiles (
24 + singleton INTEGER PRIMARY KEY CHECK(singleton = 1),
25 + id TEXT NOT NULL UNIQUE CHECK(length(id) = 36),
26 + display_name TEXT NOT NULL CHECK(length(trim(display_name)) BETWEEN 1 AND 80),
27 + category TEXT NOT NULL CHECK(category IN ('girl_minor','boy_minor','adult')),
28 + companion_name TEXT NOT NULL CHECK(length(trim(companion_name)) BETWEEN 1 AND 40),
29 + theme_key TEXT NOT NULL CHECK(theme_key IN ('violet','blue','mint','coral'))
30 + )""",
31 + """CREATE TABLE local_plans (
32 + id TEXT PRIMARY KEY NOT NULL CHECK(length(id) = 36),
33 + profile_id TEXT NOT NULL REFERENCES local_profiles(id),
34 + title TEXT NOT NULL CHECK(length(trim(title)) BETWEEN 1 AND 200),
35 + kind TEXT NOT NULL CHECK(kind IN ('task','event','routine')),
36 + recurrence TEXT NOT NULL CHECK(recurrence IN ('once','daily','everyTwoDays','weekly')),
37 + start_date TEXT NOT NULL CHECK(length(start_date) = 10),
38 + until_date TEXT CHECK(until_date IS NULL OR (length(until_date) = 10 AND until_date >= start_date)),
39 + start_minute INTEGER NOT NULL CHECK(start_minute BETWEEN 0 AND 1439),
40 + end_minute INTEGER NOT NULL CHECK(end_minute BETWEEN 1 AND 1440 AND end_minute > start_minute),
41 + reminder_minutes INTEGER CHECK(reminder_minutes IS NULL OR reminder_minutes IN (0,5,10,15,30)),
42 + archived INTEGER NOT NULL DEFAULT 0 CHECK(archived IN (0,1))
43 + )""",
44 + """CREATE TABLE local_weekly_slots (
45 + plan_id TEXT NOT NULL REFERENCES local_plans(id),
46 + weekday INTEGER NOT NULL CHECK(weekday BETWEEN 1 AND 7),
47 + start_minute INTEGER NOT NULL CHECK(start_minute BETWEEN 0 AND 1439),
48 + end_minute INTEGER NOT NULL CHECK(end_minute BETWEEN 1 AND 1440 AND end_minute > start_minute),
49 + PRIMARY KEY(plan_id, weekday)
50 + )""",
51 + """CREATE TABLE local_occurrences (
52 + id TEXT PRIMARY KEY NOT NULL CHECK(length(id) = 36),
53 + plan_id TEXT NOT NULL REFERENCES local_plans(id),
54 + occurrence_date TEXT NOT NULL CHECK(length(occurrence_date) = 10),
55 + title TEXT NOT NULL CHECK(length(trim(title)) BETWEEN 1 AND 200),
56 + kind TEXT NOT NULL CHECK(kind IN ('task','event','routine')),
57 + start_minute INTEGER NOT NULL CHECK(start_minute BETWEEN 0 AND 1439),
58 + end_minute INTEGER NOT NULL CHECK(end_minute BETWEEN 1 AND 1440 AND end_minute > start_minute),
59 + completed INTEGER NOT NULL DEFAULT 0 CHECK(completed IN (0,1)),
60 + archived INTEGER NOT NULL DEFAULT 0 CHECK(archived IN (0,1)),
61 + reminder_minutes INTEGER CHECK(reminder_minutes IS NULL OR reminder_minutes IN (0,5,10,15,30)),
62 + UNIQUE(plan_id, occurrence_date)
63 + )""",
64 + 'CREATE INDEX local_occurrences_date ON local_occurrences(occurrence_date)',
65 +)
66 +COLUMNS = {
67 + 'local_profiles': ('singleton', 'id', 'display_name', 'category', 'companion_name', 'theme_key'),
68 + 'local_plans': ('id', 'profile_id', 'title', 'kind', 'recurrence', 'start_date', 'until_date',
69 + 'start_minute', 'end_minute', 'reminder_minutes', 'archived'),
70 + 'local_weekly_slots': ('plan_id', 'weekday', 'start_minute', 'end_minute'),
71 + 'local_occurrences': ('id', 'plan_id', 'occurrence_date', 'title', 'kind', 'start_minute',
72 + 'end_minute', 'completed', 'archived', 'reminder_minutes'),
73 +}
74 +PRIMARY_KEYS = {
75 + 'local_profiles': ('singleton',), 'local_plans': ('id',),
76 + 'local_weekly_slots': ('plan_id', 'weekday'), 'local_occurrences': ('id',),
77 +}
78 +KINDS = ('task', 'event', 'routine')
79 +RECURRENCES = ('once', 'daily', 'everyTwoDays', 'weekly')
80 +
81 +
82 +def _require(condition):
83 + if not condition:
84 + raise RecoveryError('invalid_snapshot')
85 +
86 +
87 +def _integer(value, minimum, maximum):
88 + _require(type(value) is int and minimum <= value <= maximum)
89 +
90 +
91 +def _text(value, maximum):
92 + _require(type(value) is str and '\x00' not in value)
93 + try:
94 + length = len(value.strip().encode('utf-16-le')) // 2
95 + except UnicodeError:
96 + raise RecoveryError('invalid_snapshot') from None
97 + _require(1 <= length <= maximum)
98 +
99 +
100 +def _uuid(value):
101 + _require(type(value) is str)
102 + try:
103 + parsed = uuid.UUID(value)
104 + except (ValueError, AttributeError):
105 + raise RecoveryError('invalid_snapshot') from None
106 + _require(str(parsed) == value and parsed.version == 4 and parsed.variant == uuid.RFC_4122)
107 +
108 +
109 +def _date(value):
110 + _require(type(value) is str and re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', value))
111 + try:
112 + date.fromisoformat(value)
113 + except ValueError:
114 + raise RecoveryError('invalid_snapshot') from None
115 +
116 +
117 +def _time(row):
118 + _integer(row['start_minute'], 0, 1439)
119 + _integer(row['end_minute'], 1, 1440)
120 + _require(row['end_minute'] > row['start_minute'])
121 +
122 +
123 +def _reminder(value):
124 + _require(value is None or (type(value) is int and value in (0, 5, 10, 15, 30)))
125 +
126 +
127 +def _validate(document):
128 + _require(type(document) is dict and set(document) == {'format', 'schemaVersion', 'syntheticOnly', 'tables'})
129 + _require(document['format'] == FORMAT and type(document['format']) is str)
130 + _require(type(document['schemaVersion']) is int and document['schemaVersion'] == SCHEMA_VERSION)
131 + _require(document['syntheticOnly'] is True)
132 + tables = document['tables']
133 + _require(type(tables) is dict and set(tables) == set(COLUMNS))
134 + total = 0
135 + for table, columns in COLUMNS.items():
136 + rows = tables[table]
137 + _require(type(rows) is list)
138 + total += len(rows)
139 + _require(total <= MAX_ROWS)
140 + for row in rows:
141 + _require(type(row) is dict and set(row) == set(columns))
142 + _require(len(tables['local_profiles']) <= 1)
143 + profile_ids = set()
144 + for row in tables['local_profiles']:
145 + _integer(row['singleton'], 1, 1)
146 + _uuid(row['id'])
147 + _text(row['display_name'], 80)
148 + _text(row['companion_name'], 40)
149 + _require(row['category'] in ('girl_minor', 'boy_minor', 'adult'))
150 + _require(row['theme_key'] in ('violet', 'blue', 'mint', 'coral'))
151 + profile_ids.add(row['id'])
152 + plans = {}
153 + for row in tables['local_plans']:
154 + _uuid(row['id'])
155 + _uuid(row['profile_id'])
156 + _require(row['id'] not in plans and row['profile_id'] in profile_ids)
157 + _text(row['title'], 200)
158 + _require(row['kind'] in KINDS and row['recurrence'] in RECURRENCES)
159 + _date(row['start_date'])
160 + if row['until_date'] is not None:
161 + _date(row['until_date'])
162 + _require(row['until_date'] >= row['start_date'])
163 + _time(row)
164 + _reminder(row['reminder_minutes'])
165 + _integer(row['archived'], 0, 1)
166 + plans[row['id']] = row
167 + slots = set()
168 + weekly_plan_ids = set()
169 + for row in tables['local_weekly_slots']:
170 + _uuid(row['plan_id'])
171 + _require(row['plan_id'] in plans and plans[row['plan_id']]['recurrence'] == 'weekly')
172 + _integer(row['weekday'], 1, 7)
173 + _time(row)
174 + key = (row['plan_id'], row['weekday'])
175 + _require(key not in slots)
176 + slots.add(key)
177 + weekly_plan_ids.add(row['plan_id'])
178 + _require(weekly_plan_ids == {p['id'] for p in plans.values() if p['recurrence'] == 'weekly'})
179 + occurrence_ids = set()
180 + occurrence_dates = set()
181 + for row in tables['local_occurrences']:
182 + _uuid(row['id'])
183 + _uuid(row['plan_id'])
184 + _require(row['plan_id'] in plans and row['id'] not in occurrence_ids)
185 + _date(row['occurrence_date'])
186 + key = (row['plan_id'], row['occurrence_date'])
187 + _require(key not in occurrence_dates)
188 + occurrence_dates.add(key)
189 + occurrence_ids.add(row['id'])
190 + _text(row['title'], 200)
191 + _require(row['kind'] in KINDS)
192 + _time(row)
193 + _integer(row['completed'], 0, 1)
194 + _integer(row['archived'], 0, 1)
195 + _reminder(row['reminder_minutes'])
196 + return {table: sorted(tables[table], key=lambda row: tuple(row[key] for key in PRIMARY_KEYS[table]))
197 + for table in COLUMNS}
198 +
199 +
200 +def _document(tables):
201 + return {'format': FORMAT, 'schemaVersion': SCHEMA_VERSION, 'syntheticOnly': True, 'tables': tables}
202 +
203 +
204 +def _canonical(document):
205 + payload = json.dumps(document, ensure_ascii=False, sort_keys=True, separators=(',', ':'),
206 + allow_nan=False).encode('utf-8')
207 + if len(payload) > MAX_PAYLOAD_BYTES:
208 + raise RecoveryError('payload_too_large')
209 + return payload
210 +
211 +
212 +def _new_database():
213 + connection = sqlite3.connect(':memory:')
214 + try:
215 + connection.execute('PRAGMA foreign_keys = ON')
216 + connection.execute(f'PRAGMA application_id = {FIXTURE_APPLICATION_ID}')
217 + connection.execute(f'PRAGMA user_version = {SCHEMA_VERSION}')
218 + for sql in DDL:
219 + connection.execute(sql)
220 + except BaseException:
221 + connection.close()
222 + raise
223 + return connection
224 +
225 +
226 +def _normalize_sql(sql):
227 + if sql is None:
228 + return None
229 + # Preserve quoted literals exactly; ignore formatting between SQL tokens.
230 + return ''.join(token if token.startswith("'") else re.sub(r'\s+', '', token).lower()
231 + for token in re.findall(r"'(?:''|[^'])*'|[^']+", sql))
232 +
233 +
234 +def _schema(connection):
235 + return {(kind, name, table, _normalize_sql(sql)) for kind, name, table, sql in
236 + connection.execute('SELECT type,name,tbl_name,sql FROM sqlite_schema')}
237 +
238 +
239 +def _validate_source_header(prefix):
240 + """Gate the first 100 bytes before reading any fixture body into memory."""
241 + if len(prefix) != 100 or prefix[:16] != b'SQLite format 3\x00':
242 + raise RecoveryError('invalid_source')
243 + if int.from_bytes(prefix[68:72], 'big') != FIXTURE_APPLICATION_ID:
244 + raise RecoveryError('synthetic_marker_required')
245 + if int.from_bytes(prefix[60:64], 'big') != SCHEMA_VERSION:
246 + raise RecoveryError('unsupported_schema')
247 + # A standalone image cannot resolve WAL state. Require rollback-journal
248 + # read/write versions rather than rewriting headers or ignoring WAL.
249 + if prefix[18:20] != b'\x01\x01':
250 + raise RecoveryError('source_not_closed')
251 +
252 +
253 +def export_fixture(path: Path) -> bytes:
254 + """Read an explicitly marked, closed fixture without changing its files."""
255 + connection = None
256 + try:
257 + path = Path(path)
258 + if any(Path(str(path) + suffix).exists() for suffix in ('-wal', '-shm', '-journal')):
259 + raise RecoveryError('source_not_closed')
260 + # The shared descriptor-based reader checks the opened file's identity and
261 + # size. SQLite only sees these bounded bytes; it never reopens the path.
262 + source = read_bounded(path, MAX_PAYLOAD_BYTES, prefix_validator=_validate_source_header)
263 + connection = sqlite3.connect(':memory:')
264 + connection.deserialize(source)
265 + connection.execute('PRAGMA query_only = ON')
266 + connection.execute('PRAGMA trusted_schema = OFF')
267 + if connection.execute('PRAGMA application_id').fetchone() != (FIXTURE_APPLICATION_ID,):
268 + raise RecoveryError('synthetic_marker_required')
269 + if connection.execute('PRAGMA user_version').fetchone() != (SCHEMA_VERSION,):
270 + raise RecoveryError('unsupported_schema')
271 + reference = _new_database()
272 + try:
273 + expected_schema = _schema(reference)
274 + finally:
275 + reference.close()
276 + actual_schema = _schema(connection)
277 + android = ('table', 'android_metadata', 'android_metadata',
278 + _normalize_sql('CREATE TABLE android_metadata (locale TEXT)'))
279 + if actual_schema not in (expected_schema, expected_schema | {android}):
280 + raise RecoveryError('unsupported_schema')
281 + if connection.execute('PRAGMA integrity_check').fetchall() != [('ok',)]:
282 + raise RecoveryError('invalid_source')
283 + if connection.execute('PRAGMA foreign_key_check').fetchall():
284 + raise RecoveryError('invalid_source')
285 + tables = {}
286 + total = 0
287 + for table, columns in COLUMNS.items():
288 + count = connection.execute(f'SELECT count(*) FROM {table}').fetchone()[0]
289 + total += count
290 + if total > MAX_ROWS:
291 + raise RecoveryError('too_many_rows')
292 + # All identifiers originate in this module's whitelist.
293 + values = connection.execute(f'SELECT {",".join(columns)} FROM {table}').fetchall()
294 + tables[table] = [dict(zip(columns, row)) for row in values]
295 + return _canonical(_document(_validate(_document(tables))))
296 + except (OSError, sqlite3.Error, ValueError, TypeError, UnicodeError, OverflowError):
297 + raise RecoveryError('invalid_source') from None
298 + finally:
299 + if connection is not None:
300 + connection.close()
301 +
302 +
303 +def _unique_object(pairs):
304 + result = {}
305 + for key, value in pairs:
306 + _require(key not in result)
307 + result[key] = value
308 + return result
309 +
310 +
311 +def _reject_constant(_value):
312 + raise RecoveryError('invalid_snapshot')
313 +
314 +
315 +def database_from_snapshot(payload: bytes) -> bytes:
316 + """Validate JSON and rebuild in memory; never execute payload-supplied SQL."""
317 + if type(payload) is not bytes or len(payload) > MAX_PAYLOAD_BYTES:
318 + raise RecoveryError('invalid_snapshot')
319 + connection = None
320 + try:
321 + document = json.loads(payload.decode('utf-8'), object_pairs_hook=_unique_object,
322 + parse_constant=_reject_constant)
323 + tables = _validate(document)
324 + connection = _new_database()
325 + for table, columns in COLUMNS.items():
326 + sql = f'INSERT INTO {table} ({",".join(columns)}) VALUES ({",".join("?" for _ in columns)})'
327 + connection.executemany(sql, [tuple(row[key] for key in columns) for row in tables[table]])
328 + connection.commit()
329 + if connection.execute('PRAGMA integrity_check').fetchall() != [('ok',)]:
330 + raise RecoveryError('invalid_snapshot')
331 + if connection.execute('PRAGMA foreign_key_check').fetchall():
332 + raise RecoveryError('invalid_snapshot')
333 + result = connection.serialize()
334 + if len(result) > MAX_PAYLOAD_BYTES:
335 + raise RecoveryError('payload_too_large')
336 + return result
337 + except (ValueError, TypeError, UnicodeError, OverflowError, RecursionError, sqlite3.Error):
338 + raise RecoveryError('invalid_snapshot') from None
339 + finally:
340 + if connection is not None:
341 + connection.close()
342 +
343 +
344 +def create_sample_database() -> bytes:
345 + """Create explicit fictional QA records, all dated in 2024, entirely in memory."""
346 + profile_id = '11111111-1111-4111-8111-111111111111'
347 + plan_ids = [f'{n:08d}-2222-4222-8222-222222222222' for n in range(1, 5)]
348 + tables = {table: [] for table in COLUMNS}
349 + tables['local_profiles'] = [dict(zip(COLUMNS['local_profiles'],
350 + (1, profile_id, 'Fictional آزمایشی', 'girl_minor', 'Fictional همراه', 'violet')))]
351 + for index, recurrence in enumerate(RECURRENCES):
352 + values = (plan_ids[index], profile_id, f'Fictional {recurrence}',
353 + KINDS[index % len(KINDS)], recurrence, '2024-01-01',
354 + None if index == 0 else '2024-02-29', 480 + index * 60,
355 + 510 + index * 60, (None, 5, 15, 30)[index], int(index == 3))
356 + tables['local_plans'].append(dict(zip(COLUMNS['local_plans'], values)))
357 + values = (f'{index + 1:08d}-3333-4333-8333-333333333333', plan_ids[index],
358 + '2024-01-01', f'Fictional edited occurrence {index + 1}',
359 + KINDS[(index + 1) % len(KINDS)], 800 + index * 20, 810 + index * 20,
360 + int(index % 2 == 1), int(index == 3), (0, None, 10, 30)[index])
361 + tables['local_occurrences'].append(dict(zip(COLUMNS['local_occurrences'], values)))
362 + tables['local_weekly_slots'] = [dict(zip(COLUMNS['local_weekly_slots'],
363 + (plan_ids[3], weekday, start, start + 45)))
364 + for weekday, start in ((1, 600), (4, 900), (7, 1000))]
365 + return database_from_snapshot(_canonical(_document(tables)))
scripts/personal_recovery_cli.py new
+178
@@ -0,0 +1,178 @@
1 +#!/usr/bin/env python3
2 +"""Fictional recovery rehearsal. Never use this QA entry point on owner data."""
3 +
4 +import argparse
5 +import getpass
6 +import hashlib
7 +import json
8 +from pathlib import Path
9 +import secrets
10 +import sqlite3
11 +import sys
12 +import warnings
13 +
14 +if __package__ in (None, ""):
15 + sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
16 +
17 +from scripts.personal_recovery.archive import open_archive, seal
18 +from scripts.personal_recovery.common import MAX_PAYLOAD_BYTES, RecoveryError
19 +from scripts.personal_recovery.files import publish_new, read_bounded
20 +from scripts.personal_recovery.snapshot import (
21 + create_sample_database,
22 + database_from_snapshot,
23 + export_fixture,
24 +)
25 +
26 +
27 +def pack_fixture(source: Path, destination: Path, passphrase: str) -> None:
28 + # export_fixture refuses an unmarked DB before reading its profile/task data.
29 + payload = export_fixture(source)
30 + publish_new(destination, seal(payload, passphrase))
31 +
32 +
33 +def restore_fixture(source: Path, destination: Path, passphrase: str) -> None:
34 + raw = read_bounded(source, MAX_PAYLOAD_BYTES + 64)
35 + payload = open_archive(raw, passphrase)
36 + database = database_from_snapshot(payload)
37 + publish_new(destination, database)
38 +
39 +
40 +def _ask_password(confirm: bool) -> str:
41 + if not sys.stdin.isatty():
42 + raise RecoveryError("interactive_terminal_required")
43 + # Refuse getpass's echoing fallback if a hidden terminal is unavailable.
44 + with warnings.catch_warnings():
45 + warnings.simplefilter("error", getpass.GetPassWarning)
46 + try:
47 + value = getpass.getpass("Synthetic QA passphrase (hidden): ")
48 + if confirm and value != getpass.getpass("Repeat passphrase (hidden): "):
49 + raise RecoveryError("passphrase_confirmation_mismatch")
50 + return value
51 + except (getpass.GetPassWarning, EOFError):
52 + raise RecoveryError("interactive_terminal_required") from None
53 +
54 +
55 +def _expect_refusal(operation, destination: Path) -> None:
56 + try:
57 + operation()
58 + except RecoveryError:
59 + if destination.exists():
60 + raise RecoveryError("demo_failed") from None
61 + return
62 + raise RecoveryError("demo_failed")
63 +
64 +
65 +def demo(directory: Path) -> dict:
66 + """Exercise real disk SQLite, encryption and reopen with process-local secret."""
67 + directory = Path(directory)
68 + if directory.is_symlink():
69 + raise RecoveryError("invalid_demo_directory")
70 + if directory.exists():
71 + if not directory.is_dir() or any(directory.iterdir()):
72 + raise RecoveryError("demo_directory_not_empty")
73 + else:
74 + directory.mkdir(mode=0o700)
75 + source = directory / "synthetic-source.sqlite"
76 + archive = directory / "synthetic-transfer.lgrf"
77 + restored = directory / "synthetic-restored.sqlite"
78 + publish_new(source, create_sample_database())
79 + original_hash = hashlib.sha256(source.read_bytes()).hexdigest()
80 + before = export_fixture(source)
81 + passphrase = secrets.token_urlsafe(32)
82 + pack_fixture(source, archive, passphrase)
83 + invalid_destination = directory / "must-not-exist.sqlite"
84 + _expect_refusal(lambda: restore_fixture(archive, invalid_destination, secrets.token_urlsafe(32)), invalid_destination)
85 + corrupted = bytearray(read_bounded(archive, MAX_PAYLOAD_BYTES + 64))
86 + corrupted[-1] ^= 1
87 + _expect_refusal(lambda: open_archive(bytes(corrupted), passphrase), invalid_destination)
88 + restore_fixture(archive, restored, passphrase)
89 + if export_fixture(restored) != before:
90 + raise RecoveryError("demo_failed")
91 + if hashlib.sha256(source.read_bytes()).hexdigest() != original_hash:
92 + raise RecoveryError("demo_failed")
93 + restored_hash = hashlib.sha256(restored.read_bytes()).hexdigest()
94 + try:
95 + restore_fixture(archive, restored, passphrase)
96 + except RecoveryError as failure:
97 + if failure.code != "destination_exists":
98 + raise RecoveryError("demo_failed") from None
99 + else:
100 + raise RecoveryError("demo_failed")
101 + if hashlib.sha256(restored.read_bytes()).hexdigest() != restored_hash:
102 + raise RecoveryError("demo_failed")
103 + with sqlite3.connect(f"{restored.resolve().as_uri()}?mode=ro", uri=True) as db:
104 + if db.execute("PRAGMA quick_check").fetchone() != ("ok",):
105 + raise RecoveryError("demo_failed")
106 + if db.execute("PRAGMA foreign_key_check").fetchall():
107 + raise RecoveryError("demo_failed")
108 + tables = ("local_profiles", "local_plans", "local_weekly_slots", "local_occurrences")
109 + counts = {table: db.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0] for table in tables}
110 + if any(count == 0 for count in counts.values()):
111 + raise RecoveryError("demo_failed")
112 + return {
113 + "schemaVersion": 1,
114 + "result": "PASS",
115 + "syntheticOnly": True,
116 + "scope": "host SQLite v1 encrypted recovery rehearsal; no device or owner data",
117 + "counts": counts,
118 + "canonicalSnapshotSha256": hashlib.sha256(before).hexdigest(),
119 + "checks": {
120 + "fullFieldRoundTripAfterCloseReopen": "PASS",
121 + "sourceBytesUnchanged": "PASS",
122 + "independentSqlIntegrityAndCounts": "PASS",
123 + "invalidCredentialRejectedBeforeOutput": "PASS",
124 + "tamperingRejected": "PASS",
125 + "repeatRestoreRefusedWithoutOverwrite": "PASS",
126 + },
127 + "limitations": {
128 + "androidSideBySide": "UNVERIFIED",
129 + "subsequentSignedAppUpgrade": "UNVERIFIED",
130 + "physicalDeviceOrOwnerData": "UNVERIFIED",
131 + "WindowsAndUsb": "UNVERIFIED",
132 + "powerLossDurability": "UNVERIFIED",
133 + "ownerSigningKey": "UNVERIFIED",
134 + },
135 + }
136 +
137 +
138 +def main(argv=None) -> int:
139 + parser = argparse.ArgumentParser(description=__doc__)
140 + subcommands = parser.add_subparsers(dest="command", required=True)
141 + for name in ("create-fixture", "pack", "restore-fixture", "demo"):
142 + command = subcommands.add_parser(name)
143 + command.add_argument("--acknowledge-synthetic-only", action="store_true")
144 + if name == "demo":
145 + command.add_argument("--directory", type=Path, required=True)
146 + else:
147 + command.add_argument("--output", type=Path, required=True)
148 + if name != "create-fixture":
149 + command.add_argument("--source", type=Path, required=True)
150 + args = parser.parse_args(argv)
151 + try:
152 + if not args.acknowledge_synthetic_only:
153 + raise RecoveryError("synthetic_acknowledgement_required")
154 + if args.command == "demo":
155 + report = demo(args.directory)
156 + else:
157 + if args.command == "create-fixture":
158 + publish_new(args.output, create_sample_database())
159 + elif args.command == "pack":
160 + pack_fixture(args.source, args.output, _ask_password(confirm=True))
161 + else:
162 + restore_fixture(args.source, args.output, _ask_password(confirm=False))
163 + report = {"status": "PASS", "syntheticOnly": True}
164 + print(json.dumps(report, ensure_ascii=True, sort_keys=True))
165 + return 0
166 + except RecoveryError as failure:
167 + print(json.dumps({"status": "REFUSED", "reason": failure.code, "syntheticOnly": True}))
168 + return 2
169 + except (OSError, sqlite3.Error):
170 + print(json.dumps({"status": "REFUSED", "reason": "file_io_error", "syntheticOnly": True}))
171 + return 2
172 + except KeyboardInterrupt:
173 + print(json.dumps({"status": "CANCELLED", "reason": "interrupted", "syntheticOnly": True}))
174 + return 130
175 +
176 +
177 +if __name__ == "__main__":
178 + raise SystemExit(main())
scripts/tests/test_recovery_archive.py new
+165
@@ -0,0 +1,165 @@
1 +"""Synthetic-only tests of the versioned, authenticated recovery envelope."""
2 +
3 +import importlib
4 +import unittest
5 +from unittest.mock import patch
6 +
7 +from cryptography.hazmat.primitives.ciphers.aead import AESGCM
8 +from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
9 +
10 +from scripts.personal_recovery.common import MAX_PAYLOAD_BYTES, RecoveryError
11 +
12 +
13 +MAGIC = b"LGRF\x01"
14 +HEADER_SIZE = 33
15 +TAG_SIZE = 16
16 +PASSWORD = "fictional recovery phrase"
17 +
18 +
19 +class RecoveryArchiveTests(unittest.TestCase):
20 + def setUp(self):
21 + try:
22 + self.archive = importlib.import_module("scripts.personal_recovery.archive")
23 + except ModuleNotFoundError:
24 + self.fail("Recovery archive implementation is missing")
25 +
26 + def assert_refused_before_kdf(self, operation, value, password, code):
27 + with patch.object(self.archive, "Scrypt") as kdf:
28 + with self.assertRaises(RecoveryError) as caught:
29 + operation(value, password)
30 + self.assertEqual(caught.exception.code, code)
31 + self.assertEqual(str(caught.exception), code)
32 + kdf.assert_not_called()
33 +
34 + def test_round_trip_arbitrary_bytes(self):
35 + payload = b"fictional-only\x00\xff\x80" * 100
36 + encrypted = self.archive.seal(payload, PASSWORD)
37 + self.assertEqual(self.archive.open_archive(encrypted, PASSWORD), payload)
38 + self.assertNotIn(payload, encrypted)
39 +
40 + def test_empty_payload_round_trip(self):
41 + encrypted = self.archive.seal(b"", PASSWORD)
42 + self.assertEqual(len(encrypted), HEADER_SIZE + TAG_SIZE)
43 + self.assertEqual(self.archive.open_archive(encrypted, PASSWORD), b"")
44 +
45 + def test_format_and_fixed_crypto_parameters_with_independent_decryption(self):
46 + payload = b"fictional independent compatibility fixture"
47 + encrypted = self.archive.seal(payload, PASSWORD)
48 + self.assertEqual(encrypted[:5], MAGIC)
49 + self.assertEqual(len(encrypted), len(payload) + HEADER_SIZE + TAG_SIZE)
50 + key = Scrypt(salt=encrypted[5:21], length=32, n=32768, r=8, p=1).derive(
51 + PASSWORD.encode("utf-8")
52 + )
53 + self.assertEqual(
54 + AESGCM(key).decrypt(encrypted[21:33], encrypted[33:], encrypted[:33]),
55 + payload,
56 + )
57 +
58 + def test_open_independently_constructed_archive(self):
59 + salt = bytes(range(16))
60 + nonce = bytes(range(12))
61 + header = MAGIC + salt + nonce
62 + key = Scrypt(salt=salt, length=32, n=32768, r=8, p=1).derive(
63 + PASSWORD.encode("utf-8")
64 + )
65 + payload = b"fictional external envelope"
66 + encrypted = header + AESGCM(key).encrypt(nonce, payload, header)
67 + self.assertEqual(self.archive.open_archive(encrypted, PASSWORD), payload)
68 +
69 + def test_every_seal_uses_new_salt_and_nonce(self):
70 + first = self.archive.seal(b"fictional", PASSWORD)
71 + second = self.archive.seal(b"fictional", PASSWORD)
72 + self.assertNotEqual(first[5:21], second[5:21])
73 + self.assertNotEqual(first[21:33], second[21:33])
74 + self.assertNotEqual(first, second)
75 +
76 + def test_wrong_password_and_tampering_share_safe_authentication_error(self):
77 + encrypted = self.archive.seal(b"fictional integrity fixture", PASSWORD)
78 + cases = [(encrypted, "another fictional password")]
79 + for index in (5, 20, 21, 32, 33, len(encrypted) - 1):
80 + changed = bytearray(encrypted)
81 + changed[index] ^= 1
82 + cases.append((bytes(changed), PASSWORD))
83 + cases.append((encrypted + b"\x00", PASSWORD))
84 + cases.append((encrypted[:-1], PASSWORD))
85 + for changed, password in cases:
86 + with self.subTest(case=len(changed), password_matches=password == PASSWORD):
87 + with self.assertRaises(RecoveryError) as caught:
88 + self.archive.open_archive(changed, password)
89 + self.assertEqual(caught.exception.code, "archive_authentication_failed")
90 + self.assertEqual(str(caught.exception), "archive_authentication_failed")
91 + self.assertIsNone(caught.exception.__cause__)
92 + self.assertTrue(caught.exception.__suppress_context__)
93 +
94 + def test_header_magic_and_version_rejected_before_kdf(self):
95 + valid_size = MAGIC + bytes(16 + 12 + TAG_SIZE)
96 + for index in range(5):
97 + changed = bytearray(valid_size)
98 + changed[index] ^= 1
99 + with self.subTest(index=index):
100 + self.assert_refused_before_kdf(
101 + self.archive.open_archive, bytes(changed), PASSWORD, "invalid_archive"
102 + )
103 +
104 + def test_truncated_archive_rejected_before_kdf(self):
105 + for size in (0, 4, 5, 20, 21, 32, 33, 48):
106 + with self.subTest(size=size):
107 + self.assert_refused_before_kdf(
108 + self.archive.open_archive, (MAGIC + bytes(44))[:size],
109 + PASSWORD, "invalid_archive"
110 + )
111 +
112 + def test_oversized_archive_rejected_before_kdf(self):
113 + encrypted = MAGIC + bytes(MAX_PAYLOAD_BYTES + HEADER_SIZE + TAG_SIZE - 4)
114 + self.assertEqual(len(encrypted), MAX_PAYLOAD_BYTES + HEADER_SIZE + TAG_SIZE + 1)
115 + self.assert_refused_before_kdf(
116 + self.archive.open_archive, encrypted, PASSWORD, "invalid_archive"
117 + )
118 +
119 + def test_oversized_payload_rejected_before_kdf(self):
120 + self.assert_refused_before_kdf(
121 + self.archive.seal, bytes(MAX_PAYLOAD_BYTES + 1), PASSWORD, "invalid_payload"
122 + )
123 +
124 + def test_exact_payload_boundary_round_trip(self):
125 + payload = b"f" * MAX_PAYLOAD_BYTES
126 + encrypted = self.archive.seal(payload, PASSWORD)
127 + self.assertEqual(len(encrypted), MAX_PAYLOAD_BYTES + HEADER_SIZE + TAG_SIZE)
128 + self.assertEqual(self.archive.open_archive(encrypted, PASSWORD), payload)
129 +
130 + def test_invalid_passphrase_rejected_before_kdf_in_both_directions(self):
131 + encrypted = MAGIC + bytes(16 + 12 + TAG_SIZE)
132 + for password in ("", "x" * 11, "x" * 1025, "\u0628" * 513, "x" * 12 + "\ud800", None, b"fictional password"):
133 + for operation, value in ((self.archive.seal, b"fixture"), (self.archive.open_archive, encrypted)):
134 + with self.subTest(operation=operation.__name__, password_type=type(password).__name__):
135 + self.assert_refused_before_kdf(operation, value, password, "invalid_passphrase")
136 +
137 + def test_minimum_character_and_maximum_utf8_passphrase_boundaries(self):
138 + for password in ("x" * 12, "x" * 1024, "\u0628" * 512):
139 + with self.subTest(characters=len(password)):
140 + encrypted = self.archive.seal(b"fictional boundary", password)
141 + self.assertEqual(self.archive.open_archive(encrypted, password), b"fictional boundary")
142 +
143 + def test_unicode_passphrase_is_used_without_normalization(self):
144 + composed = "fictional-\u00e9-phrase"
145 + decomposed = "fictional-e\u0301-phrase"
146 + encrypted = self.archive.seal("ساختگی".encode("utf-8"), composed)
147 + self.assertEqual(self.archive.open_archive(encrypted, composed), "ساختگی".encode("utf-8"))
148 + with self.assertRaises(RecoveryError) as caught:
149 + self.archive.open_archive(encrypted, decomposed)
150 + self.assertEqual(caught.exception.code, "archive_authentication_failed")
151 +
152 + def test_character_count_not_utf8_length_controls_passphrase_minimum(self):
153 + self.assert_refused_before_kdf(
154 + self.archive.seal, b"fictional", "\u0628" * 6, "invalid_passphrase"
155 + )
156 +
157 + def test_nonbytes_payloads_and_archives_are_safely_rejected_before_kdf(self):
158 + for value in (None, "fictional", bytearray(b"fictional"), memoryview(b"fictional"), 4):
159 + with self.subTest(value_type=type(value).__name__):
160 + self.assert_refused_before_kdf(self.archive.seal, value, PASSWORD, "invalid_payload")
161 + self.assert_refused_before_kdf(self.archive.open_archive, value, PASSWORD, "invalid_archive")
162 +
163 +
164 +if __name__ == "__main__":
165 + unittest.main()
scripts/tests/test_recovery_cli.py new
+121
@@ -0,0 +1,121 @@
1 +"""End-to-end host checks with fictional data and independently opened SQLite."""
2 +
3 +from contextlib import redirect_stdout
4 +import hashlib
5 +import io
6 +import json
7 +from pathlib import Path
8 +import sqlite3
9 +import tempfile
10 +import unittest
11 +from unittest.mock import patch
12 +
13 +from scripts.personal_recovery.common import RecoveryError
14 +from scripts.personal_recovery.snapshot import create_sample_database, export_fixture
15 +from scripts.personal_recovery_cli import demo, main, pack_fixture, restore_fixture
16 +
17 +
18 +class RecoveryCliTests(unittest.TestCase):
19 + def setUp(self):
20 + self.temp = tempfile.TemporaryDirectory()
21 + self.addCleanup(self.temp.cleanup)
22 + self.root = Path(self.temp.name)
23 + # Deliberately fictional test passphrase, not an owner credential.
24 + self.password = "fictional test phrase only"
25 +
26 + def fixture(self):
27 + source = self.root / "source.sqlite"
28 + source.write_bytes(create_sample_database())
29 + return source
30 +
31 + def test_real_files_close_reopen_full_snapshot_matches_without_source_changes(self):
32 + source = self.fixture()
33 + source_hash = hashlib.sha256(source.read_bytes()).hexdigest()
34 + archive = self.root / "transfer.lgrf"
35 + restored = self.root / "restored.sqlite"
36 + expected = export_fixture(source)
37 + pack_fixture(source, archive, self.password)
38 + restore_fixture(archive, restored, self.password)
39 + self.assertEqual(export_fixture(restored), expected)
40 + self.assertEqual(hashlib.sha256(source.read_bytes()).hexdigest(), source_hash)
41 + self.assertFalse(source.read_bytes()[:64] in archive.read_bytes())
42 + with sqlite3.connect(f"{restored.as_uri()}?mode=ro", uri=True) as db:
43 + self.assertEqual(db.execute("PRAGMA quick_check").fetchone(), ("ok",))
44 + self.assertEqual(db.execute("PRAGMA foreign_key_check").fetchall(), [])
45 + for table in ("local_profiles", "local_plans", "local_weekly_slots", "local_occurrences"):
46 + self.assertGreater(db.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0], 0)
47 +
48 + def test_wrong_password_tamper_and_repeat_never_modify_or_create_destination(self):
49 + source = self.fixture()
50 + archive = self.root / "transfer.lgrf"
51 + destination = self.root / "restored.sqlite"
52 + pack_fixture(source, archive, self.password)
53 + with self.assertRaises(RecoveryError):
54 + restore_fixture(archive, destination, "incorrect fictional phrase")
55 + self.assertFalse(destination.exists())
56 + raw = bytearray(archive.read_bytes())
57 + raw[-1] ^= 1
58 + corrupted = self.root / "corrupted.lgrf"
59 + corrupted.write_bytes(raw)
60 + with self.assertRaises(RecoveryError):
61 + restore_fixture(corrupted, destination, self.password)
62 + self.assertFalse(destination.exists())
63 + restore_fixture(archive, destination, self.password)
64 + previous = destination.read_bytes()
65 + with self.assertRaises(RecoveryError) as refusal:
66 + restore_fixture(archive, destination, self.password)
67 + self.assertEqual(refusal.exception.code, "destination_exists")
68 + self.assertEqual(destination.read_bytes(), previous)
69 +
70 + def test_unmarked_source_refused_without_archive(self):
71 + source = self.fixture()
72 + with sqlite3.connect(source) as db:
73 + db.execute("PRAGMA application_id=0")
74 + destination = self.root / "refused.lgrf"
75 + with self.assertRaises(RecoveryError):
76 + pack_fixture(source, destination, self.password)
77 + self.assertFalse(destination.exists())
78 +
79 + def test_missing_acknowledgement_cannot_create_any_files(self):
80 + output = io.StringIO()
81 + with redirect_stdout(output):
82 + code = main(["create-fixture", "--output", str(self.root / "blocked.sqlite")])
83 + self.assertEqual(code, 2)
84 + self.assertEqual(json.loads(output.getvalue())["reason"], "synthetic_acknowledgement_required")
85 + self.assertEqual(list(self.root.iterdir()), [])
86 +
87 + def test_noninteractive_pack_refuses_without_reading_passphrase(self):
88 + source = self.fixture()
89 + output = io.StringIO()
90 + with patch("sys.stdin.isatty", return_value=False), patch("getpass.getpass") as prompt, redirect_stdout(output):
91 + code = main(["pack", "--source", str(source), "--output", str(self.root / "blocked"), "--acknowledge-synthetic-only"])
92 + self.assertEqual(code, 2)
93 + self.assertEqual(json.loads(output.getvalue())["reason"], "interactive_terminal_required")
94 + prompt.assert_not_called()
95 + self.assertFalse((self.root / "blocked").exists())
96 +
97 + def test_failure_output_contains_only_reason_not_payload_paths_or_password(self):
98 + output = io.StringIO()
99 + with patch("scripts.personal_recovery_cli._ask_password", return_value=self.password), redirect_stdout(output):
100 + code = main(["pack", "--source", str(self.root / "missing"), "--output", str(self.root / "none"), "--acknowledge-synthetic-only"])
101 + self.assertEqual(code, 2)
102 + report = json.loads(output.getvalue())
103 + self.assertEqual(set(report), {"status", "reason", "syntheticOnly"})
104 + self.assertNotIn(str(self.root), output.getvalue())
105 + self.assertNotIn(self.password, output.getvalue())
106 +
107 + def test_demo_receipt_is_sanitized_and_records_independent_checks(self):
108 + directory = self.root / "demo"
109 + receipt = demo(directory)
110 + self.assertEqual(receipt["result"], "PASS")
111 + self.assertTrue(receipt["syntheticOnly"])
112 + self.assertTrue(all(value == "PASS" for value in receipt["checks"].values()))
113 + self.assertEqual(receipt["limitations"]["androidSideBySide"], "UNVERIFIED")
114 + self.assertNotIn("display_name", json.dumps(receipt))
115 + self.assertNotIn("password", json.dumps(receipt).lower())
116 + with self.assertRaises(RecoveryError):
117 + demo(directory)
118 +
119 +
120 +if __name__ == "__main__":
121 + unittest.main()
scripts/tests/test_recovery_files.py new
+157
@@ -0,0 +1,157 @@
1 +"""Failure-path tests for write-once synthetic QA artifacts."""
2 +
3 +import errno
4 +import os
5 +from pathlib import Path
6 +import stat
7 +import subprocess
8 +import sys
9 +import tempfile
10 +import unittest
11 +from unittest.mock import patch
12 +
13 +from scripts.personal_recovery.common import RecoveryError
14 +from scripts.personal_recovery.files import publish_new, read_bounded
15 +
16 +
17 +class RecoveryFilesTests(unittest.TestCase):
18 + def setUp(self):
19 + self.tmp = tempfile.TemporaryDirectory()
20 + self.addCleanup(self.tmp.cleanup)
21 + self.root = Path(self.tmp.name)
22 +
23 + def test_complete_file_private_and_no_temporary_residue(self):
24 + dest = self.root / "fictional.lgrf"
25 + publish_new(dest, b"synthetic ciphertext")
26 + self.assertEqual(dest.read_bytes(), b"synthetic ciphertext")
27 + self.assertEqual(sorted(p.name for p in self.root.iterdir()), [dest.name])
28 + if os.name == "posix":
29 + self.assertEqual(stat.S_IMODE(dest.stat().st_mode), 0o600)
30 +
31 + def test_existing_file_never_overwritten(self):
32 + dest = self.root / "existing"
33 + dest.write_bytes(b"keep")
34 + with self.assertRaises(RecoveryError) as failure:
35 + publish_new(dest, b"replacement")
36 + self.assertEqual(failure.exception.code, "destination_exists")
37 + self.assertEqual(dest.read_bytes(), b"keep")
38 + self.assertEqual(list(self.root.iterdir()), [dest])
39 +
40 + def test_symlink_never_replaces_or_modifies_target(self):
41 + target = self.root / "target"
42 + target.write_bytes(b"keep")
43 + dest = self.root / "link"
44 + dest.symlink_to(target)
45 + with self.assertRaises(RecoveryError):
46 + publish_new(dest, b"replacement")
47 + self.assertTrue(dest.is_symlink())
48 + self.assertEqual(target.read_bytes(), b"keep")
49 +
50 + def test_space_exhaustion_leaves_no_output(self):
51 + with patch("scripts.personal_recovery.files.os.fsync", side_effect=OSError(errno.ENOSPC, "synthetic")):
52 + with self.assertRaises(RecoveryError) as failure:
53 + publish_new(self.root / "new", b"fictional")
54 + self.assertEqual(failure.exception.code, "file_io_error")
55 + self.assertEqual(list(self.root.iterdir()), [])
56 +
57 + def test_interruption_before_publish_leaves_no_output(self):
58 + with patch("scripts.personal_recovery.files.os.fsync", side_effect=KeyboardInterrupt):
59 + with self.assertRaises(KeyboardInterrupt):
60 + publish_new(self.root / "new", b"fictional")
61 + self.assertEqual(list(self.root.iterdir()), [])
62 +
63 + def test_racing_destination_creation_is_preserved(self):
64 + dest = self.root / "new"
65 + real_link = os.link
66 +
67 + def raced(source, destination):
68 + Path(destination).write_bytes(b"other writer")
69 + return real_link(source, destination)
70 +
71 + with patch("scripts.personal_recovery.files.os.link", side_effect=raced):
72 + with self.assertRaises(RecoveryError) as failure:
73 + publish_new(dest, b"replacement")
74 + self.assertEqual(failure.exception.code, "destination_exists")
75 + self.assertEqual(dest.read_bytes(), b"other writer")
76 + self.assertEqual(list(self.root.iterdir()), [dest])
77 +
78 + def test_bounded_read_rejects_oversize_and_symlink(self):
79 + path = self.root / "input"
80 + path.write_bytes(b"12345")
81 + self.assertEqual(read_bounded(path, 5), b"12345")
82 + with self.assertRaises(RecoveryError):
83 + read_bounded(path, 4)
84 + link = self.root / "link"
85 + link.symlink_to(path)
86 + with self.assertRaises(RecoveryError):
87 + read_bounded(link, 5)
88 +
89 + @unittest.skipUnless(hasattr(os, "mkfifo"), "POSIX named-pipe test")
90 + def test_named_pipe_is_refused_without_waiting_for_writer(self):
91 + fifo = self.root / "pipe"
92 + os.mkfifo(fifo)
93 + code = ("from pathlib import Path; from scripts.personal_recovery.files import read_bounded; "
94 + "read_bounded(Path(__import__('sys').argv[1]), 10)")
95 + try:
96 + result = subprocess.run([sys.executable, "-c", code, str(fifo)], capture_output=True, timeout=2)
97 + except subprocess.TimeoutExpired:
98 + self.fail("nonregular input blocked instead of being refused")
99 + self.assertNotEqual(result.returncode, 0)
100 + self.assertIn(b"invalid_input_file", result.stderr)
101 +
102 + def test_swap_after_initial_lstat_cannot_bypass_identity_or_size_checks(self):
103 + source = self.root / "source"
104 + source.write_bytes(b"small")
105 + replacement = self.root / "replacement"
106 + replacement.write_bytes(b"oversized fictional replacement")
107 + real_open = os.open
108 +
109 + def swapped(path, flags):
110 + source.unlink()
111 + source.symlink_to(replacement)
112 + return real_open(path, flags)
113 +
114 + with patch("scripts.personal_recovery.files.os.open", side_effect=swapped):
115 + with self.assertRaises(RecoveryError):
116 + read_bounded(source, 10)
117 +
118 + def test_regular_file_swap_with_same_size_is_refused(self):
119 + source = self.root / "source"
120 + source.write_bytes(b"first")
121 + replacement = self.root / "replacement"
122 + replacement.write_bytes(b"other")
123 + real_open = os.open
124 +
125 + def swapped(path, flags):
126 + os.replace(replacement, source)
127 + return real_open(path, flags)
128 +
129 + with patch("scripts.personal_recovery.files.os.open", side_effect=swapped):
130 + with self.assertRaises(RecoveryError):
131 + read_bounded(source, 10)
132 +
133 + def test_prefix_refusal_precedes_any_body_read(self):
134 + source = self.root / "source"
135 + source.write_bytes(b"f" * 200)
136 + observed = []
137 +
138 + def reject(prefix):
139 + observed.append(prefix)
140 + raise RecoveryError("synthetic_marker_required")
141 +
142 + with self.assertRaises(RecoveryError) as failure:
143 + read_bounded(source, 300, prefix_validator=reject)
144 + self.assertEqual(failure.exception.code, "synthetic_marker_required")
145 + self.assertEqual(observed, [b"f" * 100])
146 +
147 + def test_prefix_gate_uses_unbuffered_stream_without_read_ahead(self):
148 + source = self.root / "source"
149 + source.write_bytes(b"f" * 200)
150 + real_fdopen = os.fdopen
151 + with patch("scripts.personal_recovery.files.os.fdopen", wraps=real_fdopen) as opening:
152 + read_bounded(source, 300, prefix_validator=lambda prefix: None)
153 + self.assertEqual(opening.call_args.kwargs.get("buffering"), 0)
154 +
155 +
156 +if __name__ == "__main__":
157 + unittest.main()
scripts/tests/test_recovery_snapshot.py new
+424
@@ -0,0 +1,424 @@
1 +"""Synthetic-only SQLite portability and refusal checks; never open owner data."""
2 +import copy
3 +import hashlib
4 +import importlib
5 +import importlib.util
6 +import json
7 +from pathlib import Path
8 +import re
9 +import sqlite3
10 +import tempfile
11 +import unittest
12 +from unittest import mock
13 +
14 +from scripts.personal_recovery import files
15 +from scripts.personal_recovery.common import (
16 + FIXTURE_APPLICATION_ID, MAX_PAYLOAD_BYTES, MAX_ROWS, RecoveryError,
17 +)
18 +
19 +ROOT = Path(__file__).resolve().parents[2]
20 +P = '11111111-1111-4111-8111-111111111111'
21 +A = '22222222-2222-4222-8222-222222222222'
22 +B = '33333333-3333-4333-8333-333333333333'
23 +O = '44444444-4444-4444-8444-444444444444'
24 +
25 +
26 +def fixture_connection(path, *, marked=True):
27 + """Use the actual application's DDL, independently of the new exporter."""
28 + connection = sqlite3.connect(path)
29 + source = (ROOT / 'apps/lifemate/lib/standalone/store.dart').read_text()
30 + for sql in re.findall(r"'''(CREATE TABLE .*?)'''", source, re.DOTALL):
31 + connection.execute(sql)
32 + connection.execute('CREATE INDEX local_occurrences_date ON local_occurrences(occurrence_date)')
33 + connection.execute('PRAGMA user_version = 1')
34 + if marked:
35 + connection.execute(f'PRAGMA application_id = {FIXTURE_APPLICATION_ID}')
36 + connection.execute('INSERT INTO local_profiles VALUES (1,?,?,?,?,?)',
37 + (P, 'Fictional آزمایشی', 'girl_minor', 'Fictional همراه', 'mint'))
38 + connection.execute('INSERT INTO local_plans VALUES (?,?,?,?,?,?,?,?,?,?,?)',
39 + (A, P, 'Fictional weekly', 'routine', 'weekly', '2024-01-01',
40 + '2024-02-29', 400, 500, 30, 1))
41 + connection.execute('INSERT INTO local_plans VALUES (?,?,?,?,?,?,?,?,?,?,?)',
42 + (B, P, 'Fictional one-off', 'event', 'once', '2024-02-29',
43 + None, 0, 1440, None, 0))
44 + connection.executemany('INSERT INTO local_weekly_slots VALUES (?,?,?,?)',
45 + [(A, 7, 700, 750), (A, 1, 600, 630)])
46 + connection.execute('INSERT INTO local_occurrences VALUES (?,?,?,?,?,?,?,?,?,?)',
47 + (O, A, '2024-01-01', 'Fictional edited independent title',
48 + 'task', 800, 900, 1, 1, 0))
49 + connection.commit()
50 + return connection
51 +
52 +
53 +class SnapshotTests(unittest.TestCase):
54 + def setUp(self):
55 + self.directory = tempfile.TemporaryDirectory()
56 + self.addCleanup(self.directory.cleanup)
57 + self.path = Path(self.directory.name) / 'fictional.sqlite'
58 + connection = fixture_connection(self.path)
59 + connection.close()
60 + self.assertIsNotNone(importlib.util.find_spec('scripts.personal_recovery.snapshot'),
61 + 'snapshot module is required')
62 + self.module = importlib.import_module('scripts.personal_recovery.snapshot')
63 +
64 + def document(self):
65 + return json.loads(self.module.export_fixture(self.path))
66 +
67 + def reject_document(self, document):
68 + with self.assertRaises(RecoveryError):
69 + self.module.database_from_snapshot(json.dumps(document).encode())
70 +
71 + def test_exact_roundtrip_all_fields_and_source_digest(self):
72 + before = hashlib.sha256(self.path.read_bytes()).hexdigest()
73 + payload = self.module.export_fixture(self.path)
74 + self.assertEqual(hashlib.sha256(self.path.read_bytes()).hexdigest(), before)
75 + self.assertEqual(sorted(p.name for p in self.path.parent.iterdir()), ['fictional.sqlite'])
76 + document = json.loads(payload)
77 + self.assertEqual(set(document), {'format', 'schemaVersion', 'syntheticOnly', 'tables'})
78 + self.assertEqual(document['format'], 'LifeGuideSyntheticRecovery')
79 + self.assertIs(document['syntheticOnly'], True)
80 + self.assertEqual(document['schemaVersion'], 1)
81 + self.assertEqual(document['tables']['local_occurrences'][0]['title'],
82 + 'Fictional edited independent title')
83 + self.assertEqual([s['weekday'] for s in document['tables']['local_weekly_slots']], [1, 7])
84 + self.assertEqual(payload, json.dumps(document, ensure_ascii=False, sort_keys=True,
85 + separators=(',', ':'), allow_nan=False).encode())
86 + restored = self.path.parent / 'restored.sqlite'
87 + restored.write_bytes(self.module.database_from_snapshot(payload))
88 + self.assertEqual(self.module.export_fixture(restored), payload)
89 + with sqlite3.connect(self.path) as original, sqlite3.connect(restored) as result:
90 + for table in document['tables']:
91 + self.assertEqual(sorted(original.execute(f'SELECT * FROM {table}').fetchall()),
92 + sorted(result.execute(f'SELECT * FROM {table}').fetchall()))
93 + self.assertEqual(result.execute('PRAGMA integrity_check').fetchall(), [('ok',)])
94 + self.assertEqual(result.execute('PRAGMA foreign_key_check').fetchall(), [])
95 +
96 + def test_sample_has_fictional_past_rows_for_all_recurrences_and_independent_state(self):
97 + self.path.write_bytes(self.module.create_sample_database())
98 + tables = self.document()['tables']
99 + self.assertEqual({p['recurrence'] for p in tables['local_plans']},
100 + {'once', 'daily', 'everyTwoDays', 'weekly'})
101 + self.assertEqual({p['kind'] for p in tables['local_plans']}, {'task', 'event', 'routine'})
102 + self.assertTrue(all(p['start_date'].startswith('2024-') for p in tables['local_plans']))
103 + self.assertTrue(all('Fictional' in p['title'] for p in tables['local_plans']))
104 + self.assertTrue(any(o['completed'] and o['archived'] for o in tables['local_occurrences']))
105 + self.assertTrue(any(p['archived'] for p in tables['local_plans']))
106 + plans = {p['id']: p for p in tables['local_plans']}
107 + self.assertTrue(any(o['title'] != plans[o['plan_id']]['title']
108 + for o in tables['local_occurrences']))
109 +
110 + def test_marker_checked_before_any_schema_or_content_query(self):
111 + with sqlite3.connect(self.path) as connection:
112 + connection.execute('PRAGMA application_id = 0')
113 + real_connect = sqlite3.connect
114 + queries = []
115 +
116 + def traced_connect(*args, **kwargs):
117 + connection = real_connect(*args, **kwargs)
118 + connection.set_trace_callback(queries.append)
119 + return connection
120 +
121 + with mock.patch.object(self.module.sqlite3, 'connect', side_effect=traced_connect):
122 + with self.assertRaises(RecoveryError):
123 + self.module.export_fixture(self.path)
124 + self.assertEqual(queries, [])
125 + with real_connect(self.path) as connection:
126 + connection.execute(f'PRAGMA application_id = {FIXTURE_APPLICATION_ID}')
127 + with mock.patch.object(self.module.sqlite3, 'connect', side_effect=traced_connect):
128 + self.module.export_fixture(self.path)
129 + marker = next(index for index, query in enumerate(queries) if query == 'PRAGMA application_id')
130 + first_select = next(index for index, query in enumerate(queries) if 'SELECT' in query.upper())
131 + self.assertLess(marker, first_select)
132 +
133 + def test_marker_is_safety_gate_not_authentication(self):
134 + self.assertIn('not authentication', self.module.__doc__)
135 +
136 + def test_unknown_version_refused_without_source_change(self):
137 + with sqlite3.connect(self.path) as connection:
138 + connection.execute('PRAGMA user_version = 2')
139 + before = self.path.read_bytes()
140 + with self.assertRaises(RecoveryError):
141 + self.module.export_fixture(self.path)
142 + self.assertEqual(before, self.path.read_bytes())
143 +
144 + def test_extra_sql_objects_or_modified_schema_refused(self):
145 + cases = [
146 + 'CREATE TABLE unexpected (secret TEXT)',
147 + 'CREATE VIEW unexpected AS SELECT * FROM local_profiles',
148 + 'CREATE TRIGGER unexpected AFTER INSERT ON local_plans BEGIN DELETE FROM local_profiles; END',
149 + 'CREATE INDEX unexpected ON local_profiles(display_name)',
150 + 'ALTER TABLE local_profiles ADD COLUMN unexpected TEXT',
151 + ]
152 + for sql in cases:
153 + with self.subTest(sql=sql):
154 + path = self.path.parent / 'modified.sqlite'
155 + path.write_bytes(self.path.read_bytes())
156 + with sqlite3.connect(path) as connection:
157 + connection.execute(sql)
158 + with self.assertRaises(RecoveryError):
159 + self.module.export_fixture(path)
160 +
161 + def test_android_metadata_optional_and_never_exported(self):
162 + expected = self.module.export_fixture(self.path)
163 + with sqlite3.connect(self.path) as connection:
164 + connection.execute('CREATE TABLE android_metadata (locale TEXT)')
165 + connection.execute("INSERT INTO android_metadata VALUES ('fictional_locale')")
166 + self.assertEqual(self.module.export_fixture(self.path), expected)
167 + with sqlite3.connect(self.path) as connection:
168 + connection.execute('ALTER TABLE android_metadata ADD COLUMN extra TEXT')
169 + with self.assertRaises(RecoveryError):
170 + self.module.export_fixture(self.path)
171 +
172 + def test_invalid_database_types_and_dates_refused(self):
173 + for sql in ["UPDATE local_plans SET start_date='2024-02-30'",
174 + "UPDATE local_plans SET id='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' WHERE title='Fictional weekly'",
175 + "UPDATE local_plans SET start_minute='secret invalid value'",
176 + "UPDATE local_occurrences SET plan_id='99999999-9999-4999-8999-999999999999'"]:
177 + with self.subTest(sql=sql):
178 + path = self.path.parent / 'invalid.sqlite'
179 + path.write_bytes(self.path.read_bytes())
180 + with sqlite3.connect(path) as connection:
181 + connection.execute('PRAGMA ignore_check_constraints = ON')
182 + connection.execute(sql)
183 + with self.assertRaises(RecoveryError) as error:
184 + self.module.export_fixture(path)
185 + self.assertNotIn('secret', str(error.exception))
186 +
187 + def test_nonexistent_corrupt_and_symlink_sources_refused(self):
188 + for path in [self.path.parent / 'missing', self.path.parent / 'corrupt',
189 + self.path.parent / 'symlink']:
190 + if path.name == 'corrupt':
191 + path.write_bytes(b'fictional not sqlite')
192 + if path.name == 'symlink':
193 + path.symlink_to(self.path)
194 + with self.subTest(path=path.name), self.assertRaises(RecoveryError):
195 + self.module.export_fixture(path)
196 + self.assertFalse((self.path.parent / 'missing').exists())
197 +
198 + def test_source_symlink_swap_refused_before_sqlite_content_read(self):
199 + replacement = self.path.parent / 'replacement.sqlite'
200 + saved_original = self.path.parent / 'original.sqlite'
201 + replacement.write_bytes(self.path.read_bytes())
202 + with sqlite3.connect(replacement) as connection:
203 + connection.execute("UPDATE local_profiles SET display_name='Fictional swap canary'")
204 + original_hash = hashlib.sha256(self.path.read_bytes()).hexdigest()
205 + replacement_hash = hashlib.sha256(replacement.read_bytes()).hexdigest()
206 + real_lstat = Path.lstat
207 + real_connect = sqlite3.connect
208 + queries = []
209 + swapped = False
210 +
211 + def swapping_lstat(candidate, *args, **kwargs):
212 + nonlocal swapped
213 + info = real_lstat(candidate, *args, **kwargs)
214 + if candidate == self.path and not swapped:
215 + swapped = True
216 + self.path.rename(saved_original)
217 + self.path.symlink_to(replacement)
218 + return info
219 +
220 + def traced_connect(*args, **kwargs):
221 + connection = real_connect(*args, **kwargs)
222 + connection.set_trace_callback(queries.append)
223 + return connection
224 +
225 + with mock.patch.object(Path, 'lstat', new=swapping_lstat), \
226 + mock.patch.object(self.module.sqlite3, 'connect', side_effect=traced_connect):
227 + with self.assertRaises(RecoveryError):
228 + self.module.export_fixture(self.path)
229 + self.assertTrue(swapped)
230 + self.assertFalse(any('SELECT' in query.upper() for query in queries), queries)
231 + self.assertEqual(hashlib.sha256(saved_original.read_bytes()).hexdigest(), original_hash)
232 + self.assertEqual(hashlib.sha256(replacement.read_bytes()).hexdigest(), replacement_hash)
233 +
234 + def test_unmarked_and_future_schema_headers_refused_before_body_read(self):
235 + original = self.path.read_bytes()
236 + cases = [(68, b'\x00\x00\x00\x00', 'synthetic_marker_required'),
237 + (60, b'\x00\x00\x00\x02', 'unsupported_schema')]
238 + for offset, changed, code in cases:
239 + with self.subTest(code=code):
240 + modified = original[:offset] + changed + original[offset + 4:]
241 + self.path.write_bytes(modified)
242 + before = hashlib.sha256(modified).hexdigest()
243 + real_fdopen = files.os.fdopen
244 + reads = []
245 +
246 + class ObservedStream:
247 + def __init__(self, stream):
248 + self.stream = stream
249 +
250 + def __enter__(self):
251 + return self
252 +
253 + def __exit__(self, *args):
254 + self.stream.close()
255 +
256 + def read(self, size=-1):
257 + chunk = self.stream.read(size)
258 + reads.append(len(chunk))
259 + return chunk
260 +
261 + def observed_fdopen(*args, **kwargs):
262 + return ObservedStream(real_fdopen(*args, **kwargs))
263 +
264 + with mock.patch.object(files.os, 'fdopen', side_effect=observed_fdopen), \
265 + mock.patch.object(self.module.sqlite3, 'connect') as connection:
266 + with self.assertRaises(RecoveryError) as error:
267 + self.module.export_fixture(self.path)
268 + self.assertEqual(reads, [100])
269 + self.assertEqual(error.exception.code, code)
270 + connection.assert_not_called()
271 + self.assertEqual(hashlib.sha256(self.path.read_bytes()).hexdigest(), before)
272 +
273 + def test_cold_wal_headers_refused_before_sqlite_open(self):
274 + original = self.path.read_bytes()
275 + real_connect = sqlite3.connect
276 + calls = []
277 +
278 + def recording_connect(*args, **kwargs):
279 + calls.append(args[0])
280 + return real_connect(*args, **kwargs)
281 +
282 + for versions in [b'\x02\x02', b'\x01\x02', b'\x02\x01']:
283 + with self.subTest(versions=versions):
284 + modified = original[:18] + versions + original[20:]
285 + self.path.write_bytes(modified)
286 + calls.clear()
287 + with mock.patch.object(self.module.sqlite3, 'connect', side_effect=recording_connect):
288 + with self.assertRaises(RecoveryError):
289 + self.module.export_fixture(self.path)
290 + self.assertEqual(calls, [])
291 + self.assertEqual(self.path.read_bytes(), modified)
292 +
293 + def test_active_sidecars_refused(self):
294 + for suffix in ['-wal', '-shm', '-journal']:
295 + sidecar = Path(str(self.path) + suffix)
296 + sidecar.write_bytes(b'fictional')
297 + with self.subTest(suffix=suffix), self.assertRaises(RecoveryError):
298 + self.module.export_fixture(self.path)
299 + sidecar.unlink()
300 +
301 + def test_strict_json_and_top_level_contract(self):
302 + for raw in [b'{}', b'[]', b'null', b'\xff', b'{', b'{"format":1,"format":2}',
303 + b'{"x":NaN}', b'{"x":Infinity}', b'[' * 1100]:
304 + with self.subTest(raw=raw[:30]), self.assertRaises(RecoveryError):
305 + self.module.database_from_snapshot(raw)
306 + document = self.document()
307 + for key, value in [('schemaVersion', True), ('schemaVersion', 2),
308 + ('syntheticOnly', 1), ('syntheticOnly', False),
309 + ('format', 'unknown'), ('extra', 'forbidden')]:
310 + changed = copy.deepcopy(document)
311 + changed[key] = value
312 + with self.subTest(key=key, value=value):
313 + self.reject_document(changed)
314 + raw = self.module.export_fixture(self.path).decode()
315 + raw = raw.replace('"singleton":1', '"singleton":1,"singleton":1')
316 + with self.assertRaises(RecoveryError):
317 + self.module.database_from_snapshot(raw.encode())
318 +
319 + def test_unknown_missing_tables_rows_and_columns_refused(self):
320 + document = self.document()
321 + changes = []
322 + extra = copy.deepcopy(document)
323 + extra['tables']['android_metadata'] = []
324 + changes.append(extra)
325 + missing = copy.deepcopy(document)
326 + del missing['tables']['local_plans']
327 + changes.append(missing)
328 + for value in [{}, None, ['wrong']]:
329 + changed = copy.deepcopy(document)
330 + changed['tables']['local_plans'] = value
331 + changes.append(changed)
332 + for remove in [False, True]:
333 + changed = copy.deepcopy(document)
334 + row = changed['tables']['local_plans'][0]
335 + if remove:
336 + del row['title']
337 + else:
338 + row['extra'] = 'forbidden'
339 + changes.append(changed)
340 + for changed in changes:
341 + with self.subTest(changed=changes.index(changed)):
342 + self.reject_document(changed)
343 +
344 + def test_invalid_scalar_values_refused(self):
345 + document = self.document()
346 + cases = [
347 + ('local_profiles', 'singleton', True), ('local_profiles', 'singleton', 0),
348 + ('local_profiles', 'id', 'not-a-uuid'),
349 + ('local_profiles', 'id', P.upper().replace('11111111', 'AAAAAAAA', 1)),
350 + ('local_profiles', 'category', 'child'), ('local_profiles', 'theme_key', 'unknown'),
351 + ('local_profiles', 'display_name', ' '), ('local_profiles', 'display_name', 'a' * 81),
352 + ('local_profiles', 'companion_name', 'a' * 41),
353 + ('local_profiles', 'display_name', '\x00'),
354 + ('local_plans', 'title', 'a' * 201), ('local_plans', 'title', 42),
355 + ('local_plans', 'kind', 'other'), ('local_plans', 'recurrence', 'monthly'),
356 + ('local_plans', 'start_date', '2024-02-30'), ('local_plans', 'start_date', '2024-1-01'),
357 + ('local_plans', 'start_date', '0000-01-01'),
358 + ('local_plans', 'until_date', '2023-12-31'),
359 + ('local_plans', 'start_minute', True), ('local_plans', 'start_minute', 1.0),
360 + ('local_plans', 'start_minute', '1'), ('local_plans', 'start_minute', -1),
361 + ('local_plans', 'end_minute', 1441), ('local_plans', 'end_minute', 400),
362 + ('local_plans', 'archived', 2), ('local_plans', 'reminder_minutes', 20),
363 + ('local_weekly_slots', 'weekday', 8), ('local_weekly_slots', 'weekday', False),
364 + ('local_weekly_slots', 'end_minute', 1),
365 + ('local_occurrences', 'completed', True), ('local_occurrences', 'archived', -1),
366 + ('local_occurrences', 'occurrence_date', '2023-02-29'),
367 + ('local_occurrences', 'reminder_minutes', 1),
368 + ]
369 + for table, key, value in cases:
370 + with self.subTest(table=table, key=key, value=value):
371 + changed = copy.deepcopy(document)
372 + changed['tables'][table][0][key] = value
373 + self.reject_document(changed)
374 +
375 + def test_duplicate_primary_and_unique_keys_refused(self):
376 + document = self.document()
377 + for table in document['tables']:
378 + changed = copy.deepcopy(document)
379 + changed['tables'][table].append(copy.deepcopy(changed['tables'][table][0]))
380 + with self.subTest(table=table):
381 + self.reject_document(changed)
382 + changed = copy.deepcopy(document)
383 + occurrence = copy.deepcopy(changed['tables']['local_occurrences'][0])
384 + occurrence['id'] = '55555555-5555-4555-8555-555555555555'
385 + changed['tables']['local_occurrences'].append(occurrence)
386 + self.reject_document(changed)
387 +
388 + def test_foreign_keys_and_weekly_recurrence_links_refused(self):
389 + document = self.document()
390 + for table, key in [('local_plans', 'profile_id'),
391 + ('local_occurrences', 'plan_id'), ('local_weekly_slots', 'plan_id')]:
392 + changed = copy.deepcopy(document)
393 + changed['tables'][table][0][key] = O
394 + with self.subTest(table=table):
395 + self.reject_document(changed)
396 + changed = copy.deepcopy(document)
397 + changed['tables']['local_weekly_slots'] = []
398 + self.reject_document(changed)
399 + changed = copy.deepcopy(document)
400 + changed['tables']['local_plans'][0]['recurrence'] = 'daily'
401 + self.reject_document(changed)
402 +
403 + def test_payload_and_row_limits(self):
404 + with self.assertRaises(RecoveryError):
405 + self.module.database_from_snapshot(b' ' * (MAX_PAYLOAD_BYTES + 1))
406 + changed = self.document()
407 + changed['tables']['local_occurrences'] = [changed['tables']['local_occurrences'][0]] * (MAX_ROWS + 1)
408 + self.reject_document(changed)
409 + with self.path.open('ab') as stream:
410 + stream.truncate(MAX_PAYLOAD_BYTES + 1)
411 + with self.assertRaises(RecoveryError):
412 + self.module.export_fixture(self.path)
413 +
414 + def test_empty_v1_database_roundtrips(self):
415 + with sqlite3.connect(self.path) as connection:
416 + for table in ['local_occurrences', 'local_weekly_slots', 'local_plans', 'local_profiles']:
417 + connection.execute(f'DELETE FROM {table}')
418 + payload = self.module.export_fixture(self.path)
419 + self.path.write_bytes(self.module.database_from_snapshot(payload))
420 + self.assertTrue(all(not rows for rows in self.document()['tables'].values()))
421 +
422 +
423 +if __name__ == '__main__':
424 + unittest.main()