import glob import hashlib import sqlite3 import threading import pytest import migrations from db import DatabaseManager CLIENTS_SQL = """ CREATE TABLE clients ( id INTEGER PRIMARY KEY AUTOINCREMENT, common_name TEXT UNIQUE NOT NULL, real_address TEXT, status TEXT DEFAULT 'Active', total_bytes_received INTEGER DEFAULT 0, total_bytes_sent INTEGER DEFAULT 0, last_bytes_received INTEGER DEFAULT 0, last_bytes_sent INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE usage_history ( id INTEGER PRIMARY KEY AUTOINCREMENT, client_id INTEGER, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, bytes_received INTEGER, bytes_sent INTEGER, bytes_received_rate_mbps REAL, bytes_sent_rate_mbps REAL, FOREIGN KEY (client_id) REFERENCES clients (id) ); CREATE INDEX idx_usage_ts ON usage_history(timestamp); """ STATS_SQL = "".join(f""" CREATE TABLE {t} ( timestamp TEXT NOT NULL, client_id INTEGER NOT NULL, bytes_received INTEGER DEFAULT 0, bytes_sent INTEGER DEFAULT 0, PRIMARY KEY (timestamp, client_id), FOREIGN KEY (client_id) REFERENCES clients (id) ); CREATE INDEX idx_{t}_ts ON {t}(timestamp); """ for t in ["stats_5min", "stats_15min", "stats_hourly", "stats_6h", "stats_daily"]) # Oldest schema: APP/db.py at commit c9af0a5 (no active_sessions, users, login_attempts), # plus a legacy users table without the 2FA columns (the case _ensure_column was written for; # no commit holds that table definition, it is reconstructed from the migration step) OLDEST_SQL = CLIENTS_SQL + STATS_SQL + """ CREATE TABLE users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); """ # Baseline: APP_CORE/db.py at commit 3836049 (identical to the schema today) BASELINE_SQL = CLIENTS_SQL + STATS_SQL + """ CREATE TABLE active_sessions ( client_id INTEGER, common_name TEXT, real_address TEXT, bytes_received INTEGER, bytes_sent INTEGER, connected_since TIMESTAMP, last_seen TIMESTAMP, FOREIGN KEY (client_id) REFERENCES clients (id) ); CREATE TABLE users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, totp_secret TEXT, is_2fa_enabled INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE login_attempts ( ip_address TEXT PRIMARY KEY, attempts INTEGER DEFAULT 0, last_attempt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); """ ROWS_SQL = """ INSERT INTO clients (id, common_name, real_address, total_bytes_received, total_bytes_sent) VALUES (1, 'alice', '10.0.0.1:1000', 1000, 2000); INSERT INTO clients (id, common_name, real_address, total_bytes_received, total_bytes_sent) VALUES (2, 'bob', '10.0.0.2:2000', 3000, 4000); INSERT INTO usage_history (client_id, timestamp, bytes_received, bytes_sent) VALUES (1, '2026-01-01 10:00:00', 10, 20); INSERT INTO usage_history (client_id, timestamp, bytes_received, bytes_sent) VALUES (2, '2026-01-01 10:00:10', 30, 40); INSERT INTO stats_5min (timestamp, client_id, bytes_received, bytes_sent) VALUES ('2026-01-01 10:00:00', 1, 10, 20); INSERT INTO users (id, username, password_hash) VALUES (1, 'admin', 'hash'); """ SCHEMAS = {"oldest_c9af0a5": OLDEST_SQL, "baseline_3836049": BASELINE_SQL} DATA_QUERIES = [ "SELECT * FROM clients ORDER BY id", "SELECT * FROM usage_history ORDER BY id", "SELECT * FROM stats_5min", "SELECT id, username, password_hash FROM users", ] @pytest.fixture(autouse=True) def _auto_migrate(monkeypatch): monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False) def make_db(path, schema_sql, extra_sql=ROWS_SQL): conn = sqlite3.connect(path) conn.executescript(schema_sql + extra_sql) conn.commit() conn.close() def query(path, sql): conn = sqlite3.connect(path) try: return conn.execute(sql).fetchall() finally: conn.close() def table_names(path): return {r[0] for r in query(path, "SELECT name FROM sqlite_master WHERE type='table'")} def sha(path): with open(path, "rb") as f: return hashlib.sha256(f.read()).hexdigest() @pytest.mark.parametrize("schema", SCHEMAS) def test_old_schema_is_migrated_without_data_loss(tmp_path, schema): db = str(tmp_path / "old.db") make_db(db, SCHEMAS[schema]) before = [query(db, q) for q in DATA_QUERIES] report = migrations.run(db) # Original rows intact assert [query(db, q) for q in DATA_QUERIES] == before # Missing tables and columns are there, existing rows get the defaults assert {"active_sessions", "users", "login_attempts"} <= table_names(db) assert query(db, "SELECT totp_secret, is_2fa_enabled FROM users") == [(None, 0)] # Stamped, and the backup is the untouched pre-migration copy assert query(db, "SELECT version, name FROM schema_migrations") == [(1, "baseline")] backups = glob.glob(db + ".bak-*") assert backups == [report.backup] assert [query(backups[0], q) for q in DATA_QUERIES] == before assert "schema_migrations" not in table_names(backups[0]) assert query(backups[0], "PRAGMA integrity_check") == [("ok",)] def test_second_run_is_a_noop(tmp_path): db = str(tmp_path / "old.db") make_db(db, OLDEST_SQL) migrations.run(db) first = sha(db) report = migrations.run(db) assert report.applied == [] and report.backup is None assert len(glob.glob(db + ".bak-*")) == 1 assert sha(db) == first def test_too_new_database_is_not_touched(tmp_path, monkeypatch): db = str(tmp_path / "new.db") make_db(db, BASELINE_SQL, ROWS_SQL + """ CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT); INSERT INTO schema_migrations VALUES (9999, 'from the future', '2030-01-01T00:00:00Z'); """) before = sha(db) with pytest.raises(migrations.SchemaTooNew): migrations.run(db) # The service itself refuses to start: exit code 1, no traceback monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_DB_PATH", db) with pytest.raises(SystemExit) as exc: DatabaseManager(str(tmp_path / "none.ini")).init_database() assert exc.value.code == 1 assert sha(db) == before assert glob.glob(db + ".bak-*") == [] assert len(query(db, "SELECT * FROM clients")) == 2 def test_fresh_database_gets_full_schema_without_backup(tmp_path): db = str(tmp_path / "fresh.db") report = migrations.run(db) assert report.created and report.backup is None assert glob.glob(db + ".bak-*") == [] assert {"clients", "usage_history", "active_sessions", "users", "login_attempts", "stats_5min", "stats_daily", "schema_migrations"} <= table_names(db) assert query(db, "SELECT version FROM schema_migrations") == [(1,)] def test_auto_migrate_off_refuses_while_pending(tmp_path, monkeypatch): db = str(tmp_path / "old.db") make_db(db, OLDEST_SQL) before = sha(db) monkeypatch.setenv("OVPMON_AUTO_MIGRATE", "0") with pytest.raises(migrations.MigrationPending, match="migrate.py"): migrations.startup(db) assert sha(db) == before migrations.run(db) migrations.startup(db) # up to date: allowed def test_simultaneous_start_makes_one_backup(tmp_path): db = str(tmp_path / "old.db") make_db(db, OLDEST_SQL) barrier = threading.Barrier(2) reports, errors = [], [] def start(): try: barrier.wait() reports.append(migrations.run(db)) except Exception as e: # pragma: no cover errors.append(e) threads = [threading.Thread(target=start) for _ in range(2)] for t in threads: t.start() for t in threads: t.join() assert errors == [] assert len(glob.glob(db + ".bak-*")) == 1 assert sorted(len(r.applied) for r in reports) == [0, 1] assert query(db, "SELECT version FROM schema_migrations") == [(1,)]