diff --git a/APP_PROFILER/database.py b/APP_PROFILER/database.py index 5331291..a8d22f1 100644 --- a/APP_PROFILER/database.py +++ b/APP_PROFILER/database.py @@ -1,4 +1,4 @@ -from sqlalchemy import create_engine +from sqlalchemy import create_engine, inspect, text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker @@ -22,3 +22,14 @@ def get_db(): yield db finally: db.close() + +def ensure_columns(): + """Idempotent 'add column if missing' migration for existing databases. + create_all() creates new tables but never alters existing ones.""" + insp = inspect(engine) + if "user_profiles" not in insp.get_table_names(): + return + existing = {c["name"] for c in insp.get_columns("user_profiles")} + if "note" not in existing: + with engine.begin() as conn: + conn.execute(text("ALTER TABLE user_profiles ADD COLUMN note TEXT")) diff --git a/APP_PROFILER/main.py b/APP_PROFILER/main.py index 0357ec0..352d262 100644 --- a/APP_PROFILER/main.py +++ b/APP_PROFILER/main.py @@ -7,13 +7,14 @@ import os import os sys.path.append(os.path.dirname(os.path.abspath(__file__))) -from database import engine, Base +from database import engine, Base, ensure_columns from routers import system, server, profiles, server_process from utils.logging import setup_logging from fastapi.middleware.cors import CORSMiddleware # Create Database Tables Base.metadata.create_all(bind=engine) +ensure_columns() setup_logging() diff --git a/APP_PROFILER/models.py b/APP_PROFILER/models.py index 9e978d4..26c63b7 100644 --- a/APP_PROFILER/models.py +++ b/APP_PROFILER/models.py @@ -1,4 +1,4 @@ -from sqlalchemy import Column, Integer, String, Boolean, DateTime, JSON +from sqlalchemy import Column, Integer, String, Boolean, DateTime, JSON, Text from sqlalchemy.sql import func from database import Base from datetime import datetime @@ -61,3 +61,4 @@ class UserProfile(Base): is_revoked = Column(Boolean, default=False) is_expired = Column(Boolean, default=False) file_path = Column(String, nullable=True) + note = Column(Text, nullable=True) diff --git a/APP_PROFILER/requirements-dev.txt b/APP_PROFILER/requirements-dev.txt new file mode 100644 index 0000000..7af6bb0 --- /dev/null +++ b/APP_PROFILER/requirements-dev.txt @@ -0,0 +1,3 @@ +-r requirements.txt +pytest +httpx diff --git a/APP_PROFILER/requirements.txt b/APP_PROFILER/requirements.txt index 7eec6e6..b57a99d 100644 --- a/APP_PROFILER/requirements.txt +++ b/APP_PROFILER/requirements.txt @@ -4,4 +4,5 @@ sqlalchemy psutil python-multipart jinja2 -pyjwt \ No newline at end of file +pyjwt +requests diff --git a/APP_PROFILER/routers/profiles.py b/APP_PROFILER/routers/profiles.py index adcaaa7..2848c45 100644 --- a/APP_PROFILER/routers/profiles.py +++ b/APP_PROFILER/routers/profiles.py @@ -5,7 +5,7 @@ from sqlalchemy.orm import Session from database import get_db from utils.auth import verify_token from models import UserProfile -from schemas import UserProfile as UserProfileSchema, UserProfileCreate +from schemas import UserProfile as UserProfileSchema, UserProfileCreate, UserProfileNoteUpdate from services import pki, generator from datetime import datetime @@ -74,6 +74,9 @@ def create_profile( profile_in: UserProfileCreate, db: Session = Depends(get_db) ): + if pki.is_init_running(): + raise HTTPException(status_code=409, detail="PKI initialization is running") + # Check existing existing = db.query(UserProfile).filter(UserProfile.username == profile_in.username).first() if existing: @@ -116,6 +119,17 @@ def create_profile( db.refresh(new_profile) return new_profile +@router.put("/profiles/{profile_id}/note", response_model=UserProfileSchema) +def update_profile_note(profile_id: int, body: UserProfileNoteUpdate, db: Session = Depends(get_db)): + profile = db.query(UserProfile).filter(UserProfile.id == profile_id).first() + if not profile: + raise HTTPException(status_code=404, detail="Profile not found") + + profile.note = body.note + db.commit() + db.refresh(profile) + return profile + @router.delete("/profiles/{profile_id}") def revoke_profile(profile_id: int, db: Session = Depends(get_db)): profile = db.query(UserProfile).filter(UserProfile.id == profile_id).first() diff --git a/APP_PROFILER/routers/system.py b/APP_PROFILER/routers/system.py index b8e21dd..616fdde 100644 --- a/APP_PROFILER/routers/system.py +++ b/APP_PROFILER/routers/system.py @@ -36,15 +36,21 @@ def update_pki_config( ): return config.update_pki_settings(db, settings) -@router.post("/system/init") +@router.post("/system/init", status_code=202) def init_system_pki(db: Session = Depends(get_db)): try: - msg = pki.init_pki(db) - return {"message": msg} - except Exception as e: - raise HTTPException(status_code=500, detail=str(e)) + pki.start_init_async(db) + except pki.InitConflict as e: + raise HTTPException(status_code=409, detail=str(e)) + return {"state": "running"} + +@router.get("/system/init/status") +def get_init_status(db: Session = Depends(get_db)): + return pki.init_status(db) @router.delete("/system/pki") def clear_system_pki(db: Session = Depends(get_db)): + if pki.is_init_running(): + raise HTTPException(status_code=409, detail="PKI initialization is running") msg = pki.clear_pki(db) return {"message": msg} diff --git a/APP_PROFILER/schemas.py b/APP_PROFILER/schemas.py index c8feed3..3b88fcd 100644 --- a/APP_PROFILER/schemas.py +++ b/APP_PROFILER/schemas.py @@ -224,6 +224,18 @@ class UserProfile(UserProfileBase): is_revoked: bool = False is_expired: bool = False file_path: Optional[str] = None + note: Optional[str] = None class Config: from_attributes = True + +class UserProfileNoteUpdate(BaseModel): + note: Optional[str] = Field(None, max_length=1000) + + @field_validator("note") + @classmethod + def _empty_to_none(cls, val): + # Empty or whitespace-only note clears the field + if val is None or not val.strip(): + return None + return val diff --git a/APP_PROFILER/services/pki.py b/APP_PROFILER/services/pki.py index d021c1f..0f4fdc2 100644 --- a/APP_PROFILER/services/pki.py +++ b/APP_PROFILER/services/pki.py @@ -1,9 +1,12 @@ import os import subprocess import logging +import shutil +import threading from .config import get_pki_settings from sqlalchemy.orm import Session from datetime import datetime +from database import SessionLocal logger = logging.getLogger(__name__) @@ -120,37 +123,114 @@ def _get_easyrsa_env(db: Session): } return env -def init_pki(db: Session): +# --- Async PKI initialization ------------------------------------------- +# Single Profiler process only: the job state lives in memory. +class InitConflict(Exception): + """PKI init cannot start: a job is running or the PKI is already complete.""" + +_init_lock = threading.Lock() +_init_job = {"state": "idle", "step": None, "started_at": None, "finished_at": None, "error": None} + +def _marker_path() -> str: + # Outside PKI_DIR: "easyrsa init-pki" recreates that directory + return os.path.join(os.path.dirname(PKI_DIR), ".pki-init-in-progress") + +def is_initialized(db: Session = None) -> bool: + """A CA exists and no init run was left unfinished. A PKI without the marker is never + wiped automatically, even if it was built by an older version.""" + return os.path.isfile(os.path.join(PKI_DIR, "ca.crt")) and not os.path.exists(_marker_path()) + +def is_init_running() -> bool: + with _init_lock: + return _init_job["state"] == "running" + +def init_status(db: Session) -> dict: + with _init_lock: + job = dict(_init_job) + job["initialized"] = is_initialized() + return job + +def _set_step(step: str): + with _init_lock: + _init_job["step"] = step + +def _gen_ta_key(): + # TLS auth key requires openvpn, not easyrsa + subprocess.run(["openvpn", "--genkey", "secret", os.path.join(PKI_DIR, "ta.key")], check=True) + +def init_pki(db: Session, on_step=None): env = _get_easyrsa_env(db) pki_settings = get_pki_settings(db) - - if os.path.exists(os.path.join(PKI_DIR, "ca.crt")): + step = on_step or (lambda name: None) + + if is_initialized(): logger.warning("PKI already initialized") return "PKI already initialized" # Init PKI + step("init-pki") _run_easyrsa(["init-pki"], env) # Build CA + step("ca") _run_easyrsa(["--req-cn=" + pki_settings.fqdn_ca, "build-ca", "nopass"], env) # Build Server Cert + step("server-cert") _run_easyrsa(["build-server-full", pki_settings.fqdn_server, "nopass"], env) # Gen DH + step("dh") _run_easyrsa(["gen-dh"], env) - # Gen TLS Auth Key (requires openvpn, not easyrsa) - ta_key_path = os.path.join(PKI_DIR, "ta.key") - subprocess.run(["openvpn", "--genkey", "secret", ta_key_path], check=True) + # Gen TLS Auth Key + step("ta-key") + _gen_ta_key() # Gen CRL + step("crl") _run_easyrsa(["gen-crl"], env) _publish_crl() return "PKI Initialized" +def _init_worker(): + db = SessionLocal() # own session: the request session is closed after the 202 + try: + init_pki(db, on_step=_set_step) + os.remove(_marker_path()) + result = {"state": "done", "step": None, "error": None} + except Exception as e: + logger.exception("Async PKI init failed") + result = {"state": "error", "error": str(e)[:1000]} + finally: + db.close() + with _init_lock: + _init_job.update(result, finished_at=datetime.utcnow().isoformat() + "Z") + +def start_init_async(db: Session): + with _init_lock: + if _init_job["state"] == "running": + raise InitConflict("PKI initialization is already running") + if is_initialized(): + raise InitConflict("PKI is already initialized") + # Here the PKI is absent, has no CA, or carries the marker of an interrupted run: + # nothing usable in it, start from scratch + if os.path.exists(PKI_DIR): + shutil.rmtree(PKI_DIR) + os.makedirs(os.path.dirname(_marker_path()), exist_ok=True) + open(_marker_path(), "w").close() + _init_job.update(state="running", step=None, error=None, finished_at=None, + started_at=datetime.utcnow().isoformat() + "Z") + threading.Thread(target=_init_worker, daemon=True).start() + def clear_pki(db: Session): + with _init_lock: + if _init_job["state"] != "running": + _init_job.update(state="idle", step=None, started_at=None, finished_at=None, error=None) + if os.path.exists(_marker_path()): + os.remove(_marker_path()) + # 1. Clear Database Users from models import UserProfile try: diff --git a/APP_PROFILER/test_async_pki_init.py b/APP_PROFILER/test_async_pki_init.py new file mode 100644 index 0000000..bc884cc --- /dev/null +++ b/APP_PROFILER/test_async_pki_init.py @@ -0,0 +1,59 @@ +import os +import tempfile +import threading +import time + +# 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 services import pki +from utils.auth import verify_token + +app.dependency_overrides[verify_token] = lambda: {"sub": "test"} +client = TestClient(app) + + +def test_async_init_runs_once(monkeypatch): + pki_dir = os.path.join(_tmp.name, "pki") + release = threading.Event() + + def touch(*parts): + path = os.path.join(pki_dir, *parts) + os.makedirs(os.path.dirname(path), exist_ok=True) + open(path, "w").close() + + def fake_easyrsa(command, env): + if command[0] == "build-server-full": + touch("issued", command[1] + ".crt") + elif command[0] == "gen-dh": + release.wait(5) # keeps the job running until the test lets go + touch("dh.pem") + elif command[0] == "gen-crl": + touch("crl.pem") + elif "build-ca" in command: + touch("ca.crt") + + monkeypatch.setattr(pki, "PKI_DIR", pki_dir) + monkeypatch.setattr(pki, "_run_easyrsa", fake_easyrsa) + monkeypatch.setattr(pki, "_gen_ta_key", lambda: touch("ta.key")) + monkeypatch.setattr(pki, "_publish_crl", lambda: True) + + res = client.post("/api/system/init") + assert res.status_code == 202 and res.json() == {"state": "running"} + assert client.post("/api/system/init").status_code == 409 + assert client.get("/api/system/init/status").json()["state"] == "running" + assert client.delete("/api/system/pki").status_code == 409 + + release.set() + deadline = time.time() + 5 + while time.time() < deadline: + status = client.get("/api/system/init/status").json() + if status["state"] != "running": + break + time.sleep(0.05) + + assert status["state"] == "done" and status["initialized"] is True + assert client.post("/api/system/init").status_code == 409 diff --git a/APP_PROFILER/test_profile_note.py b/APP_PROFILER/test_profile_note.py new file mode 100644 index 0000000..3c332ff --- /dev/null +++ b/APP_PROFILER/test_profile_note.py @@ -0,0 +1,32 @@ +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 models import UserProfile +from utils.auth import verify_token + +app.dependency_overrides[verify_token] = lambda: {"sub": "test"} +client = TestClient(app) + + +def test_put_note_is_stored_and_listed(): + db = SessionLocal() + profile = UserProfile(username="note-user", status="active") + db.add(profile) + db.commit() + profile_id = profile.id + db.close() + + res = client.put(f"/api/profiles/{profile_id}/note", json={"note": "hello"}) + assert res.status_code == 200 + assert res.json()["note"] == "hello" + + res = client.get("/api/profiles") + assert res.status_code == 200 + assert [p["note"] for p in res.json() if p["id"] == profile_id] == ["hello"] diff --git a/APP_UI/src/assets/main.css b/APP_UI/src/assets/main.css index d107b4b..91ead5c 100644 --- a/APP_UI/src/assets/main.css +++ b/APP_UI/src/assets/main.css @@ -1802,6 +1802,48 @@ input[type="number"].config-input { transform: scale(1.02); } +/* Profile note tooltip (v-note-tooltip) */ +.note-tooltip { + --bs-tooltip-max-width: 320px; + --bs-tooltip-bg: var(--bg-card); + --bs-tooltip-color: var(--text-main); + --bs-tooltip-opacity: 1; +} + +.note-tooltip .tooltip-inner { + max-width: 320px; + white-space: pre-wrap; + text-align: left; + word-break: break-word; + background-color: var(--bg-card); + color: var(--text-main); + border: 1px solid var(--border-color); + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); +} + +.note-tooltip .tooltip-arrow::before { + border-top-color: var(--border-color); +} + +/* Compact label : value list (profile details modal) */ +.profile-meta { + display: grid; + grid-template-columns: 5.5rem 1fr; + gap: 0.25rem 0.75rem; + margin: 0 0 1rem; + font-size: 0.9rem; +} + +.profile-meta dt { + font-weight: 600; + color: var(--text-muted); +} + +.profile-meta dd { + margin: 0; + text-align: left; +} + /* Shared Utilities */ .cursor-pointer { cursor: pointer; diff --git a/APP_UI/src/components/ProfileDetailsModal.vue b/APP_UI/src/components/ProfileDetailsModal.vue new file mode 100644 index 0000000..334d261 --- /dev/null +++ b/APP_UI/src/components/ProfileDetailsModal.vue @@ -0,0 +1,86 @@ + + + diff --git a/APP_UI/src/directives/noteTooltip.js b/APP_UI/src/directives/noteTooltip.js new file mode 100644 index 0000000..5a3dad5 --- /dev/null +++ b/APP_UI/src/directives/noteTooltip.js @@ -0,0 +1,37 @@ +import { Tooltip } from 'bootstrap'; + +// v-note-tooltip="text": Bootstrap tooltip with the profile note. +// No tooltip for an empty value; plain text only (html: false). +const create = (el, text) => { + el._noteTooltip = new Tooltip(el, { + title: text, + placement: 'top', + container: 'body', + html: false, + trigger: 'hover', + customClass: 'note-tooltip' + }); +}; + +const destroy = (el) => { + el._noteTooltip?.dispose(); + el._noteTooltip = null; +}; + +// Hide on click: the row click opens the details modal +const hideOnClick = (el) => el._noteTooltip?.hide(); + +export default { + mounted(el, binding) { + el.addEventListener('click', () => hideOnClick(el)); + if (binding.value) create(el, binding.value); + }, + updated(el, binding) { + if (binding.value === binding.oldValue) return; + destroy(el); + if (binding.value) create(el, binding.value); + }, + unmounted(el) { + destroy(el); + } +}; diff --git a/APP_UI/src/views/Certificates.vue b/APP_UI/src/views/Certificates.vue index 3e177c8..7f082e8 100644 --- a/APP_UI/src/views/Certificates.vue +++ b/APP_UI/src/views/Certificates.vue @@ -88,9 +88,12 @@ Active Certificates ({{ activeCerts.length }}) - - -
{{ cert.username }}
+ + +
+ {{ cert.username }} + +
{{ cert.file_path || 'N/A' }}
Client @@ -100,10 +103,10 @@ - - @@ -114,9 +117,12 @@ Expired / Revoked ({{ expiredCerts.length }}) - - -
{{ cert.username }}
+ + +
+ {{ cert.username }} + +
{{ cert.file_path || 'N/A' }}
Client @@ -126,7 +132,7 @@ - @@ -140,6 +146,7 @@ +
@@ -152,6 +159,8 @@ import { ref, computed, onMounted } from 'vue'; import { useApi } from '../composables/useApi'; import NewClientModal from '../components/NewClientModal.vue'; import ConfirmModal from '../components/ConfirmModal.vue'; +import ProfileDetailsModal from '../components/ProfileDetailsModal.vue'; +import vNoteTooltip from '../directives/noteTooltip'; const { profilesApiClient } = useApi(); @@ -162,6 +171,7 @@ const hideExpired = ref(false); const newClientModal = ref(null); const confirmModal = ref(null); +const detailsModal = ref(null); const toastMessage = ref(''); const toastType = ref('success'); @@ -276,6 +286,20 @@ const createClient = async (username) => { } }; +const showDetails = (cert) => { + detailsModal.value.open(cert); +}; + +const saveNote = async ({ id, note }) => { + try { + await profilesApiClient.put(`/profiles/${id}/note`, { note }); + showToast('Note saved.', 'success'); + loadCerts(); + } catch(e) { + showToast(e.response?.data?.detail || e.message, 'error'); + } +}; + const downloadConfig = async (cert) => { if (!cert.id) return; try { diff --git a/APP_UI/src/views/PKIConfig.vue b/APP_UI/src/views/PKIConfig.vue index 6054b9a..576c268 100644 --- a/APP_UI/src/views/PKIConfig.vue +++ b/APP_UI/src/views/PKIConfig.vue @@ -149,21 +149,23 @@
- - -
+
{{ stepText }}
@@ -171,7 +173,7 @@ diff --git a/DOCS/Changes/2026-10-04_Async_PKI_Init.md b/DOCS/Changes/2026-10-04_Async_PKI_Init.md new file mode 100644 index 0000000..7b3a072 --- /dev/null +++ b/DOCS/Changes/2026-10-04_Async_PKI_Init.md @@ -0,0 +1,35 @@ +# Async PKI initialization (2026-10-04) + +Goal: `Init PKI` can take minutes (DH parameters); it no longer holds an HTTP request. Plan: [Async_PKI_Init_PLAN](2026-10-04_Async_PKI_Init_PLAN.md). + +## Changes + +| Area | Change | +|---|---| +| API (`APP_PROFILER/routers/system.py`) | `POST /system/init` returns `202 {"state":"running"}` and runs the init in a background thread; `409` if a job is running or the PKI is initialized. New `GET /system/init/status` (`state`, `step`, `initialized`, `started_at`, `finished_at`, `error`). `DELETE /system/pki` and `POST /profiles` return `409` while a job is running | +| Service (`APP_PROFILER/services/pki.py`) | In-memory job state under a lock; the thread uses its own DB session; steps `init-pki`, `ca`, `server-cert`, `dh`, `ta-key`, `crl`; EasyRSA error text is stored in `error` | +| Interrupted runs | A marker file `/.pki-init-in-progress` (outside the PKI directory) exists while a job runs and is removed on success. A leftover marker (restart, crash, failed job) means the PKI is incomplete: it is wiped and rebuilt on the next Init. A PKI without the marker and with `ca.crt` counts as initialized and is **never** wiped automatically | +| UI (`APP_UI/src/views/PKIConfig.vue`) | State comes from the server on page load; spinner and step text while running, polling every 3 s; Init, Clear and Save disabled while running; Init disabled with a hint once initialized; success or error message at the end; a `409` on start attaches to the running job; the button locks on click | +| Docs | `DOCS/Profiler_Management/API_Reference.md` | +| Test | `APP_PROFILER/test_async_pki_init.py` (one test with EasyRSA stubs): 202, second start 409, status `running`, Clear 409, then `done` and a further start 409 | + +## Verification (containers) + +| Check | Result | +|---|---| +| `pytest test_async_pki_init.py` and `test_profile_note.py` in `python:3.12-alpine` | 2 passed | +| Existing complete PKI | status `initialized: true`, Init is a no-op | +| Clear, then Init | `202`, second start `409`, steps `init-pki` → `dh` → `done` (3 s and 54 s in two runs) | +| Partial PKI with the marker (simulated interrupted run) | wiped, rebuilt, marker removed, `initialized: true` | +| Create a client during the run / after it | `409` / `200` | +| UI bundle | `app-ui` builds and contains the status polling; the page behaviour is checked manually | + +## Notes + +- The Profiler must run as a single process (in-memory job state): `python main.py` in Docker, one `uvicorn` in the native unit. Do not add workers. +- Initialization is not cancelled by a page reload; the page reattaches to the running job. +- Not implemented: cancelling a run, progress percentage, async Clear PKI. + +## Existing installations + +No manual steps. Rebuild and restart the Profiler (native: `ovpmon-profiler`; Docker: `app-profiler`, `app-ui`). An already initialized PKI is detected as before. diff --git a/DOCS/Changes/2026-10-04_Async_PKI_Init_PLAN.md b/DOCS/Changes/2026-10-04_Async_PKI_Init_PLAN.md new file mode 100644 index 0000000..10f3047 --- /dev/null +++ b/DOCS/Changes/2026-10-04_Async_PKI_Init_PLAN.md @@ -0,0 +1,46 @@ +# Async PKI initialization: implementation plan (2026-10-04) + +Goal: `Init PKI` can take minutes (DH parameters). Run it in the background; the PKI Configuration page shows progress, survives a page reload and prevents a second start. + +## Current state +- `POST /system/init` (`APP_PROFILER/routers/system.py`) runs `pki.init_pki()` synchronously: init-pki, build-ca, server cert, gen-dh, ta.key, gen-crl, CRL publish. The HTTP request stays open until it ends. +- `pki.init_pki()` treats the PKI as initialized if `ca.crt` exists, so a PKI interrupted after the CA step (restart, crash) would be reported as ready. +- `PKIConfig.vue`: `isLoading` is local to the page, so a reload loses the state and the button becomes active again. +- The Profiler runs as a single process (`python main.py` in Docker, one `uvicorn` in the native unit), so in-memory job state is valid. + +## Steps + +### 1. Backend (`APP_PROFILER/`) +- `services/pki.py` + - `is_initialized()`: true only when the PKI is complete (`ca.crt`, `dh.pem`, `ta.key`, `crl.pem` and the server certificate exist). Existing complete PKIs are detected without migration. + - Job state `init_job` (module level, guarded by a lock): `state` = `idle | running | done | error`, `step` (init-pki, CA, server certificate, DH, TLS key, CRL), `started_at`, `finished_at`, `error`. + - `start_init_async()`: refuses to start when a job is running or the PKI is complete; removes an incomplete PKI left by an interrupted run; starts a daemon thread with its **own** DB session; the thread updates `step` and ends in `done` or `error` (error text from EasyRSA, no secrets). +- `routers/system.py` + - `POST /system/init` returns `202 {"state": "running"}` immediately; `409` if a job is running or the PKI is already initialized. + - `GET /system/init/status` returns `{state, step, initialized, started_at, finished_at, error}`. + - `DELETE /system/pki` returns `409` while an init job is running. + - `POST /profiles` returns `409` while an init job is running (the PKI is not complete). +- After an application restart the state is `idle`; an interrupted PKI is reported as `initialized: false`, and Init PKI cleans it up and starts again. + +### 2. UI (`APP_UI/src/views/PKIConfig.vue`) +- On mount call `GET /system/init/status`; state is taken from the server, not from the page. +- `running`: spinner on the Init PKI button, the current step text ("Generating DH parameters..."), polling every 3 s, Init / Clear / Save disabled. +- `done` or `initialized: true`: Init PKI is disabled with the hint "PKI is already initialized. Use Clear PKI to start over"; a success message is shown once when the job finishes while the page is open. +- `error`: error message, Init PKI is enabled again. +- After Clear PKI the status is reloaded and the button is enabled again. +- A double click or a second tab cannot start a second job (button locked immediately on click, backend answers `409` anyway; the UI treats `409 running` as "attach to the running job"). +- Polling stops on unmount. + +### 3. Tests (minimal) +- One pytest in `APP_PROFILER`: with the EasyRSA steps replaced by fast stubs, `POST /system/init` returns `202`, a second `POST` returns `409`, `GET /system/init/status` ends in `done` and `initialized: true`, a third `POST` returns `409`. No UI tests. + +### 4. Verification (containers, stand `ovpmon-test`, port 8089) +- Rebuild `app-profiler` and `app-ui`. Clear PKI, press Init PKI: spinner appears, the page can be reloaded and still shows progress, buttons are locked, the result appears on completion, Init PKI stays locked afterwards, Clear PKI unlocks it. +- Restart `ovp-profiler` during the run: status is `idle` and `initialized: false`, Init PKI cleans up and completes. +- Existing PKI from the current stand is detected as initialized. + +### 5. Documentation +- `DOCS/Profiler_Management/API_Reference.md` (new endpoints and `409` cases), `README.md`, `DOCS/General/Index.md`, summary `DOCS/Changes/2026-10-04_Async_PKI_Init.md`. Note for operators: single Profiler process is required (do not run several uvicorn workers). + +## Out of scope +Cancelling a running init, progress percentage, async Clear PKI, job history. diff --git a/DOCS/Changes/2026-10-04_Profile_Modal_Polish_PLAN.md b/DOCS/Changes/2026-10-04_Profile_Modal_Polish_PLAN.md new file mode 100644 index 0000000..99c5649 --- /dev/null +++ b/DOCS/Changes/2026-10-04_Profile_Modal_Polish_PLAN.md @@ -0,0 +1,29 @@ +# Compact profile modal and note tooltip: implementation plan (2026-10-04) + +Goal: (1) make the profile details modal compact with a balanced layout, (2) show the profile note in a tooltip when hovering over the client name in the Certificates list. UI only; no API or DB changes. + +## Steps + +### 1. Compact modal (`APP_UI/src/components/ProfileDetailsModal.vue`) +- Remove `modal-lg`: use the default Bootstrap width (500 px) and `modal-dialog-centered`; on phones it stays full width minus margins. +- Layout of the details block: a compact two-column "label : value" list (fixed narrow label column, value left-aligned right next to it) instead of two wide columns. Rows: Status, Created, Expires (with days remaining next to the date, e.g. `2027-01-10 (98 d)`), Revoked (only if set), File. +- Header: client name as the title with the status badge next to it; the separate "Client Name" and "Status" rows are removed. +- File path: single line, `text-break`, small muted font. +- Note: textarea with 3 rows, counter under it on the right; Save / Close buttons stay in the footer. +- Dates: one short format (`YYYY-MM-DD HH:mm`) instead of locale date plus time. + +### 2. Note tooltip (`APP_UI/src/views/Certificates.vue`) +- Hovering the username cell (both active and expired/revoked rows) shows a tooltip with the note text. No note: no tooltip. +- Implementation: Bootstrap Tooltip (already a dependency) via a small directive `v-note-tooltip="cert.note"` in `APP_UI/src/directives/` (create on mount, update the text when the note changes after saving, dispose on unmount). Options: `placement: 'top'`, `container: 'body'`, `html: false` (note is plain text, so no XSS), long text wrapped to a max width of about 320 px, line breaks preserved. +- Small note marker (`fa-note-sticky` icon, muted) next to the username when a note exists, so it is visible which clients have a note. +- Styles in `assets/main.css`: tooltip max width, `white-space: pre-wrap`, dark theme colours via existing variables. + +### 3. Verification (containers, no new tests) +- No new automated tests (UI only, no UI test infrastructure). +- Rebuild `app-ui` in the existing stand (`ovpmon-test`, port 8089) and check manually: modal width and layout in light and dark themes and on a narrow window; tooltip on active and revoked rows; tooltip text updates right after saving a note; no tooltip for clients without a note; long and multi-line notes. + +### 4. Documentation +- Summary appended to `DOCS/Changes/2026-10-04_Profile_Notes.md`; one line in the `README.md` changes table. + +## Out of scope +Showing the note as a table column, editing the note from the list, API changes. diff --git a/DOCS/Changes/2026-10-04_Profile_Notes.md b/DOCS/Changes/2026-10-04_Profile_Notes.md new file mode 100644 index 0000000..ebcb629 --- /dev/null +++ b/DOCS/Changes/2026-10-04_Profile_Notes.md @@ -0,0 +1,55 @@ +# Profile details modal and notes (2026-10-04) + +Goal: make rows on the **Certificates** page clickable; a click opens a modal with the main profile details and a note that can be saved. Plan: [Profile_Notes_PLAN](2026-10-04_Profile_Notes_PLAN.md). + +## Changes + +| Area | Change | +|---|---| +| Model (`APP_PROFILER/models.py`) | `UserProfile.note` (nullable `Text`) | +| Schemas (`APP_PROFILER/schemas.py`) | `note` in the profile response; `UserProfileNoteUpdate` (max 1000 chars, empty or whitespace-only becomes `null`) | +| Migration (`APP_PROFILER/database.py`, `main.py`) | `ensure_columns()` runs after `create_all` and adds `note` to an existing `user_profiles` table if missing (idempotent) | +| API (`APP_PROFILER/routers/profiles.py`) | `PUT /profiles/{id}/note` returns the updated profile; `404` if missing; JWT required. PUT is used because CORS does not allow PATCH | +| UI (`APP_UI/src/components/ProfileDetailsModal.vue`) | New modal on `BaseModal`: name, status, created, expiration, days remaining, revoked date, file path, note textarea with counter; Save is enabled only after a change | +| UI (`APP_UI/src/views/Certificates.vue`) | Rows (active and expired/revoked) open the modal; download/revoke buttons use `@click.stop`; `saveNote()` calls the API, shows a toast and reloads the list | +| Fix (`APP_PROFILER/requirements.txt`) | Added `requests`: `services/utils.py` imports it to detect the public IP, and creating a client failed with `No module named 'requests'` (HTTP 500, "Config Generation failed") when Public IP was not set in server settings. The failed attempts had already issued the certificate in PKI | +| Docs | `DOCS/Profiler_Management/API_Reference.md`: new endpoint and `note` field | +| Tests | `APP_PROFILER/test_profile_note.py` (one test), `APP_PROFILER/requirements-dev.txt` | + +## Verification (in containers) + +| Check | Result | +|---|---| +| `pytest test_profile_note.py` in `python:3.12-alpine` | 1 passed | +| `docker compose` build of all four images | OK | +| New DB: `note` column present | OK | +| Old-schema DB (no `note`): column added on start, data kept, second start is a no-op | OK | +| `PUT /profiles/{id}/note` with JWT | 200, note returned by `GET /profiles` | +| Without token / note over 1000 chars / unknown id | 401 / 422 / 404 | +| Whitespace-only note | stored as `null` | +| Browser check of the UI | manual (see below) | + +## Notes + +- Run the new test on its own (`cd APP_PROFILER && pip install -r requirements-dev.txt && pytest test_profile_note.py`): the older `test_server_process.py` also imports `main` with the default DB path. +- On a revoked row the Revoke button is disabled; some browsers do not pass a click on a disabled button to the row, so the modal may not open from that spot. Click elsewhere in the row. +- The modal closes right after Save; if the request fails the text is not kept. + +## Existing installations + +Rebuild the Profiler image so that `requests` is installed. A client name whose certificate was already issued by a failed attempt cannot be created again (Easy-RSA: certificate exists, HTTP 500); use another name or revoke/clear it in PKI. + +No manual steps: the `note` column is added on the next Profiler start (native: restart `ovpmon-profiler`; Docker: rebuild `app-profiler` and `app-ui`). Back up `ovpn_profiler.db` first. + +## Follow-up: compact modal and note tooltip (2026-10-04) + +Plan: [Profile_Modal_Polish_PLAN](2026-10-04_Profile_Modal_Polish_PLAN.md). UI only. + +| Area | Change | +|---|---| +| `ProfileDetailsModal.vue` | Default modal width (no `modal-lg`); name and status badge in the header; compact label : value list (Created, Expires with days remaining, Revoked, File); dates as `YYYY-MM-DD HH:mm`; 3-row note field | +| `directives/noteTooltip.js` | `v-note-tooltip`: Bootstrap Tooltip with the note text (plain text, hover, hidden on click); recreated when the note changes, disposed on unmount | +| `Certificates.vue` | Tooltip on the client cell in active and expired/revoked rows; muted note icon next to the name when a note exists | +| `main.css` | `.note-tooltip` (max width 320 px, line breaks kept, light/dark theme variables), `.profile-meta` grid | + +Verification: `app-ui` image builds, the note icon and tooltip styles are in the bundle; layout and tooltip behaviour are checked manually. diff --git a/DOCS/Changes/2026-10-04_Profile_Notes_PLAN.md b/DOCS/Changes/2026-10-04_Profile_Notes_PLAN.md new file mode 100644 index 0000000..5a4dd2d --- /dev/null +++ b/DOCS/Changes/2026-10-04_Profile_Notes_PLAN.md @@ -0,0 +1,29 @@ +# Profile details modal and notes: implementation plan (2026-10-04) + +Goal: on the **Certificates** page, rows become clickable. A click opens a modal with the main profile details and a free-text **note** that can be saved. Profiles have no note field today, so a minimal Profiler change is required to store it. + +## Steps + +### 1. Profiler backend (`APP_PROFILER/`) +- `models.py`: `UserProfile.note = Column(Text, nullable=True)`. +- `schemas.py`: `note: Optional[str]` in the response schema; new `UserProfileNoteUpdate` (max 1000 chars, empty string becomes `None`). +- Startup migration: idempotent "add column if missing" step (pattern from `APP_CORE/db.py`), so existing databases do not fail with `no such column`. +- `routers/profiles.py`: `PUT /profiles/{profile_id}/note` returns the updated profile; 404 if not found; JWT required (router-level `verify_token`). PUT is used because CORS does not allow PATCH. + +### 2. UI (`APP_UI/`) +- New `src/components/ProfileDetailsModal.vue` built on `BaseModal.vue` (pattern: `NewClientModal.vue`): username, status badge, created, expiration, days remaining, revoked date, file path, note textarea, Save / Close. +- `src/views/Certificates.vue`: clickable rows (active and expired/revoked), `@click.stop` on the download/revoke buttons, `saveNote()` via `profilesApiClient.put`, reload and toast. + +### 3. Tests (minimal) +- One pytest test in `APP_PROFILER`: `PUT /profiles/{id}/note` stores the note and `GET /profiles` returns it (temporary DB, auth dependency overridden). +- No UI tests (no test infrastructure in `APP_UI`). + +### 4. Build and verification (containers) +- Tests and build run in containers; the result is deployed with `docker-compose` on this host for manual checks. + +### 5. Documentation +- `DOCS/Profiler_Management/API_Reference.md`, `DOCS/General/Index.md`, `README.md` (Changes table). +- Summary of the work: `DOCS/Changes/2026-10-04_Profile_Notes.md` (written at the end). + +## Out of scope +Note history, per-user permissions, search by note, other pages. diff --git a/DOCS/General/Index.md b/DOCS/General/Index.md index c93c621..a5aa685 100644 --- a/DOCS/General/Index.md +++ b/DOCS/General/Index.md @@ -19,6 +19,8 @@ Welcome to the documentation for the OpenVPN Monitor suite. - [Settings validation (2026-09-30)](../Changes/2026-09-30_Settings_Validation.md) - [Privilege separation (2026-09-30)](../Changes/2026-09-30_Privilege_Separation.md) - [Egress via Hysteria2 (2026-09-30)](../Changes/2026-09-30_Egress_via_Hysteria2.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) ## 🔍 Core Monitoring (`APP_CORE`) The core module responsible for log parsing, real-time statistics, and the primary API. diff --git a/DOCS/Profiler_Management/API_Reference.md b/DOCS/Profiler_Management/API_Reference.md index 532485b..9d2d64f 100644 --- a/DOCS/Profiler_Management/API_Reference.md +++ b/DOCS/Profiler_Management/API_Reference.md @@ -18,17 +18,23 @@ Manage OpenVPN Client profiles (`.ovpn` configs and certificates). ### `GET /profiles` List all user profiles. -- **Response**: Array of profile objects (id, username, status, expiration_date, etc.). +- **Response**: Array of profile objects (id, username, status, expiration_date, note, etc.). ### `POST /profiles` Create a new user profile. - **Body**: `{"username": "jdoe"}` - **Action**: Generates keys, requests certificate, builds `.ovpn` file. +- **Response `409`**: PKI initialization is running (the PKI is not complete yet). ### `DELETE /profiles/{id}` Revoke a user profile. - **Action**: Revokes certificate in CRL and marks profile as revoked in DB. +### `PUT /profiles/{id}/note` +Set or clear the free-text note of a profile. +- **Body**: `{"note": "text"}` (max 1000 characters; empty or `null` clears the note) +- **Response**: Updated profile object (including `note`). `404` if the profile does not exist. + ### `GET /profiles/{id}/download` Download the `.ovpn` configuration file for a user. - **Response**: File stream (application/x-openvpn-profile). @@ -53,11 +59,20 @@ Update PKI settings (e.g., Key Size, Certificate Expiry). - **Body**: JSON object matching `PKISetting` schema. ### `POST /system/init` -Initialize the PKI infrastructure (InitCA, GenDH, BuildServerCert). -- **Note**: Only runs if PKI is empty. +Start PKI initialization (init-pki, CA, server certificate, DH, TLS key, CRL) as a background job. Returns immediately. +- **Response `202`**: `{"state": "running"}` +- **Response `409`**: a job is already running, or the PKI is already complete (`ca.crt`, `dh.pem`, `ta.key`, `crl.pem` and the server certificate). An incomplete PKI left by an interrupted run is removed and initialization starts again. +- **Note**: Job state is kept in memory; the Profiler must run as a single process (one uvicorn worker). After a restart the state is `idle`. + +### `GET /system/init/status` +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 }` +- `initialized` reflects the files on disk (complete PKI), independent of `state`. +- `error` contains the EasyRSA message when `state` is `error`. ### `DELETE /system/pki` -**DANGER**: Completely wipes the PKI directory. +**DANGER**: Completely wipes the PKI directory and resets the job state. +- **Response `409`**: an initialization job is running. --- diff --git a/README.md b/README.md index bd73ba8..bc84aa3 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,8 @@ No default user is created. Seed the initial admin with `OVPMON_INITIAL_ADMIN_US | 2026-09-30 | Validation of server/PKI settings (config injection into the root-written OpenVPN config) | [Settings validation](DOCS/Changes/2026-09-30_Settings_Validation.md) | | 2026-09-30 | API services run as an unprivileged user; root helper validates and installs the OpenVPN config, publishes the CRL | [Privilege separation](DOCS/Changes/2026-09-30_Privilege_Separation.md) (includes CRL publishing for `crl_verify`) | | 2026-09-30 | Route OpenVPN clients through a Hysteria2 tunnel to an exit node | [Egress via Hysteria2](DOCS/Changes/2026-09-30_Egress_via_Hysteria2.md) | +| 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) | ## Notes