Files
OpenVPN-Monitoring-Simple/APP_PROFILER/test_migrations.py
T
ayurishchevandClaude Sonnet 5.5 e556d6d4b9 Database migrations with backup, integrity checks and downgrade protection
- Profiler and monitoring: schema_migrations table, additive ordered
  migrations, single write lock, integrity check, consistent backup via
  the SQLite backup API (newest 5 kept), row-count verification before
  commit, refusal to start on a database newer than the code.
- Profiler baseline migration is generated from the models and adds every
  missing column (replaces ensure_columns and the manual add_*.py scripts).
- migrate.py in each component (--check exit 0/2/1, --db); services migrate
  at start, OVPMON_AUTO_MIGRATE=0 only checks.
- Tests: test_migrations.py per component; verified on databases created by
  the code of commit 3836049 and on the live stand.
- Docs: Database_Migrations reference, change summary, deployment
  scenarios plan, README, Index.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-05 08:37:38 +03:00

200 lines
7.9 KiB
Python

import glob
import hashlib
import os
import sqlite3
import tempfile
import pytest
# The DB path must be set before database.py is imported (the migration reads the models)
_tmp = tempfile.TemporaryDirectory()
os.environ["OVPMON_PROFILER_DB_PATH"] = os.path.join(_tmp.name, "test.db")
import migrations
PKI_SQL = """
CREATE TABLE pki_settings (
id INTEGER NOT NULL, fqdn_ca VARCHAR, fqdn_server VARCHAR, easyrsa_dn VARCHAR,
easyrsa_req_country VARCHAR, easyrsa_req_province VARCHAR, easyrsa_req_city VARCHAR,
easyrsa_req_org VARCHAR, easyrsa_req_email VARCHAR, easyrsa_req_ou VARCHAR,
easyrsa_key_size INTEGER, easyrsa_ca_expire INTEGER, easyrsa_cert_expire INTEGER,
easyrsa_cert_renew INTEGER, easyrsa_crl_days INTEGER, easyrsa_batch BOOLEAN,
PRIMARY KEY (id)
);
CREATE INDEX ix_pki_settings_id ON pki_settings (id);
"""
SYSTEM_COLUMNS = """
id INTEGER NOT NULL, protocol VARCHAR, port INTEGER, vpn_network VARCHAR,
vpn_netmask VARCHAR, tunnel_type VARCHAR, split_routes JSON, duplicate_cn BOOLEAN,
crl_verify BOOLEAN, client_to_client BOOLEAN, user_defined_dns BOOLEAN, dns_servers JSON,
user_defined_cdscripts BOOLEAN, connect_script VARCHAR, disconnect_script VARCHAR,
management_interface BOOLEAN, management_interface_address VARCHAR, management_port INTEGER
"""
# Oldest schema: reconstructed from what the standalone scripts (add_columns.py,
# scripts/add_*.py) had to add later. Git history has no older models.py than fcb8f6b.
ANCIENT_SQL = PKI_SQL + f"""
CREATE TABLE system_settings ({SYSTEM_COLUMNS}, PRIMARY KEY (id));
CREATE INDEX ix_system_settings_id ON system_settings (id);
CREATE TABLE user_profiles (
id INTEGER NOT NULL, username VARCHAR, status VARCHAR, created_at DATETIME,
revoked_at DATETIME, file_path VARCHAR, PRIMARY KEY (id)
);
CREATE UNIQUE INDEX ix_user_profiles_username ON user_profiles (username);
CREATE INDEX ix_user_profiles_id ON user_profiles (id);
"""
# Baseline: models.py at commit 3836049 (everything except user_profiles.note)
BASELINE_SQL = PKI_SQL + f"""
CREATE TABLE system_settings (
{SYSTEM_COLUMNS}, public_ip VARCHAR, tun_mtu INTEGER, mssfix INTEGER, PRIMARY KEY (id)
);
CREATE INDEX ix_system_settings_id ON system_settings (id);
CREATE TABLE user_profiles (
id INTEGER NOT NULL, username VARCHAR, status VARCHAR, created_at DATETIME,
revoked_at DATETIME, expiration_date DATETIME, is_revoked BOOLEAN, is_expired BOOLEAN,
file_path VARCHAR, PRIMARY KEY (id)
);
CREATE UNIQUE INDEX ix_user_profiles_username ON user_profiles (username);
CREATE INDEX ix_user_profiles_id ON user_profiles (id);
"""
ROWS_SQL = """
INSERT INTO pki_settings (id, fqdn_ca, easyrsa_key_size) VALUES (1, 'my-ca', 4096);
INSERT INTO system_settings (id, protocol, port, tunnel_type) VALUES (1, 'tcp', 443, 'SPLIT');
INSERT INTO user_profiles (id, username, status, created_at, file_path)
VALUES (1, 'alice', 'active', '2026-01-01 10:00:00', '/p/alice.ovpn');
INSERT INTO user_profiles (id, username, status, created_at, file_path)
VALUES (2, 'bob', 'revoked', '2026-01-02 10:00:00', '/p/bob.ovpn');
"""
SCHEMAS = {"ancient": ANCIENT_SQL, "baseline_3836049": BASELINE_SQL}
@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 columns(path, table):
return [r[1] for r in query(path, f"PRAGMA table_info({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])
users_before = query(db, "SELECT id, username, status, created_at, file_path FROM user_profiles")
report = migrations.run(db)
# Original rows intact
assert query(db, "SELECT id, username, status, created_at, file_path FROM user_profiles") == users_before
assert query(db, "SELECT fqdn_ca, easyrsa_key_size FROM pki_settings") == [("my-ca", 4096)]
assert query(db, "SELECT protocol, port, tunnel_type FROM system_settings") == [("tcp", 443, "SPLIT")]
# New columns exist; existing rows get the defaults
assert {"note", "is_revoked", "is_expired", "expiration_date"} <= set(columns(db, "user_profiles"))
assert {"public_ip", "tun_mtu", "mssfix"} <= set(columns(db, "system_settings"))
# Columns added now get the default; columns that already existed keep their values
flags = (0, 0) if schema == "ancient" else (None, None)
assert query(db, "SELECT is_revoked, is_expired, expiration_date, note FROM user_profiles") == [
flags + (None, None), flags + (None, None)]
assert query(db, "SELECT public_ip, tun_mtu, mssfix FROM system_settings") == [(None, None, None)]
# 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], "SELECT id, username, status, created_at, file_path FROM user_profiles") == users_before
assert "note" not in columns(backups[0], "user_profiles")
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, BASELINE_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):
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)
with pytest.raises(migrations.SchemaTooNew):
migrations.startup(db)
assert sha(db) == before
assert glob.glob(db + ".bak-*") == []
assert len(query(db, "SELECT * FROM user_profiles")) == 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 {"note", "is_revoked"} <= set(columns(db, "user_profiles"))
assert {"public_ip", "mssfix"} <= set(columns(db, "system_settings"))
assert "ix_user_profiles_username" in [r[1] for r in query(db, "PRAGMA index_list(user_profiles)")]
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, BASELINE_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_default_clause_from_model_defaults():
import models
t = models.SystemSettings.__table__.c
assert migrations._default_clause(t.split_routes) == " DEFAULT '[]'"
assert migrations._default_clause(t.duplicate_cn) == " DEFAULT 0"
assert migrations._default_clause(t.port) == " DEFAULT 1194"
assert migrations._default_clause(t.protocol) == " DEFAULT 'udp'"
assert migrations._default_clause(t.tun_mtu) == ""
assert migrations._default_clause(models.UserProfile.__table__.c.created_at) == ""