Guard server setup behind an initialized PKI

- Profiler: server_files_missing/require_* helpers; 409 for
  /server/configure, start/restart and POST /profiles when the PKI is
  not initialized or server files (honouring fqdn_server) are missing;
  stop stays allowed; DELETE /system/pki returns 409 while OpenVPN runs;
  GET /system/init/status adds pki_ready, server_ready, missing.
- UI: shared usePkiStatus; VPN menu item locked until the PKI is ready,
  route guard for /config/vpn, Start/Restart and New Client disabled
  with hints, lock notice on the VPN page.
- Test: one pytest (test_pki_guard.py).
- Docs: plan and summary in DOCS/Changes, API reference, README, Index.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ayurishchevandClaude Sonnet 5.5 committed 2026-10-04 21:52:40 +03:00
1 parent dcc3d7f2d5
commit 56dae90ff5
19 files changed
+342 -22

No files matched your search

+4
View File
@@ -76,6 +76,10 @@ def create_profile(
): ):
if pki.is_init_running(): if pki.is_init_running():
raise HTTPException(status_code=409, detail="PKI initialization is 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 # Check existing
existing = db.query(UserProfile).filter(UserProfile.username == profile_in.username).first() existing = db.query(UserProfile).filter(UserProfile.username == profile_in.username).first()
+4 -1
View File
@@ -4,7 +4,7 @@ from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from database import get_db from database import get_db
from utils.auth import verify_token from utils.auth import verify_token
from services import generator, process, config from services import generator, process, config, pki
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -13,6 +13,7 @@ router = APIRouter(dependencies=[Depends(verify_token)])
@router.post("/server/configure") @router.post("/server/configure")
def configure_server(db: Session = Depends(get_db)): def configure_server(db: Session = Depends(get_db)):
try: try:
pki.require_server_ready(db)
# Generate to a temporary location or standard location # Generate to a temporary location or standard location
# As per plan, we behave like srvconf # As per plan, we behave like srvconf
output_path = "/etc/openvpn/server.conf" 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} return {"message": "Server configuration generated", "path": output_path}
except HTTPException: except HTTPException:
raise raise
except pki.PkiNotReady as e:
raise HTTPException(status_code=409, detail=str(e))
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) raise HTTPException(status_code=400, detail=str(e))
except Exception as e: except Exception as e:
+11 -2
View File
@@ -1,6 +1,8 @@
from fastapi import APIRouter, HTTPException from fastapi import APIRouter, HTTPException
from pydantic import BaseModel 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 utils.auth import verify_token
from typing import Optional from typing import Optional
from fastapi import Depends from fastapi import Depends
@@ -21,7 +23,7 @@ class ProcessStats(BaseModel):
uptime: Optional[str] = None uptime: Optional[str] = None
@router.post("/server/process/{action}", response_model=ProcessActionResponse) @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. Control the OpenVPN server process.
Action: start, stop, restart Action: start, stop, restart
@@ -29,6 +31,13 @@ def manage_process(action: str):
if action not in ["start", "stop", "restart"]: if action not in ["start", "stop", "restart"]:
raise HTTPException(status_code=400, detail="Invalid action. Use start, stop, or 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) result = process.control_service(action)
if result["status"] == "error": if result["status"] == "error":
+4 -1
View File
@@ -6,7 +6,7 @@ from schemas import (
ConfigResponse, SystemSettings, PKISetting, ConfigResponse, SystemSettings, PKISetting,
SystemSettingsUpdate, PKISettingUpdate SystemSettingsUpdate, PKISettingUpdate
) )
from services import config, pki from services import config, pki, process
router = APIRouter(dependencies=[Depends(verify_token)]) 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)): def clear_system_pki(db: Session = Depends(get_db)):
if pki.is_init_running(): if pki.is_init_running():
raise HTTPException(status_code=409, detail="PKI initialization is 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) msg = pki.clear_pki(db)
return {"message": msg} return {"message": msg}
+32 -1
View File
@@ -3,7 +3,7 @@ import subprocess
import logging import logging
import shutil import shutil
import threading import threading
from .config import get_pki_settings from .config import get_pki_settings, get_system_settings
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from datetime import datetime from datetime import datetime
from database import SessionLocal from database import SessionLocal
@@ -144,10 +144,41 @@ def is_init_running() -> bool:
with _init_lock: with _init_lock:
return _init_job["state"] == "running" 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: def init_status(db: Session) -> dict:
with _init_lock: with _init_lock:
job = dict(_init_job) job = dict(_init_job)
job["initialized"] = is_initialized() 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 return job
def _set_step(step: str): def _set_step(step: str):
+52
View File
@@ -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
+23 -3
View File
@@ -38,9 +38,13 @@
<router-link to="/config/pki" class="nav-link" active-class="active" title="PKI"> <router-link to="/config/pki" class="nav-link" active-class="active" title="PKI">
<i class="fas fa-fingerprint"></i> <span>PKI</span> <i class="fas fa-fingerprint"></i> <span>PKI</span>
</router-link> </router-link>
<router-link to="/config/vpn" class="nav-link" active-class="active" title="VPN"> <router-link v-if="pkiStatus.pki_ready" to="/config/vpn" class="nav-link" active-class="active" title="VPN">
<i class="fas fa-server"></i> <span>VPN</span> <i class="fas fa-server"></i> <span>VPN</span>
</router-link> </router-link>
<!-- Locked until the PKI is initialized: stays visible so the reason is clear -->
<a v-else href="/config/pki" class="nav-link nav-link-locked" title="Initialize PKI first" @click.prevent="onLockedVpnClick">
<i class="fas fa-lock"></i> <span>VPN</span>
</a>
<!-- SECTION: MANAGEMENT --> <!-- SECTION: MANAGEMENT -->
<div class="nav-section-header mt-3">MANAGEMENT</div> <div class="nav-section-header mt-3">MANAGEMENT</div>
@@ -129,6 +133,8 @@ import { useAppConfig } from './composables/useAppConfig';
import { useApi } from './composables/useApi'; import { useApi } from './composables/useApi';
import { useRoute, useRouter } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
import ToastContainer from './components/ToastContainer.vue'; import ToastContainer from './components/ToastContainer.vue';
import { usePkiStatus } from './composables/usePkiStatus';
import { useToast } from './composables/useToast';
const { loadConfig, isLoaded } = useAppConfig(); const { loadConfig, isLoaded } = useAppConfig();
const { apiClient } = useApi(); const { apiClient } = useApi();
@@ -139,6 +145,8 @@ const isSidebarOpen = ref(false);
const isCompact = ref(false); const isCompact = ref(false);
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
const { status: pkiStatus, refresh: refreshPkiStatus } = usePkiStatus();
const toast = useToast();
const isAuthenticated = computed(() => route.name !== 'Login'); const isAuthenticated = computed(() => route.name !== 'Login');
const username = ref(localStorage.getItem('ovpmon_user') || ''); const username = ref(localStorage.getItem('ovpmon_user') || '');
@@ -160,6 +168,12 @@ const syncUsername = async () => {
}; };
const onUserChanged = () => { username.value = localStorage.getItem('ovpmon_user') || ''; }; 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 = () => { const handleLogout = () => {
localStorage.removeItem('ovpmon_token'); localStorage.removeItem('ovpmon_token');
localStorage.removeItem('ovpmon_user'); localStorage.removeItem('ovpmon_user');
@@ -185,13 +199,19 @@ const refreshPage = () => {
// Close sidebar on route change // Close sidebar on route change
watch(() => route.path, () => { watch(() => route.path, () => {
isSidebarOpen.value = false; isSidebarOpen.value = false;
if (route.name !== 'Login') syncUsername(); if (route.name !== 'Login') {
syncUsername();
refreshPkiStatus();
}
}); });
onMounted(async () => { onMounted(async () => {
await loadConfig(); await loadConfig();
window.addEventListener('ovpmon-user-changed', onUserChanged); window.addEventListener('ovpmon-user-changed', onUserChanged);
if (route.name !== 'Login') syncUsername(); if (route.name !== 'Login') {
syncUsername();
refreshPkiStatus();
}
// Init Theme // Init Theme
const savedTheme = localStorage.getItem('theme') || 'light'; const savedTheme = localStorage.getItem('theme') || 'light';
+10
View File
@@ -253,6 +253,16 @@ body {
flex-shrink: 0; 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 { .nav-section-header {
padding: 15px 15px 5px 15px; padding: 15px 15px 5px 15px;
font-size: 0.75rem; font-size: 0.75rem;
+28
View File
@@ -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 };
}
+15 -2
View File
@@ -1,6 +1,8 @@
import { createRouter, createWebHistory } from 'vue-router'; import { createRouter, createWebHistory } from 'vue-router';
import Clients from '../views/Clients.vue'; import Clients from '../views/Clients.vue';
import Login from '../views/Login.vue'; import Login from '../views/Login.vue';
import { usePkiStatus } from '../composables/usePkiStatus';
import { useToast } from '../composables/useToast';
const routes = [ const routes = [
{ {
@@ -27,7 +29,8 @@ const routes = [
{ {
path: '/config/vpn', path: '/config/vpn',
name: 'VPNConfig', name: 'VPNConfig',
component: () => import('../views/VPNConfig.vue') component: () => import('../views/VPNConfig.vue'),
meta: { requiresPki: true }
}, },
{ {
path: '/server', path: '/server',
@@ -52,13 +55,23 @@ const router = createRouter({
routes routes
}); });
router.beforeEach((to, from, next) => { router.beforeEach(async (to, from, next) => {
const isAuthenticated = !!localStorage.getItem('ovpmon_token'); const isAuthenticated = !!localStorage.getItem('ovpmon_token');
if (!to.meta.public && !isAuthenticated) { if (!to.meta.public && !isAuthenticated) {
next({ name: 'Login' }); next({ name: 'Login' });
} else if (to.name === 'Login' && isAuthenticated) { } else if (to.name === 'Login' && isAuthenticated) {
next({ name: 'Analytics' }); 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 { } else {
next(); next();
} }
+5 -1
View File
@@ -24,7 +24,8 @@
<span class="input-group-text"><i class="fas fa-search"></i></span> <span class="input-group-text"><i class="fas fa-search"></i></span>
<input type="text" class="form-control" placeholder="Search by client name..." v-model="searchQuery"> <input type="text" class="form-control" placeholder="Search by client name..." v-model="searchQuery">
</div> </div>
<button class="btn-action btn-action-save btn-sm" @click="showNewClientModal"> <button class="btn-action btn-action-save btn-sm" @click="showNewClientModal"
:disabled="!pkiStatus.pki_ready" :title="pkiStatus.pki_ready ? '' : 'Initialize PKI first'">
<i class="fas fa-plus me-1"></i> New Client <i class="fas fa-plus me-1"></i> New Client
</button> </button>
</div> </div>
@@ -157,9 +158,11 @@ import ConfirmModal from '../components/ConfirmModal.vue';
import ProfileDetailsModal from '../components/ProfileDetailsModal.vue'; import ProfileDetailsModal from '../components/ProfileDetailsModal.vue';
import vNoteTooltip from '../directives/noteTooltip'; import vNoteTooltip from '../directives/noteTooltip';
import { useToast } from '../composables/useToast'; import { useToast } from '../composables/useToast';
import { usePkiStatus } from '../composables/usePkiStatus';
const { profilesApiClient } = useApi(); const { profilesApiClient } = useApi();
const toast = useToast(); const toast = useToast();
const { status: pkiStatus, refresh: refreshPkiStatus } = usePkiStatus();
const loading = ref(true); const loading = ref(true);
const allProfiles = ref([]); const allProfiles = ref([]);
@@ -339,6 +342,7 @@ const confirmRevoke = async (cert) => {
}; };
onMounted(() => { onMounted(() => {
refreshPkiStatus();
loadCerts(); loadCerts();
}); });
</script> </script>
+6 -2
View File
@@ -173,9 +173,11 @@ import { ref, computed, onMounted, onUnmounted, reactive } from 'vue';
import { useApi } from '../composables/useApi'; import { useApi } from '../composables/useApi';
import { useToast } from '../composables/useToast'; import { useToast } from '../composables/useToast';
import { usePkiStatus } from '../composables/usePkiStatus';
const { profilesApiClient } = useApi(); const { profilesApiClient } = useApi();
const toast = useToast(); const toast = useToast();
const { refresh: refreshPkiStatus } = usePkiStatus();
// State // State
const form = reactive({ const form = reactive({
@@ -265,6 +267,7 @@ const loadStatus = async (initial = false) => {
return; return;
} }
stopPolling(); stopPolling();
if (wasRunning) refreshPkiStatus(); // unlock the sidebar without a reload
// Report the result once: a job seen running on this page, or a failure found on page load // Report the result once: a job seen running on this page, or a failure found on page load
if (wasRunning && initStatus.state === 'done') { if (wasRunning && initStatus.state === 'done') {
showMessage('PKI initialized successfully!', 'success'); showMessage('PKI initialized successfully!', 'success');
@@ -301,7 +304,7 @@ const handleInit = async () => {
// Already running (second tab) or already initialized: attach to the server state // Already running (second tab) or already initialized: attach to the server state
await loadStatus(); await loadStatus();
} else { } else {
showMessage(`Error initializing: ${err.message}`, 'error'); showMessage(`Error initializing: ${err.response?.data?.detail || err.message}`, 'error');
} }
} finally { } finally {
isLoading.value = false; isLoading.value = false;
@@ -319,8 +322,9 @@ const handleClear = async () => {
const data = res.data; const data = res.data;
showMessage(data.message || 'PKI cleared successfully!', 'warning'); showMessage(data.message || 'PKI cleared successfully!', 'warning');
await loadStatus(); await loadStatus();
refreshPkiStatus();
} catch (err) { } catch (err) {
showMessage(`Error clearing PKI: ${err.message}`, 'error'); showMessage(`Error clearing PKI: ${err.response?.data?.detail || err.message}`, 'error');
} finally { } finally {
isLoading.value = false; isLoading.value = false;
action.value = ''; action.value = '';
+16 -3
View File
@@ -56,7 +56,8 @@
<!-- Start --> <!-- Start -->
<button type="button" class="btn-action btn-action-primary" <button type="button" class="btn-action btn-action-primary"
@click="handleControl('start')" @click="handleControl('start')"
:disabled="isLoading || stats.status === 'running'"> :disabled="isLoading || stats.status === 'running' || !pkiStatus.server_ready"
:title="startHint">
<i v-if="isLoading && action==='start'" class="fas fa-spinner fa-spin"></i> <i v-if="isLoading && action==='start'" class="fas fa-spinner fa-spin"></i>
<i v-else class="fas fa-play"></i> <i v-else class="fas fa-play"></i>
Start Service Start Service
@@ -65,7 +66,8 @@
<!-- Restart --> <!-- Restart -->
<button type="button" class="btn-action btn-action-save" <button type="button" class="btn-action btn-action-save"
@click="handleControl('restart')" @click="handleControl('restart')"
:disabled="isLoading"> :disabled="isLoading || !pkiStatus.server_ready"
:title="startHint">
<i v-if="isLoading && action==='restart'" class="fas fa-spinner fa-spin"></i> <i v-if="isLoading && action==='restart'" class="fas fa-spinner fa-spin"></i>
<i v-else class="fas fa-sync-alt"></i> <i v-else class="fas fa-sync-alt"></i>
Restart Service Restart Service
@@ -86,12 +88,22 @@
</template> </template>
<script setup> <script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'; import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { useApi } from '../composables/useApi'; import { useApi } from '../composables/useApi';
import { useToast } from '../composables/useToast'; import { useToast } from '../composables/useToast';
import { usePkiStatus } from '../composables/usePkiStatus';
const { profilesApiClient } = useApi(); const { profilesApiClient } = useApi();
const toast = useToast(); const toast = useToast();
const { status: pkiStatus, refresh: refreshPkiStatus } = usePkiStatus();
// Start/Restart need the PKI server files (Stop stays available)
const startHint = computed(() => {
if (pkiStatus.server_ready) return '';
return pkiStatus.pki_ready && pkiStatus.missing.length
? `Missing server files: ${pkiStatus.missing.join(', ')}`
: 'Initialize PKI first';
});
// State // State
const stats = reactive({ const stats = reactive({
@@ -141,6 +153,7 @@ const handleControl = async (cmd) => {
}; };
onMounted(() => { onMounted(() => {
refreshPkiStatus();
fetchStats(); fetchStats();
// Poll every 5 seconds // Poll every 5 seconds
pollInterval = setInterval(fetchStats, 5000); pollInterval = setInterval(fetchStats, 5000);
+16 -3
View File
@@ -1,6 +1,15 @@
<template> <template>
<div class="config-wrapper"> <div class="config-wrapper">
<div class="config-card"> <!-- PKI cleared while the page is open (e.g. in another tab) -->
<div v-if="!pkiStatus.pki_ready" class="config-card">
<div class="config-header">
<h1>Server Infrastructure Configuration</h1>
</div>
<p><i class="fas fa-lock me-2"></i>The server cannot be configured until the PKI is initialized.</p>
<router-link to="/config/pki">Go to PKI configuration</router-link>
</div>
<div v-else class="config-card">
<div class="config-header"> <div class="config-header">
<h1>Server Infrastructure Configuration</h1> <h1>Server Infrastructure Configuration</h1>
</div> </div>
@@ -254,9 +263,11 @@
import { ref, onMounted, reactive, watch } from 'vue'; import { ref, onMounted, reactive, watch } from 'vue';
import { useApi } from '../composables/useApi'; import { useApi } from '../composables/useApi';
import { useToast } from '../composables/useToast'; import { useToast } from '../composables/useToast';
import { usePkiStatus } from '../composables/usePkiStatus';
const { profilesApiClient } = useApi(); const { profilesApiClient } = useApi();
const toast = useToast(); const toast = useToast();
const { status: pkiStatus, refresh: refreshPkiStatus } = usePkiStatus();
// State // State
const form = reactive({ const form = reactive({
@@ -356,7 +367,7 @@ const handleSave = async () => {
await profilesApiClient.put('/config/server', payload); await profilesApiClient.put('/config/server', payload);
showMessage('Server configuration saved!', 'success'); showMessage('Server configuration saved!', 'success');
} catch (err) { } catch (err) {
showMessage(`Error saving: ${err.message}`, 'error'); showMessage(`Error saving: ${err.response?.data?.detail || err.message}`, 'error');
} finally { } finally {
isLoading.value = false; isLoading.value = false;
action.value = ''; action.value = '';
@@ -371,7 +382,8 @@ const handleApply = async () => {
const data = res.data; const data = res.data;
showMessage(data.message || 'Configuration applied!', 'success'); showMessage(data.message || 'Configuration applied!', 'success');
} catch (err) { } catch (err) {
showMessage(`Error applying: ${err.message}`, 'error'); showMessage(`Error applying: ${err.response?.data?.detail || err.message}`, 'error');
refreshPkiStatus();
} finally { } finally {
isLoading.value = false; isLoading.value = false;
action.value = ''; action.value = '';
@@ -379,6 +391,7 @@ const handleApply = async () => {
}; };
onMounted(() => { onMounted(() => {
refreshPkiStatus();
loadConfig(); loadConfig();
}); });
</script> </script>
@@ -0,0 +1,48 @@
# PKI dependency guard (2026-10-04)
Goal: while the PKI is not initialized the VPN (server) section is closed, and nothing that needs keys can run. Plan: [PKI_Dependency_Guard_PLAN](2026-10-04_PKI_Dependency_Guard_PLAN.md).
## Rules (backend is the source of truth)
| Operation | Rule |
|---|---|
| `POST /server/configure`, `POST /server/process/start`, `restart` | `409` unless the PKI is initialized, no init job runs and every file `server.conf` points to exists (`ca.crt`, `issued/<fqdn_server>.crt`, `private/<fqdn_server>.key`, `dh.pem`, `ta.key`, `crl.pem` when `crl_verify` is on). The message names the missing files, so a changed `fqdn_server` is caught too |
| `POST /server/process/stop` | always allowed |
| `POST /profiles` | `409` unless the PKI is initialized and no init job runs |
| `DELETE /system/pki` | `409` while an init job runs and `409 "Stop OpenVPN first"` while OpenVPN runs |
| `PUT /config/server`, `GET /config`, monitoring | open (no key operation) |
| `GET /system/init/status` | new fields `pki_ready`, `server_ready`, `missing` |
## UI
| Area | Change |
|---|---|
| `composables/usePkiStatus.js` | Shared status, refreshed on login, on every route change and by the PKI page (init finished, Clear PKI) |
| Sidebar (`App.vue`) | VPN item is locked (lock icon, muted, tooltip "Initialize PKI first") until the PKI is ready; a click goes to the PKI page |
| Router (`router/index.js`) | `/config/vpn` requires a ready PKI; otherwise redirect to the PKI page with a toast (also for a typed URL). A failed status request does not block navigation |
| `ServerManagement.vue` | Start / Restart disabled with a hint (missing files); Stop stays enabled |
| `Certificates.vue` | New Client disabled with a hint |
| `VPNConfig.vue` | Lock notice with a link to the PKI page instead of the form when the PKI is not ready; backend error text in toasts |
## Verification (containers)
| Check | Result |
|---|---|
| pytest (`test_pki_guard`, `test_async_pki_init`, `test_profile_note`) in `python:3.12-alpine` | 3 passed |
| After Clear PKI: status | `pki_ready: false`, `server_ready: false`, missing files listed |
| After Clear PKI: configure, start, restart, create client | `409`; stop `200` |
| Init PKI, then configure, start | `200`, `200` |
| Clear PKI while OpenVPN runs | `409 Stop OpenVPN first` |
| `fqdn_server` renamed after init: configure, start | `409`, names `issued/renamed-srv.crt` and `private/renamed-srv.key` |
| Create a client after init | `200` |
| UI bundle contains the guard texts | yes; behaviour in the browser is checked manually |
## Notes
- The status is refreshed on navigation and by the PKI page, not by polling: an open VPN page notices a cleared PKI on its next refresh (navigation or a failed Apply).
- After a rename of `fqdn_server` the VPN page stays reachable (the PKI itself is intact); configure, start and restart are blocked and name the missing certificate.
- `DELETE /system/pki` takes about a second longer while OpenVPN runs (process statistics).
## Existing installations
No manual steps. Rebuild and restart the Profiler and the UI. A running server is not affected until it is restarted.
@@ -0,0 +1,59 @@
# Logical protection: server setup depends on PKI (plan, 2026-10-04)
Goal: while the PKI is not initialized, the VPN (server) section is closed, and nothing that needs keys can run. The rule is enforced in the backend (the source of truth) and reflected in the UI.
## Dependency analysis
What the server needs: `ca.crt`, server certificate and key (`issued/<fqdn_server>.crt`, `private/<fqdn_server>.key`), `dh.pem`, `ta.key`, `crl.pem` (used when `crl_verify` is on). `server.conf.j2` points to all of them.
| Operation | Needs PKI? | Today | Planned |
|---|---|---|---|
| `POST /server/configure` (build and install `server.conf`) | yes, all server files | renders paths to files that do not exist and installs the config | `409` with the list of missing files |
| `POST /server/process/start`, `restart` | yes (config + keys) | tries to start; may start with a stale `server.conf` from an earlier PKI | `409` unless the server files exist; `stop` stays allowed |
| `POST /profiles` (create client) | yes (CA) | blocked only while an init job runs | `409` unless the PKI is initialized |
| `DELETE /profiles/{id}` (revoke), download | CA / existing file | no PKI means no profiles (Clear PKI wipes them) | unchanged |
| `PUT /config/server` (save settings), `GET /config` | no (only DB values) | open | open at API level (see decision 1) |
| `PUT /config/pki` | no | open | open; UI warns that changing the server name after init makes the server certificate name stale |
| Monitoring (`APP_CORE`: Analytics, Clients) | no | open | unchanged |
Hidden dependencies found:
1. Server name: `fqdn_server` is used to build the certificate path. If it is edited after init, `server.conf` would point to a missing certificate. The check must test the actual files, not just "PKI exists".
2. Clear PKI leaves `/etc/openvpn/server.conf` and possibly a running OpenVPN that has lost its keys. After Clear the server must not be startable, and Clear should not pull the keys from under a running server (decision 2).
3. An init job in progress counts as "not ready".
## Steps
### 1. Backend (`APP_PROFILER/`)
- `services/pki.py`: `server_files_missing(db)` returns the list of missing server files (honours `fqdn_server`; `crl.pem` required only when `crl_verify` is on); `require_pki_ready()` helpers raising a `PkiNotReady` exception with a clear message.
- `routers/server.py` (`/server/configure`), `routers/server_process.py` (`start`, `restart`), `routers/profiles.py` (`POST /profiles`): return `409 {"detail": "PKI is not initialized. Initialize PKI first."}` (or the list of missing files).
- `GET /system/init/status` gets two fields: `pki_ready` (initialized, no job running) and `server_ready` (all server files present) plus `missing` (file names). One endpoint feeds the whole UI.
- Decision 2: `DELETE /system/pki` returns `409 "Stop OpenVPN first"` while the OpenVPN process runs.
### 2. UI (`APP_UI/`)
- `composables/usePkiStatus.js`: shared reactive status (`pki_ready`, `server_ready`, `missing`, `state`), `refresh()`; loaded after login, on every route change and by `PKIConfig.vue` when init finishes or PKI is cleared (the sidebar updates without reload).
- Sidebar (`App.vue`): the **VPN** item stays visible but locked (lock icon, muted, tooltip "Initialize PKI first"); click redirects to the PKI page.
- Router guard (`router/index.js`): `/config/vpn` is `meta.requiresPki`; without a ready PKI the navigation is redirected to `/config/pki` with a toast "Initialize PKI before configuring the server". Direct URL entry is covered by the same guard.
- `ServerManagement.vue`: Start/Restart disabled with the hint when `server_ready` is false (Stop stays enabled).
- `Certificates.vue`: "New Client" disabled with the hint when the PKI is not initialized.
- `VPNConfig.vue`: if the status changes while the page is open (PKI cleared in another tab), the page shows the lock notice instead of the form.
- Backend `409` messages are shown through the existing toast.
### 3. Tests (minimal)
- One pytest in `APP_PROFILER` with PKI absent: `POST /server/configure`, `POST /server/process/start` and `POST /profiles` return `409`; `GET /system/init/status` shows `pki_ready: false`, `server_ready: false`. With the PKI files created (stub directory) the three calls are no longer `409` for this reason. No UI tests.
### 4. Verification (containers, stand port 8089)
- Clear PKI: VPN menu locked, `/config/vpn` redirects, Start/Restart and New Client disabled; the same calls through the API return `409`.
- Init PKI: after it finishes the menu unlocks without a page reload; configure, start, create client work.
- Edit the server name after init: configure answers `409` naming the missing certificate.
- Clear PKI with OpenVPN running: `409` (decision 2).
### 5. Documentation
- `API_Reference.md` (409 cases, new status fields), summary `DOCS/Changes/2026-10-04_PKI_Dependency_Guard.md`, README row, Index link.
## Decisions for the owner
1. `PUT /config/server` stays open at the API level (it touches only DB values and is not a key operation); the page itself is locked in the UI. Alternative: also answer `409` there.
2. Block Clear PKI while OpenVPN is running (recommended) or allow it and only warn.
3. VPN menu item: visible and locked (recommended, the user sees why) or hidden.
## Out of scope
Automatic stop of OpenVPN, certificate expiry checks, locking the Server Process page as a whole.
+1
View File
@@ -22,6 +22,7 @@ Welcome to the documentation for the OpenVPN Monitor suite.
- [Profile notes (2026-10-04)](../Changes/2026-10-04_Profile_Notes.md) - [Profile notes (2026-10-04)](../Changes/2026-10-04_Profile_Notes.md)
- [Async PKI init (2026-10-04)](../Changes/2026-10-04_Async_PKI_Init.md) - [Async PKI init (2026-10-04)](../Changes/2026-10-04_Async_PKI_Init.md)
- [Toast notifications (2026-10-04)](../Changes/2026-10-04_Toast_Notifications.md) - [Toast notifications (2026-10-04)](../Changes/2026-10-04_Toast_Notifications.md)
- [PKI dependency guard (2026-10-04)](../Changes/2026-10-04_PKI_Dependency_Guard.md)
## 🔍 Core Monitoring (`APP_CORE`) ## 🔍 Core Monitoring (`APP_CORE`)
The core module responsible for log parsing, real-time statistics, and the primary API. The core module responsible for log parsing, real-time statistics, and the primary API.
+7 -3
View File
@@ -24,7 +24,7 @@ List all user profiles.
Create a new user profile. Create a new user profile.
- **Body**: `{"username": "jdoe"}` - **Body**: `{"username": "jdoe"}`
- **Action**: Generates keys, requests certificate, builds `.ovpn` file. - **Action**: Generates keys, requests certificate, builds `.ovpn` file.
- **Response `409`**: PKI initialization is running (the PKI is not complete yet). - **Response `409`**: PKI initialization is running, or the PKI is not initialized (`"PKI is not initialized. Initialize PKI first."`).
### `DELETE /profiles/{id}` ### `DELETE /profiles/{id}`
Revoke a user profile. Revoke a user profile.
@@ -66,13 +66,15 @@ Start PKI initialization (init-pki, CA, server certificate, DH, TLS key, CRL) as
### `GET /system/init/status` ### `GET /system/init/status`
Current state of the initialization job. Current state of the initialization job.
- **Response**: `{ "state": "idle|running|done|error", "step": "init-pki|ca|server-cert|dh|ta-key|crl|null", "initialized": true, "started_at": "2026-10-04T10:00:00Z", "finished_at": null, "error": null }` - **Response**: `{ "state": "idle|running|done|error", "step": "init-pki|ca|server-cert|dh|ta-key|crl|null", "initialized": true, "started_at": "2026-10-04T10:00:00Z", "finished_at": null, "error": null, "pki_ready": true, "server_ready": true, "missing": [] }`
- `initialized` reflects the files on disk (complete PKI), independent of `state`. - `initialized` reflects the files on disk (complete PKI), independent of `state`.
- `pki_ready`: the PKI is initialized and no job is running (client certificates can be issued).
- `server_ready`: `pki_ready` and every file `server.conf` references exists; `missing` lists the absent ones (relative to the PKI directory: `ca.crt`, `issued/<fqdn_server>.crt`, `private/<fqdn_server>.key`, `dh.pem`, `ta.key`, and `crl.pem` only when `crl_verify` is on). The check uses the current `fqdn_server`, so renaming the server after init makes it not ready.
- `error` contains the EasyRSA message when `state` is `error`. - `error` contains the EasyRSA message when `state` is `error`.
### `DELETE /system/pki` ### `DELETE /system/pki`
**DANGER**: Completely wipes the PKI directory and resets the job state. **DANGER**: Completely wipes the PKI directory and resets the job state.
- **Response `409`**: an initialization job is running. - **Response `409`**: an initialization job is running, or OpenVPN is running (`"Stop OpenVPN first"`).
--- ---
@@ -81,11 +83,13 @@ Current state of the initialization job.
### `POST /server/configure` ### `POST /server/configure`
Generate the `server.conf` file based on current database settings. Generate the `server.conf` file based on current database settings.
- **Response**: `{"message": "Server configuration generated", "path": "/etc/openvpn/server.conf"}` - **Response**: `{"message": "Server configuration generated", "path": "/etc/openvpn/server.conf"}`
- **Response `409`**: the PKI is not initialized or an init job is running (`"PKI is not initialized. Initialize PKI first."`), or server files are missing (`"PKI server files are missing: ..."`).
### `POST /server/process/{action}` ### `POST /server/process/{action}`
Control the OpenVPN system service. Control the OpenVPN system service.
- **Path Param**: `action` (start, stop, restart) - **Path Param**: `action` (start, stop, restart)
- **Response**: Status of the command execution. - **Response**: Status of the command execution.
- **Response `409`**: for `start` and `restart` only, same conditions as `POST /server/configure`. `stop` is always allowed.
### `GET /server/process/stats` ### `GET /server/process/stats`
Get telemetry for the OpenVPN process. Get telemetry for the OpenVPN process.
+1
View File
@@ -64,6 +64,7 @@ No default user is created. Seed the initial admin with `OVPMON_INITIAL_ADMIN_US
| 2026-10-04 | Certificates page: clickable rows, profile details modal with a saved note (`PUT /profiles/{id}/note`) | [Profile notes](DOCS/Changes/2026-10-04_Profile_Notes.md) (includes the compact modal and the note tooltip on the client name) | | 2026-10-04 | Certificates page: clickable rows, profile details modal with a saved note (`PUT /profiles/{id}/note`) | [Profile notes](DOCS/Changes/2026-10-04_Profile_Notes.md) (includes the compact modal and the note tooltip on the client name) |
| 2026-10-04 | PKI initialization runs in the background: status endpoint, progress on the PKI page, protection against a second start | [Async PKI init](DOCS/Changes/2026-10-04_Async_PKI_Init.md) | | 2026-10-04 | PKI initialization runs in the background: status endpoint, progress on the PKI page, protection against a second start | [Async PKI init](DOCS/Changes/2026-10-04_Async_PKI_Init.md) |
| 2026-10-04 | Toast notifications moved to the bottom-right corner, shared component, light/dark themes | [Toast notifications](DOCS/Changes/2026-10-04_Toast_Notifications.md) | | 2026-10-04 | Toast notifications moved to the bottom-right corner, shared component, light/dark themes | [Toast notifications](DOCS/Changes/2026-10-04_Toast_Notifications.md) |
| 2026-10-04 | Server setup is closed until the PKI is initialized (VPN menu lock, 409 for configure/start/create client, Clear PKI blocked while OpenVPN runs) | [PKI dependency guard](DOCS/Changes/2026-10-04_PKI_Dependency_Guard.md) |
## Notes ## Notes