Certificates: profile modal with notes, note tooltip; async PKI init
- Profiler: UserProfile.note (nullable, startup migration), PUT
/profiles/{id}/note (max 1000 chars); add missing `requests`
dependency (client creation failed without Public IP set).
- UI: clickable rows on Certificates open a compact profile details
modal with an editable note; tooltip with the note on the client
name (v-note-tooltip) and a note icon.
- PKI init runs in a background thread: POST /system/init returns 202,
GET /system/init/status, 409 for a second start, Clear PKI and client
creation are blocked while it runs. A marker file identifies an
interrupted run (only such a PKI is wiped on the next Init).
- PKI Configuration page: state from the server, progress spinner and
step text, polling, Init/Clear/Save locked while running, Init locked
once initialized.
- Tests: one pytest each for notes and async init (requirements-dev.txt).
- Docs: plans and summaries in DOCS/Changes, API reference, README, Index.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3836049230
commit
d251ec73d0
24 files changed
+722
-39
No files matched your search
@@ -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"))
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -0,0 +1,3 @@
|
||||
-r requirements.txt
|
||||
pytest
|
||||
httpx
|
||||
@@ -4,4 +4,5 @@ sqlalchemy
|
||||
psutil
|
||||
python-multipart
|
||||
jinja2
|
||||
pyjwt
|
||||
pyjwt
|
||||
requests
|
||||
@@ -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()
|
||||
|
||||
@@ -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}
|
||||
@@ -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
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -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"]
|
||||
Reference in new issue
Block a user