from contextlib import closing import json from pathlib import Path import shutil import sqlite3 from types import SimpleNamespace from unittest.mock import Mock import zipfile import pytest from hf_backup import ARCHIVE_NAME, BackupError, DatasetBackup, HubDataset, read_database from space_server import build_space_app, settings class FakeDataset: def __init__(self, directory): self.repo_id = 'test/private-data' self.revision = 'revision-0' self.path = directory / ARCHIVE_NAME self.count = 0 self.fail = False self.during_upload = None def prepare(self): return self.path if self.path.exists() else None def publish(self, archive, fingerprint): if self.fail: raise ConnectionError('test-token-must-not-appear') shutil.copyfile(archive, self.path) self.count += 1 self.revision = f'revision-{self.count}' if self.during_upload: self.during_upload() self.during_upload = None @pytest.fixture def backup(tmp_path, seeded): directory = tmp_path / 'data' directory.mkdir() shutil.copyfile(seeded, directory / 'mom.sqlite3') service = DatasetBackup(directory, FakeDataset(tmp_path)) service.restore() return service def edit(service, body='An actual saved change'): with closing(sqlite3.connect(service.data_dir / 'mom.sqlite3')) as db: db.execute("INSERT OR REPLACE INTO metadata(key,value) VALUES('backup_test',?)", (body,)) db.commit() def test_only_changed_content_uploads_and_checkpoint_is_not_a_change(backup): assert backup.sync_once() assert backup.backend.count == 1 assert not backup.sync_once() with closing(sqlite3.connect(backup.data_dir / 'mom.sqlite3')) as db: db.execute('PRAGMA journal_mode=WAL') db.execute('SELECT * FROM users').fetchall() db.execute('PRAGMA wal_checkpoint(TRUNCATE)') assert not backup.sync_once() edit(backup) assert backup.sync_once() assert not backup.sync_once() assert backup.backend.count == 2 def test_failure_retries_without_leaking_exception(backup, caplog): backup.sync_once() previous = backup.last_fingerprint edit(backup) backup.backend.fail = True assert not backup.sync_once() assert backup.last_fingerprint == previous assert backup.status()['state'] == 'degraded' assert 'test-token-must-not-appear' not in caplog.text backup.backend.fail = False assert backup.sync_once() assert backup.status()['state'] == 'ok' def test_writes_during_upload_are_saved_next_interval(backup): backup.backend.during_upload = lambda: edit(backup, 'written during upload') assert backup.sync_once() assert backup.sync_once() assert backup.backend.count == 2 assert not backup.sync_once() def test_restore_preserves_passwords_entries_templates_and_key(backup, tmp_path): name = 'a' * 32 + '.xlsx' original = Path(__file__).resolve().parents[1] / 'sources' / 'MOM_Technical Report on 15-09-2026.xlsx' (backup.data_dir / 'imports').mkdir() shutil.copyfile(original, backup.data_dir / 'imports' / name) (backup.data_dir / '.secret_key').write_text('generated-key') with closing(sqlite3.connect(backup.data_dir / 'mom.sqlite3')) as db: db.execute("UPDATE users SET password_hash='preserved-hash',must_change=0 WHERE id=1") db.execute('UPDATE meetings SET source_file=? WHERE id=2', ('upload:' + name,)) db.execute("INSERT INTO metadata(key,value) VALUES('setup_complete','1')") db.commit() edit(backup) assert backup.sync_once() fresh = tmp_path / 'after-restart' app, restored = build_space_app(fresh, backup.backend) assert restored.restored with closing(read_database(fresh / 'mom.sqlite3')) as db: assert db.execute('SELECT password_hash,must_change FROM users WHERE id=1').fetchone() == ('preserved-hash', 0) assert db.execute("SELECT value FROM metadata WHERE key='backup_test'").fetchone()[0] == 'An actual saved change' assert (fresh / 'imports' / name).read_bytes() == original.read_bytes() assert (fresh / '.secret_key').read_text() == 'generated-key' assert not restored.sync_once() # restore + app initialization are not data edits response = app.test_client().get('/login', base_url='https://test.hf.space') assert response.status_code == 200 cookie = response.headers['Set-Cookie'] assert all(flag in cookie for flag in ('Secure', 'HttpOnly', 'SameSite=None', 'Partitioned')) assert 'X-Frame-Options' not in response.headers assert 'frame-ancestors https://huggingface.co' in response.headers['Content-Security-Policy'] def test_pending_local_changes_survive_restart(backup): backup.sync_once() edit(backup, 'pending local edit') restarted = DatasetBackup(backup.data_dir, backup.backend) restarted.restore() assert not restarted.restored assert restarted.sync_once() def test_conflicting_local_database_is_not_overwritten(backup, tmp_path, seeded): edit(backup, 'remote changes') backup.sync_once() other = tmp_path / 'other' other.mkdir() shutil.copyfile(seeded, other / 'mom.sqlite3') before = (other / 'mom.sqlite3').read_bytes() with pytest.raises(BackupError, match='differ'): DatasetBackup(other, backup.backend).restore() assert (other / 'mom.sqlite3').read_bytes() == before def test_missing_source_does_not_publish_incomplete_backup(backup): with closing(sqlite3.connect(backup.data_dir / 'mom.sqlite3')) as db: db.execute('UPDATE meetings SET source_file=? WHERE id=2', ('upload:' + 'a' * 32 + '.xlsx',)) db.commit() assert not backup.sync_once() assert backup.backend.count == 0 @pytest.mark.parametrize('malicious', ['../outside.txt', '/absolute.txt', 'imports/../../outside.txt']) def test_restore_rejects_unexpected_paths(backup, tmp_path, malicious): backup.sync_once() with zipfile.ZipFile(backup.backend.path, 'a') as archive: archive.writestr(malicious, 'untrusted') destination = tmp_path / 'restore' with pytest.raises(BackupError, match='unexpected'): DatasetBackup(destination, backup.backend).restore() assert not (destination / 'mom.sqlite3').exists() assert not (tmp_path / 'outside.txt').exists() def test_corruption_does_not_create_database(backup, tmp_path): backup.sync_once() with zipfile.ZipFile(backup.backend.path) as archive: contents = {name: archive.read(name) for name in archive.namelist()} contents['mom.sqlite3'] = b'corrupt' with zipfile.ZipFile(backup.backend.path, 'w') as archive: for name, content in contents.items(): archive.writestr(name, content) fresh = tmp_path / 'fresh' with pytest.raises(BackupError, match='checksum'): build_space_app(fresh, backup.backend) assert not (fresh / 'mom.sqlite3').exists() def test_network_restore_failure_never_seeds_new_database(tmp_path): backend = Mock() backend.prepare.side_effect = ConnectionError('offline') with pytest.raises(ConnectionError): build_space_app(tmp_path / 'fresh', backend) assert not (tmp_path / 'fresh' / 'mom.sqlite3').exists() def test_worker_waits_300_seconds_and_shutdown_flushes(backup): class Clock: def __init__(self): self.waits = [] def wait(self, duration): self.waits.append(duration) return len(self.waits) > 1 def set(self): pass clock = Clock() backup._stop = clock backup.start() backup._thread.join(timeout=10) assert clock.waits == [300, 300] assert backup.backend.count == 1 edit(backup) backup.stop() assert backup.backend.count == 2 def test_secret_alias_and_default_private_dataset(): assert settings({'hf_token': 'secret', 'SPACE_ID': 'kishan/mom'}) == ('secret', 'kishan/mom-data') assert settings({'HF_TOKEN': 'secret', 'HF_DATASET_REPO': 'team/data'}) == ('secret', 'team/data') with pytest.raises(BackupError, match='Secret'): settings({'SPACE_ID': 'kishan/mom'}) with pytest.raises(BackupError, match='HF_DATASET_REPO'): settings({'hf_token': 'secret'}) def test_health_is_anonymous_read_only_and_reports_database_failure(client, app, tmp_path): for path in ('/health', '/healthz', '/api/health'): response = client.get(path) assert response.status_code == 200 assert response.json == {'status': 'ok', 'database': 'ok', 'backup': {'enabled': False}} assert response.headers['Cache-Control'] == 'no-store' assert 'Set-Cookie' not in response.headers app.config['DATABASE'] = str(tmp_path / 'missing.sqlite3') response = client.get('/health') assert response.status_code == 503 assert response.json['database'] == 'unavailable' assert not Path(app.config['DATABASE']).exists() def test_public_dataset_and_other_writers_are_rejected(tmp_path): hub = HubDataset('test/data', 'test-token') hub.api = Mock() hub.api.repo_info.return_value = SimpleNamespace(private=False, sha='a', siblings=[]) with pytest.raises(BackupError, match='private'): hub.prepare() hub.api.create_commit.assert_not_called() hub.api.repo_info.return_value = SimpleNamespace(private=True, sha='b', siblings=[]) hub.revision = 'a' with pytest.raises(BackupError, match='changed elsewhere'): hub.publish(tmp_path / 'unused.zip', 'digest') hub.api.create_commit.assert_not_called() def test_upload_is_one_commit_with_expected_parent(backup): hub = HubDataset('test/data', 'test-token') hub.api = Mock() hub.api.repo_info.return_value = SimpleNamespace(private=True, sha='a', siblings=[]) hub.api.create_commit.return_value = SimpleNamespace(oid='b') hub.revision = 'a' backup.backend = hub assert backup.sync_once() arguments = hub.api.create_commit.call_args.kwargs assert arguments['repo_type'] == 'dataset' assert arguments['parent_commit'] == 'a' assert len(arguments['operations']) == 1 assert arguments['operations'][0].path_in_repo == ARCHIVE_NAME assert hub.revision == 'b' def test_commit_response_lost_reconciles_without_duplicate_upload(backup): assert backup.sync_once() hub = HubDataset('test/data', 'test-token') hub.api = Mock() hub.revision = 'old-parent' hub.uncertain_fingerprint = backup.last_fingerprint hub.api.repo_info.return_value = SimpleNamespace(private=True, sha='saved-revision') hub.api.hf_hub_download.return_value = str(backup.backend.path) hub.publish(backup.backend.path, backup.last_fingerprint) assert hub.revision == 'saved-revision' assert hub.uncertain_fingerprint is None hub.api.create_commit.assert_not_called() def test_private_dataset_creation_and_pinned_download(): from huggingface_hub.errors import RepositoryNotFoundError hub = HubDataset('test/data', 'test-token') hub.api = Mock() hub.api.repo_info.side_effect = [RepositoryNotFoundError('missing', response=SimpleNamespace(headers={}, request=None)), SimpleNamespace(private=True, sha='initial', siblings=[])] assert hub.prepare() is None hub.api.create_repo.assert_called_once_with('test/data', repo_type='dataset', private=True, exist_ok=True) hub.api.auth_check.assert_called_once_with('test/data', repo_type='dataset', write=True) hub.api.repo_info.side_effect = None hub.api.repo_info.return_value = SimpleNamespace(private=True, sha='new', siblings=[SimpleNamespace(rfilename=ARCHIVE_NAME)]) hub.api.hf_hub_download.return_value = 'downloaded.zip' assert hub.prepare() == Path('downloaded.zip') assert hub.api.hf_hub_download.call_args.kwargs['revision'] == 'new' def test_snapshot_includes_committed_wal_but_excludes_uncommitted_edits(backup, tmp_path): with closing(sqlite3.connect(backup.data_dir / 'mom.sqlite3')) as db: db.execute('PRAGMA journal_mode=WAL') db.execute("INSERT INTO metadata VALUES('wal_test','committed')") db.commit() db.execute("UPDATE metadata SET value='not committed' WHERE key='wal_test'") assert backup.sync_once() restored = DatasetBackup(tmp_path / 'wal-restore', backup.backend) restored.restore() with closing(read_database(restored.data_dir / 'mom.sqlite3')) as restored_db: assert restored_db.execute("SELECT value FROM metadata WHERE key='wal_test'").fetchone()[0] == 'committed' db.rollback() def test_health_surfaces_backup_failure_without_personal_data(client, app, backup): backup.error = 'backup_failed' app.extensions['dataset_backup'] = backup result = client.get('/health') assert result.status_code == 200 assert result.json['backup']['state'] == 'degraded' assert result.json['backup']['error'] == 'backup_failed' assert backup.backend.repo_id not in result.text