import os import tempfile # The DB path must be set before database.py is imported (via main) _tmp = tempfile.TemporaryDirectory() os.environ["OVPMON_PROFILER_DB_PATH"] = os.path.join(_tmp.name, "test.db") from fastapi.testclient import TestClient from main import app from database import SessionLocal from services import pki, config, process from utils.auth import verify_token app.dependency_overrides[verify_token] = lambda: {"sub": "test"} client = TestClient(app) def test_server_and_clients_need_pki(monkeypatch): pki_dir = os.path.join(_tmp.name, "pki") monkeypatch.setattr(pki, "PKI_DIR", pki_dir) # Nothing here may start OpenVPN or write to /etc/openvpn monkeypatch.setattr(pki, "build_client", lambda username, db: (_ for _ in ()).throw(RuntimeError("stub"))) monkeypatch.setattr(process, "control_service", lambda action: {"status": "success", "message": action}) # No PKI: everything that needs keys is refused assert client.post("/api/server/configure").status_code == 409 assert client.post("/api/server/process/start").status_code == 409 assert client.post("/api/profiles", json={"username": "alice"}).status_code == 409 status = client.get("/api/system/init/status").json() assert status["pki_ready"] is False and status["server_ready"] is False assert status["missing"] # Stub PKI with the names the settings ask for db = SessionLocal() try: fqdn = config.get_pki_settings(db).fqdn_server crl_verify = config.get_system_settings(db).crl_verify finally: db.close() files = ["ca.crt", "dh.pem", "ta.key", f"issued/{fqdn}.crt", f"private/{fqdn}.key"] if crl_verify: files.append("crl.pem") for name in files: path = os.path.join(pki_dir, name) os.makedirs(os.path.dirname(path), exist_ok=True) open(path, "w").close() status = client.get("/api/system/init/status").json() assert status["pki_ready"] is True and status["server_ready"] is True and status["missing"] == [] assert client.post("/api/server/process/start").status_code == 200 # Past the guard: fails later in the stubbed build (500), but not with 409 assert client.post("/api/profiles", json={"username": "alice"}).status_code != 409