diff --git a/APP_PROFILER/routers/profiles.py b/APP_PROFILER/routers/profiles.py
index 2848c45..1b108cf 100644
--- a/APP_PROFILER/routers/profiles.py
+++ b/APP_PROFILER/routers/profiles.py
@@ -76,6 +76,10 @@ def create_profile(
):
if pki.is_init_running():
raise HTTPException(status_code=409, detail="PKI initialization is running")
+ try:
+ pki.require_pki_ready()
+ except pki.PkiNotReady as e:
+ raise HTTPException(status_code=409, detail=str(e))
# Check existing
existing = db.query(UserProfile).filter(UserProfile.username == profile_in.username).first()
diff --git a/APP_PROFILER/routers/server.py b/APP_PROFILER/routers/server.py
index ae1114b..bef28f7 100644
--- a/APP_PROFILER/routers/server.py
+++ b/APP_PROFILER/routers/server.py
@@ -4,7 +4,7 @@ from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from utils.auth import verify_token
-from services import generator, process, config
+from services import generator, process, config, pki
logger = logging.getLogger(__name__)
@@ -13,6 +13,7 @@ router = APIRouter(dependencies=[Depends(verify_token)])
@router.post("/server/configure")
def configure_server(db: Session = Depends(get_db)):
try:
+ pki.require_server_ready(db)
# Generate to a temporary location or standard location
# As per plan, we behave like srvconf
output_path = "/etc/openvpn/server.conf"
@@ -46,6 +47,8 @@ def configure_server(db: Session = Depends(get_db)):
return {"message": "Server configuration generated", "path": output_path}
except HTTPException:
raise
+ except pki.PkiNotReady as e:
+ raise HTTPException(status_code=409, detail=str(e))
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
diff --git a/APP_PROFILER/routers/server_process.py b/APP_PROFILER/routers/server_process.py
index e048871..27d20b0 100644
--- a/APP_PROFILER/routers/server_process.py
+++ b/APP_PROFILER/routers/server_process.py
@@ -1,6 +1,8 @@
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
-from services import process
+from services import process, pki
+from database import get_db
+from sqlalchemy.orm import Session
from utils.auth import verify_token
from typing import Optional
from fastapi import Depends
@@ -21,7 +23,7 @@ class ProcessStats(BaseModel):
uptime: Optional[str] = None
@router.post("/server/process/{action}", response_model=ProcessActionResponse)
-def manage_process(action: str):
+def manage_process(action: str, db: Session = Depends(get_db)):
"""
Control the OpenVPN server process.
Action: start, stop, restart
@@ -29,6 +31,13 @@ def manage_process(action: str):
if action not in ["start", "stop", "restart"]:
raise HTTPException(status_code=400, detail="Invalid action. Use start, stop, or restart")
+ # Stop stays allowed: it must work after Clear PKI or with a broken setup
+ if action in ("start", "restart"):
+ try:
+ pki.require_server_ready(db)
+ except pki.PkiNotReady as e:
+ raise HTTPException(status_code=409, detail=str(e))
+
result = process.control_service(action)
if result["status"] == "error":
diff --git a/APP_PROFILER/routers/system.py b/APP_PROFILER/routers/system.py
index 616fdde..0732210 100644
--- a/APP_PROFILER/routers/system.py
+++ b/APP_PROFILER/routers/system.py
@@ -6,7 +6,7 @@ from schemas import (
ConfigResponse, SystemSettings, PKISetting,
SystemSettingsUpdate, PKISettingUpdate
)
-from services import config, pki
+from services import config, pki, process
router = APIRouter(dependencies=[Depends(verify_token)])
@@ -52,5 +52,8 @@ def get_init_status(db: Session = Depends(get_db)):
def clear_system_pki(db: Session = Depends(get_db)):
if pki.is_init_running():
raise HTTPException(status_code=409, detail="PKI initialization is running")
+ # Do not pull the keys from under a running server
+ if process.get_process_stats()["status"] == "running":
+ raise HTTPException(status_code=409, detail="Stop OpenVPN first")
msg = pki.clear_pki(db)
return {"message": msg}
diff --git a/APP_PROFILER/services/pki.py b/APP_PROFILER/services/pki.py
index 0f4fdc2..561cb3d 100644
--- a/APP_PROFILER/services/pki.py
+++ b/APP_PROFILER/services/pki.py
@@ -3,7 +3,7 @@ import subprocess
import logging
import shutil
import threading
-from .config import get_pki_settings
+from .config import get_pki_settings, get_system_settings
from sqlalchemy.orm import Session
from datetime import datetime
from database import SessionLocal
@@ -144,10 +144,41 @@ def is_init_running() -> bool:
with _init_lock:
return _init_job["state"] == "running"
+class PkiNotReady(Exception):
+ """An operation needs keys that are not there (PKI absent, init running or server files missing)."""
+
+NOT_INITIALIZED_MSG = "PKI is not initialized. Initialize PKI first."
+
+def server_files_missing(db: Session) -> list:
+ """Names (relative to PKI_DIR) of the files server.conf points to that do not exist.
+ Checks the real files: a changed fqdn_server leaves the old certificate behind."""
+ fqdn = get_pki_settings(db).fqdn_server
+ files = ["ca.crt", f"issued/{fqdn}.crt", f"private/{fqdn}.key", "dh.pem", "ta.key"]
+ if get_system_settings(db).crl_verify:
+ files.append("crl.pem")
+ return [f for f in files if not os.path.isfile(os.path.join(PKI_DIR, f))]
+
+def require_pki_ready():
+ """CA operations (client certificates): initialized PKI and no init job running."""
+ if is_init_running() or not is_initialized():
+ raise PkiNotReady(NOT_INITIALIZED_MSG)
+
+def require_server_ready(db: Session):
+ """Server operations (configure, start, restart): CA plus every file server.conf references."""
+ require_pki_ready()
+ missing = server_files_missing(db)
+ if missing:
+ raise PkiNotReady(f"PKI server files are missing: {', '.join(missing)}")
+
def init_status(db: Session) -> dict:
with _init_lock:
job = dict(_init_job)
job["initialized"] = is_initialized()
+ missing = server_files_missing(db)
+ running = job["state"] == "running"
+ job["missing"] = missing
+ job["pki_ready"] = job["initialized"] and not running
+ job["server_ready"] = job["pki_ready"] and not missing
return job
def _set_step(step: str):
diff --git a/APP_PROFILER/test_pki_guard.py b/APP_PROFILER/test_pki_guard.py
new file mode 100644
index 0000000..d0719eb
--- /dev/null
+++ b/APP_PROFILER/test_pki_guard.py
@@ -0,0 +1,52 @@
+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
diff --git a/APP_UI/src/App.vue b/APP_UI/src/App.vue
index b68be8b..88b824f 100644
--- a/APP_UI/src/App.vue
+++ b/APP_UI/src/App.vue
@@ -38,9 +38,13 @@
PKI
-
+
VPN
+
+
+ VPN
+
@@ -129,6 +133,8 @@ import { useAppConfig } from './composables/useAppConfig';
import { useApi } from './composables/useApi';
import { useRoute, useRouter } from 'vue-router';
import ToastContainer from './components/ToastContainer.vue';
+import { usePkiStatus } from './composables/usePkiStatus';
+import { useToast } from './composables/useToast';
const { loadConfig, isLoaded } = useAppConfig();
const { apiClient } = useApi();
@@ -139,6 +145,8 @@ const isSidebarOpen = ref(false);
const isCompact = ref(false);
const route = useRoute();
const router = useRouter();
+const { status: pkiStatus, refresh: refreshPkiStatus } = usePkiStatus();
+const toast = useToast();
const isAuthenticated = computed(() => route.name !== 'Login');
const username = ref(localStorage.getItem('ovpmon_user') || '');
@@ -160,6 +168,12 @@ const syncUsername = async () => {
};
const onUserChanged = () => { username.value = localStorage.getItem('ovpmon_user') || ''; };
+// The locked VPN item points to the PKI page instead of the VPN page
+const onLockedVpnClick = () => {
+ toast.show('Initialize PKI first', 'info');
+ if (route.name !== 'PKIConfig') router.push('/config/pki');
+};
+
const handleLogout = () => {
localStorage.removeItem('ovpmon_token');
localStorage.removeItem('ovpmon_user');
@@ -185,13 +199,19 @@ const refreshPage = () => {
// Close sidebar on route change
watch(() => route.path, () => {
isSidebarOpen.value = false;
- if (route.name !== 'Login') syncUsername();
+ if (route.name !== 'Login') {
+ syncUsername();
+ refreshPkiStatus();
+ }
});
onMounted(async () => {
await loadConfig();
window.addEventListener('ovpmon-user-changed', onUserChanged);
- if (route.name !== 'Login') syncUsername();
+ if (route.name !== 'Login') {
+ syncUsername();
+ refreshPkiStatus();
+ }
// Init Theme
const savedTheme = localStorage.getItem('theme') || 'light';
diff --git a/APP_UI/src/assets/main.css b/APP_UI/src/assets/main.css
index 9d25b76..64c5dc4 100644
--- a/APP_UI/src/assets/main.css
+++ b/APP_UI/src/assets/main.css
@@ -253,6 +253,16 @@ body {
flex-shrink: 0;
}
+/* Section locked until the PKI is initialized */
+.nav-link-locked {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+
+.nav-link-locked:hover {
+ opacity: 0.6;
+}
+
.nav-section-header {
padding: 15px 15px 5px 15px;
font-size: 0.75rem;
diff --git a/APP_UI/src/composables/usePkiStatus.js b/APP_UI/src/composables/usePkiStatus.js
new file mode 100644
index 0000000..287e732
--- /dev/null
+++ b/APP_UI/src/composables/usePkiStatus.js
@@ -0,0 +1,28 @@
+import { reactive } from 'vue';
+import { useApi } from './useApi';
+
+// Module-level state: sidebar, router guard and views share one PKI status.
+// Optimistic defaults: nothing is locked until the first answer from GET /system/init/status.
+const status = reactive({ pki_ready: true, server_ready: true, missing: [], state: 'idle' });
+
+// Returns true when the status was updated. Safe on errors (keeps the previous values), and does
+// nothing without a session, so the Login page never calls the API.
+const refresh = async () => {
+ if (!localStorage.getItem('ovpmon_token')) return false;
+ try {
+ const { profilesApiClient } = useApi();
+ const res = await profilesApiClient.get('/system/init/status');
+ const d = res.data || {};
+ status.pki_ready = d.pki_ready !== false;
+ status.server_ready = d.server_ready !== false;
+ status.missing = d.missing || [];
+ status.state = d.state || 'idle';
+ return true;
+ } catch (e) {
+ return false;
+ }
+};
+
+export function usePkiStatus() {
+ return { status, refresh };
+}
diff --git a/APP_UI/src/router/index.js b/APP_UI/src/router/index.js
index 0f80daf..8b42ac2 100644
--- a/APP_UI/src/router/index.js
+++ b/APP_UI/src/router/index.js
@@ -1,6 +1,8 @@
import { createRouter, createWebHistory } from 'vue-router';
import Clients from '../views/Clients.vue';
import Login from '../views/Login.vue';
+import { usePkiStatus } from '../composables/usePkiStatus';
+import { useToast } from '../composables/useToast';
const routes = [
{
@@ -27,7 +29,8 @@ const routes = [
{
path: '/config/vpn',
name: 'VPNConfig',
- component: () => import('../views/VPNConfig.vue')
+ component: () => import('../views/VPNConfig.vue'),
+ meta: { requiresPki: true }
},
{
path: '/server',
@@ -52,13 +55,23 @@ const router = createRouter({
routes
});
-router.beforeEach((to, from, next) => {
+router.beforeEach(async (to, from, next) => {
const isAuthenticated = !!localStorage.getItem('ovpmon_token');
if (!to.meta.public && !isAuthenticated) {
next({ name: 'Login' });
} else if (to.name === 'Login' && isAuthenticated) {
next({ name: 'Analytics' });
+ } else if (to.meta.requiresPki) {
+ // A failed status request does not block navigation: the backend still enforces the rule
+ const { status, refresh } = usePkiStatus();
+ const ok = await refresh();
+ if (ok && !status.pki_ready) {
+ useToast().show('Initialize PKI before configuring the server', 'warning');
+ next({ name: 'PKIConfig' });
+ } else {
+ next();
+ }
} else {
next();
}
diff --git a/APP_UI/src/views/Certificates.vue b/APP_UI/src/views/Certificates.vue
index d4c684e..d44ba20 100644
--- a/APP_UI/src/views/Certificates.vue
+++ b/APP_UI/src/views/Certificates.vue
@@ -24,7 +24,8 @@
-