Files
OpenVPN-Monitoring-Simple/APP_PROFILER/test_backup.py
T

404 lines
20 KiB
Python
Raw Normal View History

import io
import os
import sqlite3
import tarfile
import tempfile
import types
import pytest
# The DB path must be set before database.py is imported (via main)
_tmp = tempfile.TemporaryDirectory()
os.environ.setdefault("OVPMON_PROFILER_DB_PATH", os.path.join(_tmp.name, "test.db"))
from fastapi.testclient import TestClient
from main import app
import migrations
from services import pki, process
from services.backup import BackupError, crypto, destinations, engine, package, store
from utils.auth import verify_token
app.dependency_overrides[verify_token] = lambda: {"sub": "test"}
client = TestClient(app)
PASS = "correct horse battery"
class InlineThread:
"""Runs the job in the calling thread: the tests need no polling."""
def __init__(self, target, args=(), daemon=None):
self.target, self.args = target, args
def start(self):
self.target(*self.args)
@pytest.fixture
def env(tmp_path, monkeypatch):
"""A complete data layout in a temporary directory, nothing of the real system is touched."""
data = tmp_path / "data"
data.mkdir()
prof, mon = str(data / "ovpn_profiler.db"), str(data / "openvpn_monitor.db")
migrations.run(prof)
conn = sqlite3.connect(mon)
conn.executescript("CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT);"
"INSERT INTO schema_migrations VALUES (2, 'x', 'now');"
"CREATE TABLE users (name TEXT); INSERT INTO users VALUES ('admin');")
conn.commit()
conn.close()
pki_dir, client_dir = tmp_path / "easy-rsa" / "pki", tmp_path / "client-config"
(pki_dir / "private").mkdir(parents=True)
(pki_dir / "ca.crt").write_text("CA")
(pki_dir / "private" / "ca.key").write_text("SECRET")
os.chmod(pki_dir / "private" / "ca.key", 0o600)
client_dir.mkdir()
(client_dir / "alice.ovpn").write_text("client config")
monkeypatch.setenv("OVPMON_BACKUP_LOCAL_ROOT", str(tmp_path / "backups"))
monkeypatch.setattr(engine, "profiler_db_path", lambda: prof)
monkeypatch.setattr(engine, "monitor_db_path", lambda: mon)
monkeypatch.setattr(engine, "client_dir", lambda: str(client_dir))
monkeypatch.setattr(engine, "core_dir", lambda: None) # the schemas are equal: no migration needed
monkeypatch.setattr(pki, "PKI_DIR", str(pki_dir))
monkeypatch.setattr(process, "get_process_stats", lambda: {"status": "stopped"})
monkeypatch.setattr(engine, "threading", types.SimpleNamespace(Thread=InlineThread))
monkeypatch.setattr(store, "db_file", lambda: str(tmp_path / "ovpmon_backup.db"))
store.init()
return types.SimpleNamespace(root=tmp_path, prof=prof, mon=mon, pki=pki_dir, clients=client_dir)
def test_package_round_trip_and_wrong_passphrase(env, tmp_path):
work = tmp_path / "w"
work.mkdir()
path, name, manifest = engine.create_package(str(work), PASS)
assert name.endswith(".ovpbak.enc") and package.parse_package_name(name)["encrypted"]
assert crypto.is_encrypted(path) and b"SECRET" not in open(path, "rb").read()
assert manifest["schema"]["monitor"] == 2 and "pki/private/ca.key" in manifest["files"]
with pytest.raises(crypto.WrongPassphrase):
crypto.decrypt_file(path, str(tmp_path / "bad.tar.gz"), "wrong passphrase")
crypto.decrypt_file(path, str(tmp_path / "ok.tar.gz"), PASS)
out = tmp_path / "out"
package.safe_extract(str(tmp_path / "ok.tar.gz"), str(out))
assert (out / "pki" / "ca.crt").read_text() == "CA"
assert (out / "pki" / "private" / "ca.key").read_text() == "SECRET"
assert oct(os.stat(out / "pki" / "private" / "ca.key").st_mode & 0o777) == "0o600"
assert (out / "client-config" / "alice.ovpn").read_text() == "client config"
assert sqlite3.connect(out / "db" / "openvpn_monitor.db").execute("SELECT name FROM users").fetchone() == ("admin",)
assert package.integrity_ok(str(out / "db" / "ovpn_profiler.db"))
def _tar(path, members):
with tarfile.open(path, "w:gz") as tar:
for info, data in members:
tar.addfile(info, io.BytesIO(data) if data is not None else None)
def test_safe_extraction_and_newer_schema(env, tmp_path):
def reg(name, data=b"x"):
info = tarfile.TarInfo(name)
info.size = len(data)
return info, data
link = tarfile.TarInfo("pki/link")
link.type, link.linkname = tarfile.SYMTYPE, "/etc/passwd"
for i, members in enumerate([[reg("../evil")], [reg("/abs/evil")], [reg("pki/../../evil")],
[(link, None)], [reg("other/file")], [reg("db/extra.db")]]):
bad = str(tmp_path / f"bad{i}.tar.gz")
_tar(bad, members)
with pytest.raises(BackupError):
package.safe_extract(bad, str(tmp_path / f"out{i}"))
assert not (tmp_path / "evil").exists()
# A valid package from a newer release is refused before anything is touched
work = tmp_path / "w"
work.mkdir()
path, _name, _ = engine.create_package(str(work), None)
out = tmp_path / "ok"
manifest = package.safe_extract(path, str(out))
conn = sqlite3.connect(out / "db" / "ovpn_profiler.db")
conn.execute("INSERT INTO schema_migrations VALUES (999, 'future', 'now')")
conn.commit()
conn.close()
with pytest.raises(BackupError, match="newer release"):
engine._prepare_staged(str(out), manifest)
# An unknown format version is refused too
import json
manifest["format_version"] = 99
(out / "manifest.json").write_text(json.dumps(manifest))
with pytest.raises(BackupError, match="Unknown package format"):
package.verify_extracted(str(out))
class FailingDestination(destinations.Destination):
type = "stub"
label = "Stub"
def put(self, local_path, name):
raise destinations.DestinationError("disk on fire")
def list(self):
return []
def test_multi_destination_backup_rotation_and_restore(env, tmp_path, monkeypatch):
monkeypatch.setitem(destinations.DESTINATION_TYPES, "stub", FailingDestination)
good = store.save_destination(None, "local-good", "local", True, 2, {"folder": "daily"}, {})
bad = store.save_destination(None, "broken", "stub", True, 14, {}, {})
stamps = iter(f"20261007T1000{i:02d}Z" for i in range(10))
monkeypatch.setattr(package, "utc_stamp", lambda now=None: next(stamps))
for _ in range(3):
engine.start_backup(None)
job = engine.status()
assert job["state"] == "partial" # one failed, the other still got the package
by_name = {r["name"]: r for r in job["results"]}
assert by_name["local-good"]["state"] == "ok" and by_name["broken"]["state"] == "error"
assert "disk on fire" in by_name["broken"]["message"]
assert store.get_destination(bad)["last_status"] == "error"
names = sorted(p["name"] for p in engine.list_packages(good))
assert len(names) == 2 and names[0].endswith("100001Z.ovpbak") # oldest of 3 rotated away
# Restore the newest package after the live data was damaged
newest = engine.list_packages(good)[0]["name"]
env.pki.joinpath("ca.crt").write_text("DAMAGED")
(env.clients / "alice.ovpn").unlink()
(env.clients / "stray.ovpn").write_text("not in the package")
sqlite3.connect(env.mon).execute("DROP TABLE users").connection.commit()
engine.start_restore(good, newest, None)
job = engine.status()
assert job["state"] == "done", job["message"]
assert job["relogin"] is True
assert env.pki.joinpath("ca.crt").read_text() == "CA"
assert (env.clients / "alice.ovpn").read_text() == "client config" and not (env.clients / "stray.ovpn").exists()
assert sqlite3.connect(env.mon).execute("SELECT name FROM users").fetchone() == ("admin",)
assert not [p for p in os.listdir(env.pki) if p.startswith(".restore-")]
# the previous state was saved first, locally
pre = destinations.LocalDestination({"folder": "pre-restore"}, {}).list()
assert len(pre) == 1 and package.parse_package_name(pre[0]["name"])
# A package that is not in the listing is not accepted
with pytest.raises(BackupError):
engine.start_restore(good, "ovpmon-backup_x_20200101T000000Z.ovpbak", None)
def test_api_requires_jwt_masks_secrets_and_refuses_remote_without_passphrase(env):
saved = app.dependency_overrides.pop(verify_token)
try:
for method, path in [("get", "/api/backup/settings"), ("put", "/api/backup/settings"),
("get", "/api/backup/destinations"), ("post", "/api/backup/destinations"),
("put", "/api/backup/destinations/1"), ("delete", "/api/backup/destinations/1"),
("post", "/api/backup/destinations/1/test"), ("get", "/api/backup/destinations/1/packages"),
("post", "/api/backup/run"), ("post", "/api/backup/restore"),
("get", "/api/backup/status"), ("get", "/api/backup/history")]:
assert getattr(client, method)(path).status_code == 401, (method, path)
finally:
app.dependency_overrides[verify_token] = saved
s3 = {"name": "bucket", "type": "s3", "params": {"endpoint": "s3.example.com", "bucket": "my-backups"},
"secrets": {"access_key": "AKIAEXAMPLE", "secret_key": "TOPSECRETVALUE"}}
r = client.post("/api/backup/destinations", json=s3)
assert r.status_code == 201
dest = r.json()
assert "TOPSECRETVALUE" not in r.text and "AKIAEXAMPLE" not in r.text
assert dest["secrets"] == {"access_key": store.MASK, "secret_key": store.MASK}
assert "TOPSECRETVALUE" not in client.get("/api/backup/destinations").text
assert "TOPSECRETVALUE" not in open(store.db_file(), "rb").read().decode("latin-1") # encrypted at rest
# Only implemented types; updating with the mask keeps the stored secret
assert client.post("/api/backup/destinations", json={**s3, "name": "x", "type": "smb"}).status_code == 400
s3["secrets"] = {"access_key": store.MASK, "secret_key": ""}
assert client.put(f"/api/backup/destinations/{dest['id']}", json=s3).status_code == 200
assert store.get_destination(dest["id"], with_secrets=True)["secrets"]["secret_key"] == "TOPSECRETVALUE"
# Remote destination without a passphrase: no backup
r = client.post("/api/backup/run", json={})
assert r.status_code == 400 and "passphrase" in r.json()["detail"].lower()
assert client.put("/api/backup/settings", json={"passphrase": "short"}).status_code == 400
r = client.put("/api/backup/settings", json={"passphrase": PASS})
assert r.status_code == 200 and r.json()["encryption_enabled"] is True and PASS not in r.text
assert client.put("/api/backup/settings", json={"clear_passphrase": True}).status_code == 400 # remote needs it
def test_package_name_server_name_fallback_and_unique_names(env, tmp_path, monkeypatch):
import re
import socket
monkeypatch.setattr(socket, "gethostname", lambda: "3f9a1c0b2d44")
assert engine.effective_server_name() == ("3f9a1c0b2d44", "hostname")
conn = sqlite3.connect(env.prof)
conn.execute("INSERT INTO system_settings (id, public_ip) VALUES (1, 'vpn.example.com')")
conn.commit()
conn.close()
assert engine.effective_server_name() == ("vpn.example.com", "public_ip")
# The setting wins, is validated, and can be cleared again
assert client.put("/api/backup/settings", json={"server_name": "bad name!"}).status_code == 400
r = client.put("/api/backup/settings", json={"server_name": "vpn-main"}).json()
assert (r["server_name"], r["effective_server_name"], r["server_name_source"]) == ("vpn-main", "vpn-main", "setting")
assert client.put("/api/backup/settings", json={"server_name": ""}).json()["server_name_source"] == "public_ip"
store.set_server_name("vpn-main")
# Name format, manifest, and -2 / -3 when the same second is taken (nothing is overwritten)
monkeypatch.setattr(package, "utc_stamp", lambda now=None: "20261007T101500Z")
dest = store.save_destination(None, "local-daily", "local", True, 2, {"folder": "daily"}, {})
old = "ovpmon-backup_oldhost_20200101T000000Z.ovpbak" # first-pass name: listed, never rotated
destinations.LocalDestination({"folder": "daily"}, {}).put(str(env.prof), old)
for _ in range(3):
engine.start_backup(None)
assert engine.status()["state"] == "done"
packages = engine.list_packages(dest)
assert [p["name"] for p in packages] == [
"ovpmon-backup_vpn-main_20261007T101500Z-3.ovpbak",
"ovpmon-backup_vpn-main_20261007T101500Z-2.ovpbak", old] # newest first; -1 rotated away
assert packages[0]["server_name"] == "vpn-main" and packages[2]["server_name"] == "oldhost"
work = tmp_path / "w"
work.mkdir()
_path, name, manifest = engine.create_package(str(work), None)
assert name == "ovpmon-backup_vpn-main_20261007T101500Z.ovpbak"
assert manifest["server_name"] == "vpn-main" and manifest["hostname"] == "3f9a1c0b2d44"
assert re.match(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$", manifest["created_at"])
class FakeKey:
blob = b"server-host-key-A"
def asbytes(self):
return self.blob
def get_name(self):
return "ssh-ed25519"
class FakeSFTP:
files, dirs = {}, set()
def get_channel(self):
return types.SimpleNamespace(settimeout=lambda t: None)
def stat(self, path):
if path in self.dirs:
return types.SimpleNamespace(st_mode=0o40700)
raise FileNotFoundError(path)
def mkdir(self, path, mode=0o777):
self.dirs.add(path)
def put(self, local, remote, confirm=True):
self.files[remote] = open(local, "rb").read()
def putfo(self, fh, remote):
self.files[remote] = fh.read()
def posix_rename(self, a, b):
self.files[b] = self.files.pop(a)
def remove(self, path):
del self.files[path]
def listdir_attr(self, directory):
return [types.SimpleNamespace(filename=p.rsplit("/", 1)[-1], st_mode=0o100600, st_size=len(v), st_mtime=1.0)
for p, v in self.files.items() if p.rsplit("/", 1)[0] == directory]
def getfo(self, remote, out):
out.write(self.files[remote])
class FakeSSH:
connects = []
def set_missing_host_key_policy(self, policy):
self.policy = policy
def connect(self, host, **kw):
FakeSSH.connects.append((host, kw.get("password"), kw.get("pkey")))
self.policy.missing_host_key(self, host, FakeKey()) # raises unless the key is the pinned one
def open_sftp(self):
return FakeSFTP()
def close(self):
pass
def test_sftp_ftp_validation_and_host_key_pinning(env, monkeypatch):
import paramiko
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519
monkeypatch.setattr(paramiko, "SSHClient", FakeSSH)
FakeSFTP.files, FakeSFTP.dirs = {}, set()
FakeSSH.connects.clear()
sftp, ftp = destinations.SFTPDestination, destinations.FTPDestination
base = {"host": "files.example.com", "port": 22, "username": "backup", "directory": "ovpmon/daily"}
# Parameter and secret rules
for bad in ({"host": "bad host!"}, {"port": 70000}, {"username": ""}, {"directory": "../x"}, {"directory": "/etc"}):
with pytest.raises(ValueError):
sftp.validate({**base, **bad}, {"password": "pw"})
with pytest.raises(ValueError):
sftp.validate(base, {}) # neither password nor key
with pytest.raises(ValueError):
sftp.validate(base, {"password": "pw", "private_key": "x"}) # both
with pytest.raises(ValueError):
sftp.validate(base, {"private_key": "-----BEGIN OPENSSH PRIVATE KEY-----\nnot a key\n"})
key = ed25519.Ed25519PrivateKey.generate().private_bytes(
serialization.Encoding.PEM, serialization.PrivateFormat.OpenSSH, serialization.NoEncryption()).decode()
assert sftp.validate(base, {"private_key": key})[1] == {"private_key": key.strip() + "\n"}
with pytest.raises(ValueError):
sftp.validate({**base, "host_key": "SHA256:x"}, {"password": "pw"}) # a pin never comes with the form
fclean, _ = ftp.validate({"host": "ftp.example.com", "username": "u", "directory": "bk"}, {"password": "pw"})
assert (fclean["port"], fclean["tls"], fclean["verify_cert"], fclean["passive"]) == (21, True, True, True)
with pytest.raises(ValueError):
ftp.validate({"host": "ftp.example.com", "username": "u", "directory": "bk"}, {}) # no password
# Not pinned: Test shows the fingerprint, nothing else works, no connection is even opened
body = {"name": "offsite", "type": "sftp", "params": base, "secrets": {"password": "pw"}}
dest = client.post("/api/backup/destinations", json=body).json()
assert dest["secrets"] == {"password": store.MASK} and "host_key" not in dest["params"]
shown = engine.test_destination(dest["id"])
assert shown["ok"] is False and shown["needs_trust"] is True and shown["key_changed"] is False
fp = shown["fingerprint"]
assert fp == destinations._ssh_fingerprint(FakeKey())
rec = store.get_destination(dest["id"], with_secrets=True)
unpinned = destinations.build_destination("sftp", rec["params"], rec["secrets"])
n = len(FakeSSH.connects)
for call in (lambda: unpinned.put(__file__, "ovpmon-backup_x_20260101T000000Z.ovpbak"), unpinned.list,
lambda: unpinned.get("ovpmon-backup_x_20260101T000000Z.ovpbak", "/dev/null"),
lambda: unpinned.delete("ovpmon-backup_x_20260101T000000Z.ovpbak")):
with pytest.raises(destinations.DestinationError, match="not trusted"):
call()
assert len(FakeSSH.connects) == n
# Trust: only the fingerprint the administrator saw is accepted
with pytest.raises(BackupError):
engine.trust_host_key(dest["id"], "SHA256:" + "A" * 43)
pinned = engine.trust_host_key(dest["id"], fp)
assert pinned["params"]["host_key"] == fp and pinned["secrets"] == {"password": store.MASK}
assert engine.test_destination(dest["id"])["ok"] is True
rec = store.get_destination(dest["id"], with_secrets=True)
d = destinations.build_destination("sftp", rec["params"], rec["secrets"])
name = "ovpmon-backup_vpn_20261007T101500Z.ovpbak"
d.put(__file__, name)
assert f"ovpmon/daily/{name}" in FakeSFTP.files and not [f for f in FakeSFTP.files if f.endswith(".part")]
FakeSFTP.files["ovpmon/daily/notes.txt"] = b"x"
assert [o["name"] for o in d.list()] == [name] # only our package names
out = os.path.join(os.path.dirname(env.prof), "got")
d.get(name, out)
assert open(out, "rb").read() == open(__file__, "rb").read()
# Pin and the form: an edit of other fields keeps the pin, a client cannot set it, a new host drops it
edit = {**body, "params": {**base, "host_key": "SHA256:" + "B" * 43, "directory": "ovpmon/other"}, "secrets": {}}
r = client.put(f"/api/backup/destinations/{dest['id']}", json=edit).json()
assert r["params"]["host_key"] == fp and r["params"]["directory"] == "ovpmon/other"
r = client.put(f"/api/backup/destinations/{dest['id']}", json={**edit, "params": {**base, "host": "other.example.com"}}).json()
assert "host_key" not in r["params"]
client.put(f"/api/backup/destinations/{dest['id']}", json={**edit, "params": base})
engine.trust_host_key(dest["id"], fp)
# A different key from the server: connection refused, Test offers the new fingerprint (changed)
FakeKey.blob = b"server-host-key-B"
try:
with pytest.raises(destinations.DestinationError, match="host key of the server changed"):
d.list()
changed = engine.test_destination(dest["id"])
assert changed["needs_trust"] is True and changed["key_changed"] is True and changed["fingerprint"] != fp
finally:
FakeKey.blob = b"server-host-key-A"