Compare commits
32
Commits
e1146ed4fe
..
main
No files matched your search
@@ -0,0 +1,38 @@
|
|||||||
|
# Build context of the all-in-one image (deploy/allinone/Dockerfile) is the repository root.
|
||||||
|
# The per-component images (docker-compose.yml) use ./APP_UI, ./APP_CORE, ./APP_PROFILER as
|
||||||
|
# their own contexts, so this file does not affect them.
|
||||||
|
|
||||||
|
# VCS, local environments, secrets
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
.claude
|
||||||
|
.env
|
||||||
|
**/.env
|
||||||
|
venv
|
||||||
|
**/venv
|
||||||
|
**/.venv
|
||||||
|
|
||||||
|
# Runtime data and local state: never part of an image
|
||||||
|
*.db
|
||||||
|
**/*.db
|
||||||
|
**/*.db.bak-*
|
||||||
|
**/easy-rsa
|
||||||
|
**/client-config
|
||||||
|
**/staging
|
||||||
|
backups
|
||||||
|
.ovpmon-*
|
||||||
|
**/*.log
|
||||||
|
|
||||||
|
# Build artefacts and caches
|
||||||
|
**/node_modules
|
||||||
|
**/dist
|
||||||
|
# the committed UI build of the system-service install (the all-in-one image builds the UI itself)
|
||||||
|
deploy/ui-dist
|
||||||
|
**/__pycache__
|
||||||
|
**/*.pyc
|
||||||
|
**/.pytest_cache
|
||||||
|
|
||||||
|
# Documentation and the compose files are not needed inside the image
|
||||||
|
DOCS
|
||||||
|
README.md
|
||||||
|
docker-compose*.yml
|
||||||
+12
@@ -1 +1,13 @@
|
|||||||
.DS_Store
|
.DS_Store
|
||||||
|
.env
|
||||||
|
backups/
|
||||||
|
.ovpmon-deploy
|
||||||
|
.ovpmon-lock/
|
||||||
|
# A UI tarball for another host is local; the committed UI build deploy/ui-dist/ (build-ui.sh --publish) must NOT be ignored
|
||||||
|
deploy/native/ui-dist.tar.gz
|
||||||
|
# Python caches (tests and compile steps create them inside the tree)
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
|
||||||
|
# local development environment
|
||||||
|
venv/
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Закоммиченная сборка UI (минифицированный JS) - шум для графа
|
||||||
|
deploy/ui-dist/assets/
|
||||||
|
|
||||||
|
# Site-specific records of one deployment (Timeweb host, Hysteria2 chain): not part of the product documentation
|
||||||
|
DEPLOYMENTS/
|
||||||
@@ -13,6 +13,7 @@ The **Core Monitoring** module provides the backend logic for collecting, extrac
|
|||||||
- A background service/daemon.
|
- A background service/daemon.
|
||||||
- Parses OpenVPN server logs (`status.log`).
|
- Parses OpenVPN server logs (`status.log`).
|
||||||
- Aggregates bandwidth usage into time-series tables (`usage_history`, `stats_hourly`, etc.).
|
- Aggregates bandwidth usage into time-series tables (`usage_history`, `stats_hourly`, etc.).
|
||||||
|
- Several simultaneous sessions of one user (`duplicate-cn`) are one record: traffic, speed and history are summed per common name; a session is identified by `Client ID` (see `DOCS/Core_Monitoring/Data_Architecture.md`).
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
@@ -26,6 +27,9 @@ python3 -m venv venv
|
|||||||
source venv/bin/activate
|
source venv/bin/activate
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# JWT key (required, no built-in default; at least 32 characters). Give the same value to APP_PROFILER
|
||||||
|
export OVPMON_API_SECRET_KEY=$(openssl rand -hex 32)
|
||||||
|
|
||||||
# Run API
|
# Run API
|
||||||
python3 openvpn_api_v3.py
|
python3 openvpn_api_v3.py
|
||||||
|
|
||||||
|
|||||||
+9
-1
@@ -2,12 +2,20 @@
|
|||||||
host = 0.0.0.0
|
host = 0.0.0.0
|
||||||
port = 5001
|
port = 5001
|
||||||
debug = false
|
debug = false
|
||||||
secret_key = ovpmon-secret-change-me
|
# Set OVPMON_API_SECRET_KEY or this value; at least 32 characters, random (openssl rand -hex 32). There is no built-in default.
|
||||||
|
secret_key =
|
||||||
|
|
||||||
[openvpn_monitor]
|
[openvpn_monitor]
|
||||||
log_path = /var/log/openvpn/openvpn-status.log
|
log_path = /var/log/openvpn/openvpn-status.log
|
||||||
db_path = openvpn_monitor.db
|
db_path = openvpn_monitor.db
|
||||||
check_interval = 10
|
check_interval = 10
|
||||||
|
# Optional gatherer reliability settings (defaults shown)
|
||||||
|
# ticks before a session missing from the status file is forgotten
|
||||||
|
session_grace_ticks = 3
|
||||||
|
# status file older than this (TIME line) means OpenVPN is stopped, no clients
|
||||||
|
status_stale_seconds = 60
|
||||||
|
# consecutive skipped ticks (bad/missing status file) before logging at ERROR
|
||||||
|
status_invalid_max = 6
|
||||||
|
|
||||||
[logging]
|
[logging]
|
||||||
level = INFO
|
level = INFO
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
# The API refuses to start without a strong JWT key (no built-in default), and tests import the
|
||||||
|
# application: give them a throwaway key before anything is imported. A real key in the
|
||||||
|
# environment is left untouched.
|
||||||
|
os.environ.setdefault("OVPMON_API_SECRET_KEY", "x" * 64)
|
||||||
+7
-110
@@ -3,6 +3,8 @@ import configparser
|
|||||||
import os
|
import os
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
import migrations
|
||||||
|
|
||||||
class DatabaseManager:
|
class DatabaseManager:
|
||||||
def __init__(self, config_file='config.ini'):
|
def __init__(self, config_file='config.ini'):
|
||||||
self.config_file = config_file
|
self.config_file = config_file
|
||||||
@@ -26,7 +28,7 @@ class DatabaseManager:
|
|||||||
return sqlite3.connect(self.db_path)
|
return sqlite3.connect(self.db_path)
|
||||||
|
|
||||||
def init_database(self):
|
def init_database(self):
|
||||||
"""Initialize the database schema"""
|
"""Initialize the database schema (applies pending migrations)"""
|
||||||
# Create directory if needed
|
# Create directory if needed
|
||||||
db_dir = os.path.dirname(self.db_path)
|
db_dir = os.path.dirname(self.db_path)
|
||||||
if db_dir and not os.path.exists(db_dir):
|
if db_dir and not os.path.exists(db_dir):
|
||||||
@@ -37,112 +39,7 @@ class DatabaseManager:
|
|||||||
|
|
||||||
self.logger.info(f"Using database: {self.db_path}")
|
self.logger.info(f"Using database: {self.db_path}")
|
||||||
|
|
||||||
conn = self.get_connection()
|
# Schema creation and upgrades live in migrations.py (versioned, with a backup before
|
||||||
cursor = conn.cursor()
|
# any change). Exits with a clear message if the database is newer than this code or
|
||||||
|
# migrations are pending while OVPMON_AUTO_MIGRATE=0.
|
||||||
def _column_exists(table, column):
|
migrations.startup_or_exit(self.db_path)
|
||||||
cursor.execute(f"PRAGMA table_info({table})")
|
|
||||||
return any(row[1] == column for row in cursor.fetchall())
|
|
||||||
|
|
||||||
def _ensure_column(table, column, type_def):
|
|
||||||
if not _column_exists(table, column):
|
|
||||||
self.logger.info(f"Adding missing column {column} to table {table}")
|
|
||||||
cursor.execute(f"ALTER TABLE {table} ADD COLUMN {column} {type_def}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 1. Clients Table
|
|
||||||
cursor.execute('''
|
|
||||||
CREATE TABLE IF NOT EXISTS clients (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
common_name TEXT UNIQUE NOT NULL,
|
|
||||||
real_address TEXT,
|
|
||||||
status TEXT DEFAULT 'Active',
|
|
||||||
total_bytes_received INTEGER DEFAULT 0,
|
|
||||||
total_bytes_sent INTEGER DEFAULT 0,
|
|
||||||
last_bytes_received INTEGER DEFAULT 0,
|
|
||||||
last_bytes_sent INTEGER DEFAULT 0,
|
|
||||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
||||||
)
|
|
||||||
''')
|
|
||||||
|
|
||||||
# 2. Raw Usage History
|
|
||||||
cursor.execute('''
|
|
||||||
CREATE TABLE IF NOT EXISTS usage_history (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
client_id INTEGER,
|
|
||||||
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
bytes_received INTEGER,
|
|
||||||
bytes_sent INTEGER,
|
|
||||||
bytes_received_rate_mbps REAL,
|
|
||||||
bytes_sent_rate_mbps REAL,
|
|
||||||
FOREIGN KEY (client_id) REFERENCES clients (id)
|
|
||||||
)
|
|
||||||
''')
|
|
||||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_usage_ts ON usage_history(timestamp)')
|
|
||||||
|
|
||||||
# 2.1 Active Sessions (Temporary state table)
|
|
||||||
cursor.execute('''
|
|
||||||
CREATE TABLE IF NOT EXISTS active_sessions (
|
|
||||||
client_id INTEGER,
|
|
||||||
common_name TEXT,
|
|
||||||
real_address TEXT,
|
|
||||||
bytes_received INTEGER,
|
|
||||||
bytes_sent INTEGER,
|
|
||||||
connected_since TIMESTAMP,
|
|
||||||
last_seen TIMESTAMP,
|
|
||||||
FOREIGN KEY (client_id) REFERENCES clients (id)
|
|
||||||
)
|
|
||||||
''')
|
|
||||||
|
|
||||||
# 2.2 Users and Auth
|
|
||||||
cursor.execute('''
|
|
||||||
CREATE TABLE IF NOT EXISTS users (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
username TEXT UNIQUE NOT NULL,
|
|
||||||
password_hash TEXT NOT NULL,
|
|
||||||
totp_secret TEXT,
|
|
||||||
is_2fa_enabled INTEGER DEFAULT 0,
|
|
||||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
||||||
)
|
|
||||||
''')
|
|
||||||
|
|
||||||
# 2.3 Login Attempts (Brute-force protection)
|
|
||||||
cursor.execute('''
|
|
||||||
CREATE TABLE IF NOT EXISTS login_attempts (
|
|
||||||
ip_address TEXT PRIMARY KEY,
|
|
||||||
attempts INTEGER DEFAULT 0,
|
|
||||||
last_attempt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
||||||
)
|
|
||||||
''')
|
|
||||||
|
|
||||||
# 3. Aggregated Stats Tables
|
|
||||||
tables = ['stats_5min', 'stats_15min', 'stats_hourly', 'stats_6h', 'stats_daily']
|
|
||||||
|
|
||||||
for table in tables:
|
|
||||||
cursor.execute(f'''
|
|
||||||
CREATE TABLE IF NOT EXISTS {table} (
|
|
||||||
timestamp TEXT NOT NULL,
|
|
||||||
client_id INTEGER NOT NULL,
|
|
||||||
bytes_received INTEGER DEFAULT 0,
|
|
||||||
bytes_sent INTEGER DEFAULT 0,
|
|
||||||
PRIMARY KEY (timestamp, client_id),
|
|
||||||
FOREIGN KEY (client_id) REFERENCES clients (id)
|
|
||||||
)
|
|
||||||
''')
|
|
||||||
cursor.execute(f'CREATE INDEX IF NOT EXISTS idx_{table}_ts ON {table}(timestamp)')
|
|
||||||
|
|
||||||
# 4. Migrations (Ensure columns in existing tables)
|
|
||||||
# If users table existed but was old, ensure it has 2FA columns
|
|
||||||
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users'")
|
|
||||||
if cursor.fetchone():
|
|
||||||
_ensure_column('users', 'totp_secret', 'TEXT')
|
|
||||||
_ensure_column('users', 'is_2fa_enabled', 'INTEGER DEFAULT 0')
|
|
||||||
|
|
||||||
conn.commit()
|
|
||||||
self.logger.info("Database initialized with full schema and migrations")
|
|
||||||
except Exception as e:
|
|
||||||
self.logger.error(f"Database initialization error: {e}")
|
|
||||||
finally:
|
|
||||||
conn.close()
|
|
||||||
Executable
+67
@@ -0,0 +1,67 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Apply pending database migrations (or only check for them).
|
||||||
|
|
||||||
|
python migrate.py apply pending migrations (backup first)
|
||||||
|
python migrate.py --check only report; exit 0 = up to date, 2 = pending, 1 = error / too new
|
||||||
|
python migrate.py --db PATH use this database file instead of the configured one
|
||||||
|
|
||||||
|
Run it from the component directory with the component's virtualenv, like the service.
|
||||||
|
The services apply pending migrations themselves at start (unless OVPMON_AUTO_MIGRATE=0).
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import migrations
|
||||||
|
from db import DatabaseManager
|
||||||
|
|
||||||
|
EXIT_OK, EXIT_ERROR, EXIT_PENDING = 0, 1, 2
|
||||||
|
|
||||||
|
|
||||||
|
def default_db_path():
|
||||||
|
return DatabaseManager().db_path
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
parser = argparse.ArgumentParser(description="Database schema migrations")
|
||||||
|
parser.add_argument("--check", action="store_true",
|
||||||
|
help="only report: exit 0 = up to date, 2 = pending, 1 = error")
|
||||||
|
parser.add_argument("--db", metavar="PATH", help="database file (default: from configuration)")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
|
||||||
|
db_path = args.db or default_db_path()
|
||||||
|
|
||||||
|
try:
|
||||||
|
st = migrations.status(db_path)
|
||||||
|
if st.too_new:
|
||||||
|
raise migrations._too_new_error(st)
|
||||||
|
print(f"Database: {db_path}" + ("" if st.exists else " (does not exist yet)"))
|
||||||
|
if not st.exists and not args.db:
|
||||||
|
print("Hint: the default database was used; for an installed system set OVPMON_OPENVPN_MONITOR_DB_PATH "
|
||||||
|
"(see /etc/ovpmon/env) or pass --db PATH")
|
||||||
|
if args.check:
|
||||||
|
print(f"Schema version: {st.current} (latest known: {migrations.latest_version()})")
|
||||||
|
if not st.pending:
|
||||||
|
print("Pending: none, up to date")
|
||||||
|
return EXIT_OK
|
||||||
|
print("Pending: " + ", ".join(f"{m.version} ({m.name})" for m in st.pending))
|
||||||
|
return EXIT_PENDING
|
||||||
|
before = st.current
|
||||||
|
report = migrations.run(db_path)
|
||||||
|
except migrations.MigrationError as e:
|
||||||
|
print(f"ERROR: {e}", file=sys.stderr)
|
||||||
|
return EXIT_ERROR
|
||||||
|
|
||||||
|
print(f"Schema version: {before} -> {report.version}")
|
||||||
|
if report.applied:
|
||||||
|
print("Applied: " + ", ".join(f"{v} ({n})" for v, n in report.applied))
|
||||||
|
else:
|
||||||
|
print("Applied: nothing, already up to date")
|
||||||
|
print(f"Backup: {report.backup or 'none'}"
|
||||||
|
+ (" (new database)" if report.created else ""))
|
||||||
|
return EXIT_OK
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,476 @@
|
|||||||
|
"""Versioned, additive-only schema migrations for the component's SQLite database.
|
||||||
|
|
||||||
|
The generic part (everything above "Migrations of this component") is the same in
|
||||||
|
APP_CORE/migrations.py and APP_PROFILER/migrations.py: the components have separate
|
||||||
|
build contexts and virtualenvs, so each carries its own copy. Keep them in sync.
|
||||||
|
|
||||||
|
Safety rules:
|
||||||
|
- a migration only adds (tables, columns, indexes); it never drops or rewrites data;
|
||||||
|
- before the first change a consistent backup is made with the SQLite backup API
|
||||||
|
('<db>.bak-<UTC timestamp>'), unless the database is brand new;
|
||||||
|
- every migration runs in its own savepoint inside one write-locked transaction, so
|
||||||
|
two processes starting at the same time cannot race (the second one waits, then
|
||||||
|
finds nothing pending);
|
||||||
|
- afterwards PRAGMA integrity_check and the row counts of all pre-existing tables are
|
||||||
|
compared with the backup; on a mismatch everything is rolled back;
|
||||||
|
- a database with a higher schema version than the code knows is never touched.
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sqlite3
|
||||||
|
import stat
|
||||||
|
import sys
|
||||||
|
import urllib.parse
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Callable, Optional
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
BACKUPS_KEEP = 5 # number of '<db>.bak-*' files kept per database
|
||||||
|
LOCK_TIMEOUT = 60 # seconds a second process waits for the migration lock
|
||||||
|
|
||||||
|
|
||||||
|
class MigrationError(Exception):
|
||||||
|
"""A migration could not be applied or verified."""
|
||||||
|
|
||||||
|
|
||||||
|
class SchemaTooNew(MigrationError):
|
||||||
|
"""The database was migrated by a newer release than this code."""
|
||||||
|
|
||||||
|
|
||||||
|
class MigrationPending(MigrationError):
|
||||||
|
"""Migrations are pending but automatic migration is disabled."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Migration:
|
||||||
|
version: int
|
||||||
|
name: str
|
||||||
|
apply: Callable[[sqlite3.Connection], None] # runs inside a transaction, no commit
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Status:
|
||||||
|
db_path: str
|
||||||
|
exists: bool
|
||||||
|
fresh: bool # no tables and no recorded migrations
|
||||||
|
applied: dict = field(default_factory=dict) # version -> name
|
||||||
|
pending: list = field(default_factory=list) # [Migration]
|
||||||
|
too_new: Optional[int] = None # highest version if above the code's
|
||||||
|
|
||||||
|
@property
|
||||||
|
def current(self):
|
||||||
|
return max(self.applied) if self.applied else 0
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Report:
|
||||||
|
db_path: str
|
||||||
|
version: int # schema version after the run
|
||||||
|
applied: list = field(default_factory=list) # [(version, name)] applied by this run
|
||||||
|
backup: Optional[str] = None
|
||||||
|
created: bool = False # the database was new and got the current schema
|
||||||
|
|
||||||
|
|
||||||
|
def latest_version():
|
||||||
|
return max((m.version for m in MIGRATIONS), default=0)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_path(target):
|
||||||
|
"""Accept a path or a SQLAlchemy engine."""
|
||||||
|
if isinstance(target, (str, os.PathLike)):
|
||||||
|
return os.fspath(target)
|
||||||
|
url = getattr(target, "url", None)
|
||||||
|
if url is not None and url.database:
|
||||||
|
return url.database
|
||||||
|
raise TypeError(f"Cannot get a database path from {target!r}")
|
||||||
|
|
||||||
|
|
||||||
|
def _quote(name):
|
||||||
|
return '"' + name.replace('"', '""') + '"'
|
||||||
|
|
||||||
|
|
||||||
|
def _tables(conn):
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT name FROM sqlite_master WHERE type='table' "
|
||||||
|
"AND substr(name, 1, 7) != 'sqlite_' ORDER BY name")
|
||||||
|
return [r[0] for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def _read_status(conn, db_path):
|
||||||
|
tables = _tables(conn)
|
||||||
|
applied = {}
|
||||||
|
if "schema_migrations" in tables:
|
||||||
|
applied = {v: n for v, n in conn.execute("SELECT version, name FROM schema_migrations")}
|
||||||
|
known = latest_version()
|
||||||
|
too_new = max(applied) if applied and max(applied) > known else None
|
||||||
|
pending = sorted((m for m in MIGRATIONS if m.version not in applied), key=lambda m: m.version)
|
||||||
|
fresh = not [t for t in tables if t != "schema_migrations"] and not applied
|
||||||
|
return Status(db_path, True, fresh, applied, pending, too_new)
|
||||||
|
|
||||||
|
|
||||||
|
def _too_new_error(st):
|
||||||
|
return SchemaTooNew(
|
||||||
|
f"Database {st.db_path} has schema version {st.too_new}, but this release only knows "
|
||||||
|
f"versions up to {latest_version()}. It was migrated by a newer release. The database "
|
||||||
|
f"has not been touched and the service will not start. Install the newer release, or "
|
||||||
|
f"restore a matching backup ('{st.db_path}.bak-*') with the services stopped.")
|
||||||
|
|
||||||
|
|
||||||
|
def _quick_status(db_path):
|
||||||
|
"""Read-only look at the database, no lock and no changes. None if it cannot be read."""
|
||||||
|
if not os.path.exists(db_path):
|
||||||
|
return Status(db_path, False, True, {}, sorted(MIGRATIONS, key=lambda m: m.version))
|
||||||
|
uri = "file:%s?mode=ro" % urllib.parse.quote(os.path.abspath(db_path))
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(uri, uri=True, timeout=LOCK_TIMEOUT)
|
||||||
|
try:
|
||||||
|
return _read_status(conn, db_path)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
except sqlite3.Error:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def status(target):
|
||||||
|
"""Report applied and pending migrations without changing anything."""
|
||||||
|
db_path = _resolve_path(target)
|
||||||
|
st = _quick_status(db_path)
|
||||||
|
if st is None:
|
||||||
|
raise MigrationError(f"Cannot read database {db_path} (not a SQLite database, or locked)")
|
||||||
|
return st
|
||||||
|
|
||||||
|
|
||||||
|
def _integrity_problems(conn):
|
||||||
|
rows = [r[0] for r in conn.execute("PRAGMA integrity_check")]
|
||||||
|
return [] if rows == ["ok"] else rows[:5]
|
||||||
|
|
||||||
|
|
||||||
|
def _row_counts(conn):
|
||||||
|
return {t: conn.execute(f"SELECT COUNT(*) FROM {_quote(t)}").fetchone()[0]
|
||||||
|
for t in _tables(conn)}
|
||||||
|
|
||||||
|
|
||||||
|
def _backup(conn, db_path):
|
||||||
|
"""Consistent copy through the SQLite backup API. Returns (path, row counts of the copy)."""
|
||||||
|
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
|
||||||
|
dest = f"{db_path}.bak-{stamp}"
|
||||||
|
n = 0
|
||||||
|
while os.path.exists(dest):
|
||||||
|
n += 1
|
||||||
|
dest = f"{db_path}.bak-{stamp}-{n}"
|
||||||
|
tmp = dest + ".part"
|
||||||
|
try:
|
||||||
|
dst = sqlite3.connect(tmp)
|
||||||
|
# A separate read-only connection: the backup API stalls when the source connection
|
||||||
|
# itself holds the write lock. Nothing has been modified yet, so the copy is consistent.
|
||||||
|
src = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=LOCK_TIMEOUT)
|
||||||
|
try:
|
||||||
|
src.backup(dst)
|
||||||
|
problems = _integrity_problems(dst)
|
||||||
|
if problems:
|
||||||
|
raise MigrationError("backup copy failed the integrity check: " + "; ".join(problems))
|
||||||
|
counts = _row_counts(dst)
|
||||||
|
finally:
|
||||||
|
src.close()
|
||||||
|
dst.close()
|
||||||
|
# The copy holds the same secrets as the database: same permissions
|
||||||
|
os.chmod(tmp, stat.S_IMODE(os.stat(db_path).st_mode))
|
||||||
|
os.replace(tmp, dest)
|
||||||
|
except Exception as e:
|
||||||
|
try:
|
||||||
|
os.remove(tmp)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
raise MigrationError(f"Cannot back up {db_path} ({e}). Nothing was changed.") from e
|
||||||
|
logger.info(f"Database backup created: {dest}")
|
||||||
|
return dest, counts
|
||||||
|
|
||||||
|
|
||||||
|
def _prune_backups(db_path, keep=BACKUPS_KEEP):
|
||||||
|
"""Keep the newest `keep` backups of this database only."""
|
||||||
|
directory = os.path.dirname(os.path.abspath(db_path))
|
||||||
|
pattern = re.compile(re.escape(os.path.basename(db_path)) + r"\.bak-(\d{8}T\d{6})(?:-(\d+))?$")
|
||||||
|
found = []
|
||||||
|
for name in os.listdir(directory):
|
||||||
|
m = pattern.match(name)
|
||||||
|
if m:
|
||||||
|
found.append((m.group(1), int(m.group(2) or 0), name))
|
||||||
|
found.sort()
|
||||||
|
for _, _, name in (found[:-keep] if keep > 0 else found):
|
||||||
|
try:
|
||||||
|
os.remove(os.path.join(directory, name))
|
||||||
|
logger.info(f"Old database backup removed: {name}")
|
||||||
|
except OSError as e:
|
||||||
|
logger.warning(f"Cannot remove old backup {name}: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
def _stamp(conn, migration):
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",
|
||||||
|
(migration.version, migration.name,
|
||||||
|
datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")))
|
||||||
|
|
||||||
|
|
||||||
|
def run(target, fresh_schema=None):
|
||||||
|
"""Apply pending migrations to the database (path or SQLAlchemy engine).
|
||||||
|
|
||||||
|
fresh_schema(conn), if given, creates the complete current schema of a brand-new
|
||||||
|
database; all migrations are then recorded as applied without running them.
|
||||||
|
Raises SchemaTooNew / MigrationError; returns a Report."""
|
||||||
|
db_path = _resolve_path(target)
|
||||||
|
if fresh_schema is None:
|
||||||
|
fresh_schema = FRESH_SCHEMA
|
||||||
|
|
||||||
|
# Fast path: nothing to do, no lock, no write
|
||||||
|
st = _quick_status(db_path)
|
||||||
|
if st is not None:
|
||||||
|
if st.too_new:
|
||||||
|
raise _too_new_error(st)
|
||||||
|
if not st.pending:
|
||||||
|
return Report(db_path, st.current)
|
||||||
|
|
||||||
|
db_dir = os.path.dirname(db_path)
|
||||||
|
if db_dir:
|
||||||
|
os.makedirs(db_dir, exist_ok=True)
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(db_path, timeout=LOCK_TIMEOUT, isolation_level=None)
|
||||||
|
try:
|
||||||
|
report = _run_locked(conn, db_path, fresh_schema)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
except sqlite3.Error as e:
|
||||||
|
raise MigrationError(f"Database error while migrating {db_path}: {e}") from e
|
||||||
|
if report.backup:
|
||||||
|
_prune_backups(db_path)
|
||||||
|
return report
|
||||||
|
|
||||||
|
|
||||||
|
def _run_locked(conn, db_path, fresh_schema):
|
||||||
|
# The write lock is taken before anything is read or changed: a second process
|
||||||
|
# waits here, and then finds nothing pending (and makes no second backup)
|
||||||
|
conn.execute("BEGIN IMMEDIATE")
|
||||||
|
try:
|
||||||
|
st = _read_status(conn, db_path)
|
||||||
|
if st.too_new:
|
||||||
|
raise _too_new_error(st)
|
||||||
|
if not st.pending:
|
||||||
|
conn.execute("ROLLBACK")
|
||||||
|
return Report(db_path, st.current)
|
||||||
|
|
||||||
|
problems = _integrity_problems(conn)
|
||||||
|
if problems:
|
||||||
|
raise MigrationError(
|
||||||
|
f"Integrity check failed for {db_path}: {'; '.join(problems)}. Nothing was changed.")
|
||||||
|
|
||||||
|
backup, before = None, {}
|
||||||
|
if not st.fresh:
|
||||||
|
backup, before = _backup(conn, db_path)
|
||||||
|
where = f"backup: {backup}" if backup else "new database, no backup needed"
|
||||||
|
|
||||||
|
conn.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS schema_migrations ("
|
||||||
|
"version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT)")
|
||||||
|
applied = []
|
||||||
|
if st.fresh and fresh_schema is not None:
|
||||||
|
fresh_schema(conn)
|
||||||
|
for m in st.pending:
|
||||||
|
_stamp(conn, m)
|
||||||
|
applied.append((m.version, m.name))
|
||||||
|
else:
|
||||||
|
for m in st.pending:
|
||||||
|
logger.info(f"Applying migration {m.version} ({m.name}) to {db_path}")
|
||||||
|
conn.execute("SAVEPOINT migration")
|
||||||
|
try:
|
||||||
|
m.apply(conn)
|
||||||
|
_stamp(conn, m)
|
||||||
|
except Exception as e:
|
||||||
|
conn.execute("ROLLBACK TO migration")
|
||||||
|
conn.execute("RELEASE migration")
|
||||||
|
# Migrations completed before this one stay (each is complete in itself)
|
||||||
|
conn.execute("COMMIT" if applied else "ROLLBACK")
|
||||||
|
raise MigrationError(
|
||||||
|
f"Migration {m.version} ({m.name}) failed and was rolled back: {e} "
|
||||||
|
f"[{where}]. The service will not start; fix the cause and run migrate.py "
|
||||||
|
f"again.") from e
|
||||||
|
conn.execute("RELEASE migration")
|
||||||
|
applied.append((m.version, m.name))
|
||||||
|
|
||||||
|
# Verify before the commit: on any mismatch nothing is kept
|
||||||
|
problems = _integrity_problems(conn)
|
||||||
|
if problems:
|
||||||
|
raise MigrationError(
|
||||||
|
f"Integrity check failed after migration of {db_path}: {'; '.join(problems)}. "
|
||||||
|
f"The changes were rolled back. Backup: {backup or 'none (new database)'}")
|
||||||
|
after = _row_counts(conn)
|
||||||
|
for table, count in before.items():
|
||||||
|
if table == "schema_migrations":
|
||||||
|
continue # the bookkeeping table is expected to grow
|
||||||
|
if after.get(table) != count:
|
||||||
|
raise MigrationError(
|
||||||
|
f"Row count of table '{table}' changed during migration ({count} -> "
|
||||||
|
f"{after.get(table)}) in {db_path}. The changes were rolled back. "
|
||||||
|
f"Backup: {backup}")
|
||||||
|
|
||||||
|
conn.execute("COMMIT")
|
||||||
|
for version, name in applied:
|
||||||
|
logger.info(f"Migration {version} ({name}) applied to {db_path} [{where}]")
|
||||||
|
return Report(db_path, applied[-1][0], applied, backup, st.fresh)
|
||||||
|
except BaseException:
|
||||||
|
if conn.in_transaction:
|
||||||
|
conn.execute("ROLLBACK")
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def startup(target, fresh_schema=None):
|
||||||
|
"""Called when a service starts. Applies pending migrations, or, with
|
||||||
|
OVPMON_AUTO_MIGRATE=0, only checks and refuses while any are pending."""
|
||||||
|
db_path = _resolve_path(target)
|
||||||
|
if os.getenv("OVPMON_AUTO_MIGRATE", "1").strip() == "0":
|
||||||
|
st = status(db_path)
|
||||||
|
if st.too_new:
|
||||||
|
raise _too_new_error(st)
|
||||||
|
if st.pending:
|
||||||
|
names = ", ".join(f"{m.version} ({m.name})" for m in st.pending)
|
||||||
|
raise MigrationPending(
|
||||||
|
f"Database {db_path} is at schema version {st.current}, pending migrations: "
|
||||||
|
f"{names}. Automatic migration is disabled (OVPMON_AUTO_MIGRATE=0): run "
|
||||||
|
f"'python migrate.py' first.")
|
||||||
|
return Report(db_path, st.current)
|
||||||
|
report = run(target, fresh_schema)
|
||||||
|
logger.info(f"Database {db_path}: schema version {report.version}")
|
||||||
|
return report
|
||||||
|
|
||||||
|
|
||||||
|
def startup_or_exit(target, fresh_schema=None):
|
||||||
|
"""startup() for service entry points: a clear message and a non-zero exit
|
||||||
|
instead of a traceback when the database must not be used."""
|
||||||
|
try:
|
||||||
|
return startup(target, fresh_schema)
|
||||||
|
except MigrationError as e:
|
||||||
|
logger.critical(str(e))
|
||||||
|
print(f"FATAL: {e}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
# --- Migrations of this component -------------------------------------------
|
||||||
|
|
||||||
|
def _m001_baseline(conn):
|
||||||
|
"""Schema of the releases before versioning (formerly DatabaseManager.init_database):
|
||||||
|
CREATE TABLE IF NOT EXISTS plus the 'add column if missing' steps. Idempotent."""
|
||||||
|
|
||||||
|
def _column_exists(table, column):
|
||||||
|
return any(row[1] == column for row in conn.execute(f"PRAGMA table_info({table})"))
|
||||||
|
|
||||||
|
def _ensure_column(table, column, type_def):
|
||||||
|
if not _column_exists(table, column):
|
||||||
|
logger.info(f"Adding missing column {column} to table {table}")
|
||||||
|
conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {type_def}")
|
||||||
|
|
||||||
|
# 1. Clients Table
|
||||||
|
conn.execute('''
|
||||||
|
CREATE TABLE IF NOT EXISTS clients (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
common_name TEXT UNIQUE NOT NULL,
|
||||||
|
real_address TEXT,
|
||||||
|
status TEXT DEFAULT 'Active',
|
||||||
|
total_bytes_received INTEGER DEFAULT 0,
|
||||||
|
total_bytes_sent INTEGER DEFAULT 0,
|
||||||
|
last_bytes_received INTEGER DEFAULT 0,
|
||||||
|
last_bytes_sent INTEGER DEFAULT 0,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
''')
|
||||||
|
|
||||||
|
# 2. Raw Usage History
|
||||||
|
conn.execute('''
|
||||||
|
CREATE TABLE IF NOT EXISTS usage_history (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
client_id INTEGER,
|
||||||
|
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
bytes_received INTEGER,
|
||||||
|
bytes_sent INTEGER,
|
||||||
|
bytes_received_rate_mbps REAL,
|
||||||
|
bytes_sent_rate_mbps REAL,
|
||||||
|
FOREIGN KEY (client_id) REFERENCES clients (id)
|
||||||
|
)
|
||||||
|
''')
|
||||||
|
conn.execute('CREATE INDEX IF NOT EXISTS idx_usage_ts ON usage_history(timestamp)')
|
||||||
|
|
||||||
|
# 2.1 Active Sessions (Temporary state table)
|
||||||
|
conn.execute('''
|
||||||
|
CREATE TABLE IF NOT EXISTS active_sessions (
|
||||||
|
client_id INTEGER,
|
||||||
|
common_name TEXT,
|
||||||
|
real_address TEXT,
|
||||||
|
bytes_received INTEGER,
|
||||||
|
bytes_sent INTEGER,
|
||||||
|
connected_since TIMESTAMP,
|
||||||
|
last_seen TIMESTAMP,
|
||||||
|
FOREIGN KEY (client_id) REFERENCES clients (id)
|
||||||
|
)
|
||||||
|
''')
|
||||||
|
|
||||||
|
# 2.2 Users and Auth
|
||||||
|
conn.execute('''
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
username TEXT UNIQUE NOT NULL,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
totp_secret TEXT,
|
||||||
|
is_2fa_enabled INTEGER DEFAULT 0,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
''')
|
||||||
|
|
||||||
|
# 2.3 Login Attempts (Brute-force protection)
|
||||||
|
conn.execute('''
|
||||||
|
CREATE TABLE IF NOT EXISTS login_attempts (
|
||||||
|
ip_address TEXT PRIMARY KEY,
|
||||||
|
attempts INTEGER DEFAULT 0,
|
||||||
|
last_attempt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
''')
|
||||||
|
|
||||||
|
# 3. Aggregated Stats Tables
|
||||||
|
tables = ['stats_5min', 'stats_15min', 'stats_hourly', 'stats_6h', 'stats_daily']
|
||||||
|
|
||||||
|
for table in tables:
|
||||||
|
conn.execute(f'''
|
||||||
|
CREATE TABLE IF NOT EXISTS {table} (
|
||||||
|
timestamp TEXT NOT NULL,
|
||||||
|
client_id INTEGER NOT NULL,
|
||||||
|
bytes_received INTEGER DEFAULT 0,
|
||||||
|
bytes_sent INTEGER DEFAULT 0,
|
||||||
|
PRIMARY KEY (timestamp, client_id),
|
||||||
|
FOREIGN KEY (client_id) REFERENCES clients (id)
|
||||||
|
)
|
||||||
|
''')
|
||||||
|
conn.execute(f'CREATE INDEX IF NOT EXISTS idx_{table}_ts ON {table}(timestamp)')
|
||||||
|
|
||||||
|
# 4. Migrations (Ensure columns in existing tables)
|
||||||
|
# If users table existed but was old, ensure it has 2FA columns
|
||||||
|
if conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users'").fetchone():
|
||||||
|
_ensure_column('users', 'totp_secret', 'TEXT')
|
||||||
|
_ensure_column('users', 'is_2fa_enabled', 'INTEGER DEFAULT 0')
|
||||||
|
|
||||||
|
|
||||||
|
def _m002_session_id(conn):
|
||||||
|
"""active_sessions.session_id: the Client ID of the session from the OpenVPN v2 status
|
||||||
|
(part of the gatherer's session key). NULL is allowed: rows of an old snapshot and a
|
||||||
|
status without the Client ID column."""
|
||||||
|
if not any(row[1] == "session_id" for row in conn.execute("PRAGMA table_info(active_sessions)")):
|
||||||
|
conn.execute("ALTER TABLE active_sessions ADD COLUMN session_id TEXT")
|
||||||
|
|
||||||
|
|
||||||
|
MIGRATIONS = [
|
||||||
|
Migration(1, "baseline", _m001_baseline),
|
||||||
|
Migration(2, "session_id", _m002_session_id),
|
||||||
|
]
|
||||||
|
|
||||||
|
# No separate "fresh" schema: the baseline migration creates everything on a new database
|
||||||
|
FRESH_SCHEMA = None
|
||||||
+96
-21
@@ -10,6 +10,7 @@ import pyotp
|
|||||||
import bcrypt
|
import bcrypt
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
from db import DatabaseManager
|
from db import DatabaseManager
|
||||||
|
from secret_key import resolve_secret_key, SecretKeyError
|
||||||
|
|
||||||
|
|
||||||
import io
|
import io
|
||||||
@@ -28,6 +29,29 @@ app = Flask(__name__)
|
|||||||
# Cross-origin access is off by default (the UI is same-origin behind Nginx); allow extra origins via OVPMON_CORS_ORIGINS (comma-separated)
|
# Cross-origin access is off by default (the UI is same-origin behind Nginx); allow extra origins via OVPMON_CORS_ORIGINS (comma-separated)
|
||||||
CORS(app, resources={r"/api/*": {"origins": [o.strip() for o in os.getenv("OVPMON_CORS_ORIGINS", "").split(",") if o.strip()]}}, supports_credentials=True)
|
CORS(app, resources={r"/api/*": {"origins": [o.strip() for o in os.getenv("OVPMON_CORS_ORIGINS", "").split(",") if o.strip()]}}, supports_credentials=True)
|
||||||
|
|
||||||
|
# Length of one bucket of the aggregate tables, seconds. The aggregates hold only bytes, so for periods
|
||||||
|
# longer than a day the speed is the bucket average: bytes * 8 / 1e6 / bucket duration.
|
||||||
|
BUCKET_SECONDS = {
|
||||||
|
'stats_5min': 300,
|
||||||
|
'stats_15min': 900,
|
||||||
|
'stats_hourly': 3600,
|
||||||
|
'stats_6h': 21600,
|
||||||
|
'stats_daily': 86400,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def avg_rate_sql(table, bytes_expr, ts_expr):
|
||||||
|
"""SQL expression of the average speed (Mbps) of a bucket of an aggregate table.
|
||||||
|
|
||||||
|
The current (incomplete) bucket lasts min(bucket length, time since its start), at least 1 second;
|
||||||
|
timestamps of the aggregates are UTC. `table` is taken only from BUCKET_SECONDS (never user input),
|
||||||
|
the other arguments are fixed column expressions of the caller.
|
||||||
|
"""
|
||||||
|
seconds = BUCKET_SECONDS[table]
|
||||||
|
return (f"({bytes_expr}) * 8.0 / 1000000.0 / "
|
||||||
|
f"MAX(1, MIN({seconds}, CAST(strftime('%s', 'now') AS INTEGER) - CAST(strftime('%s', {ts_expr}) AS INTEGER)))")
|
||||||
|
|
||||||
|
|
||||||
class OpenVPNAPI:
|
class OpenVPNAPI:
|
||||||
def get_config_value(self, section, key, fallback=None):
|
def get_config_value(self, section, key, fallback=None):
|
||||||
try:
|
try:
|
||||||
@@ -41,18 +65,27 @@ class OpenVPNAPI:
|
|||||||
return fallback
|
return fallback
|
||||||
|
|
||||||
def __init__(self, config_file='config.ini'):
|
def __init__(self, config_file='config.ini'):
|
||||||
self.db_manager = DatabaseManager(config_file)
|
|
||||||
self.db_manager.init_database()
|
|
||||||
self.config = configparser.ConfigParser()
|
self.config = configparser.ConfigParser()
|
||||||
self.config.read(config_file)
|
self.config.read(config_file)
|
||||||
|
|
||||||
|
# Security: fail closed on a missing/weak signing key, before any DB work or admin creation
|
||||||
|
try:
|
||||||
|
self.secret_key, key_source = resolve_secret_key(
|
||||||
|
os.getenv('OVPMON_API_SECRET_KEY'),
|
||||||
|
self.config.get('api', 'secret_key', fallback=None),
|
||||||
|
os.getenv('OVPMON_SECRET_KEY'))
|
||||||
|
except SecretKeyError as e:
|
||||||
|
logger.critical(f"Refusing to start: {e}")
|
||||||
|
raise SystemExit(1)
|
||||||
|
logger.info(f"JWT secret key loaded from {key_source}")
|
||||||
|
app.config['SECRET_KEY'] = self.secret_key
|
||||||
|
|
||||||
|
self.db_manager = DatabaseManager(config_file)
|
||||||
|
self.db_manager.init_database()
|
||||||
|
|
||||||
# Paths
|
# Paths
|
||||||
self.public_ip = self.get_config_value('openvpn_monitor', 'public_ip', fallback='')
|
self.public_ip = self.get_config_value('openvpn_monitor', 'public_ip', fallback='')
|
||||||
|
|
||||||
# Security
|
|
||||||
self.secret_key = self.get_config_value('api', 'secret_key', fallback='ovpmon-secret-change-me')
|
|
||||||
app.config['SECRET_KEY'] = self.secret_key
|
|
||||||
|
|
||||||
# Ensure at least one user exists
|
# Ensure at least one user exists
|
||||||
self.ensure_default_admin()
|
self.ensure_default_admin()
|
||||||
|
|
||||||
@@ -159,15 +192,20 @@ class OpenVPNAPI:
|
|||||||
c.total_bytes_received,
|
c.total_bytes_received,
|
||||||
c.total_bytes_sent,
|
c.total_bytes_sent,
|
||||||
-- Пиковая скорость Download за последние 2 минуты
|
-- Пиковая скорость Download за последние 2 минуты
|
||||||
(SELECT MAX(uh.bytes_received_rate_mbps)
|
-- (скорость пользователя = сумма по его сессиям на одной отметке времени)
|
||||||
|
(SELECT MAX(s.rate) FROM (
|
||||||
|
SELECT SUM(uh.bytes_received_rate_mbps) as rate
|
||||||
FROM usage_history uh
|
FROM usage_history uh
|
||||||
WHERE uh.client_id = c.id
|
WHERE uh.client_id = c.id
|
||||||
AND uh.timestamp >= datetime('now', '-30 seconds')) as current_recv_rate,
|
AND uh.timestamp >= datetime('now', '-30 seconds')
|
||||||
|
GROUP BY uh.timestamp) s) as current_recv_rate,
|
||||||
-- Пиковая скорость Upload за последние 2 минуты
|
-- Пиковая скорость Upload за последние 2 минуты
|
||||||
(SELECT MAX(uh.bytes_sent_rate_mbps)
|
(SELECT MAX(s.rate) FROM (
|
||||||
|
SELECT SUM(uh.bytes_sent_rate_mbps) as rate
|
||||||
FROM usage_history uh
|
FROM usage_history uh
|
||||||
WHERE uh.client_id = c.id
|
WHERE uh.client_id = c.id
|
||||||
AND uh.timestamp >= datetime('now', '-30 seconds')) as current_sent_rate,
|
AND uh.timestamp >= datetime('now', '-30 seconds')
|
||||||
|
GROUP BY uh.timestamp) s) as current_sent_rate,
|
||||||
strftime('%Y-%m-%d %H:%M:%S', c.updated_at) as last_updated
|
strftime('%Y-%m-%d %H:%M:%S', c.updated_at) as last_updated
|
||||||
FROM clients c
|
FROM clients c
|
||||||
ORDER BY c.status DESC, c.common_name
|
ORDER BY c.status DESC, c.common_name
|
||||||
@@ -179,6 +217,31 @@ class OpenVPNAPI:
|
|||||||
for row in cursor.fetchall():
|
for row in cursor.fetchall():
|
||||||
data.append(dict(zip(columns, row)))
|
data.append(dict(zip(columns, row)))
|
||||||
|
|
||||||
|
# Active sessions per CN (the table may be absent on an old database)
|
||||||
|
sessions_by_cn = {}
|
||||||
|
try:
|
||||||
|
cursor.execute('''
|
||||||
|
SELECT common_name, real_address, connected_since, bytes_received, bytes_sent
|
||||||
|
FROM active_sessions
|
||||||
|
ORDER BY connected_since, real_address
|
||||||
|
''')
|
||||||
|
for cn, addr, since, rx, tx in cursor.fetchall():
|
||||||
|
sessions_by_cn.setdefault(cn, []).append({
|
||||||
|
'real_address': addr,
|
||||||
|
'connected_since': since,
|
||||||
|
'bytes_received': rx or 0,
|
||||||
|
'bytes_sent': tx or 0,
|
||||||
|
'received_mb': round((rx or 0) / (1024 * 1024), 2),
|
||||||
|
'sent_mb': round((tx or 0) / (1024 * 1024), 2),
|
||||||
|
})
|
||||||
|
except sqlite3.Error:
|
||||||
|
sessions_by_cn = {}
|
||||||
|
|
||||||
|
for client in data:
|
||||||
|
sessions = sessions_by_cn.get(client['common_name'], []) if client['status'] == 'Active' else []
|
||||||
|
client['sessions_count'] = len(sessions)
|
||||||
|
client['sessions'] = sessions
|
||||||
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -278,17 +341,27 @@ class OpenVPNAPI:
|
|||||||
points_count = 96
|
points_count = 96
|
||||||
|
|
||||||
if is_high_res:
|
if is_high_res:
|
||||||
|
# Внутренний запрос: сумма по сессиям на одной отметке времени
|
||||||
|
# (старые строки хранят по записи на сессию), внешний: MAX скорости в интервале
|
||||||
query = f'''
|
query = f'''
|
||||||
SELECT
|
SELECT
|
||||||
datetime((strftime('%s', uh.timestamp) / {interval}) * {interval}, 'unixepoch') as timestamp,
|
datetime((strftime('%s', u.timestamp) / {interval}) * {interval}, 'unixepoch') as timestamp,
|
||||||
|
SUM(u.bytes_received) as bytes_received,
|
||||||
|
SUM(u.bytes_sent) as bytes_sent,
|
||||||
|
MAX(u.bytes_received_rate_mbps) as bytes_received_rate_mbps,
|
||||||
|
MAX(u.bytes_sent_rate_mbps) as bytes_sent_rate_mbps
|
||||||
|
FROM (
|
||||||
|
SELECT uh.timestamp as timestamp,
|
||||||
SUM(uh.bytes_received) as bytes_received,
|
SUM(uh.bytes_received) as bytes_received,
|
||||||
SUM(uh.bytes_sent) as bytes_sent,
|
SUM(uh.bytes_sent) as bytes_sent,
|
||||||
MAX(uh.bytes_received_rate_mbps) as bytes_received_rate_mbps,
|
SUM(uh.bytes_received_rate_mbps) as bytes_received_rate_mbps,
|
||||||
MAX(uh.bytes_sent_rate_mbps) as bytes_sent_rate_mbps
|
SUM(uh.bytes_sent_rate_mbps) as bytes_sent_rate_mbps
|
||||||
FROM usage_history uh
|
FROM usage_history uh
|
||||||
JOIN clients c ON uh.client_id = c.id
|
JOIN clients c ON uh.client_id = c.id
|
||||||
WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ?
|
WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ?
|
||||||
GROUP BY datetime((strftime('%s', uh.timestamp) / {interval}) * {interval}, 'unixepoch')
|
GROUP BY uh.timestamp
|
||||||
|
) u
|
||||||
|
GROUP BY datetime((strftime('%s', u.timestamp) / {interval}) * {interval}, 'unixepoch')
|
||||||
ORDER BY timestamp ASC
|
ORDER BY timestamp ASC
|
||||||
'''
|
'''
|
||||||
elif is_aggregated:
|
elif is_aggregated:
|
||||||
@@ -297,8 +370,8 @@ class OpenVPNAPI:
|
|||||||
t.timestamp,
|
t.timestamp,
|
||||||
t.bytes_received,
|
t.bytes_received,
|
||||||
t.bytes_sent,
|
t.bytes_sent,
|
||||||
0 as bytes_received_rate_mbps,
|
{avg_rate_sql(target_table, 't.bytes_received', 't.timestamp')} as bytes_received_rate_mbps,
|
||||||
0 as bytes_sent_rate_mbps
|
{avg_rate_sql(target_table, 't.bytes_sent', 't.timestamp')} as bytes_sent_rate_mbps
|
||||||
FROM {target_table} t
|
FROM {target_table} t
|
||||||
JOIN clients c ON t.client_id = c.id
|
JOIN clients c ON t.client_id = c.id
|
||||||
WHERE c.common_name = ? AND t.timestamp BETWEEN ? AND ?
|
WHERE c.common_name = ? AND t.timestamp BETWEEN ? AND ?
|
||||||
@@ -308,13 +381,14 @@ class OpenVPNAPI:
|
|||||||
query = f'''
|
query = f'''
|
||||||
SELECT
|
SELECT
|
||||||
uh.timestamp,
|
uh.timestamp,
|
||||||
uh.bytes_received,
|
SUM(uh.bytes_received) as bytes_received,
|
||||||
uh.bytes_sent,
|
SUM(uh.bytes_sent) as bytes_sent,
|
||||||
uh.bytes_received_rate_mbps,
|
SUM(uh.bytes_received_rate_mbps) as bytes_received_rate_mbps,
|
||||||
uh.bytes_sent_rate_mbps
|
SUM(uh.bytes_sent_rate_mbps) as bytes_sent_rate_mbps
|
||||||
FROM usage_history uh
|
FROM usage_history uh
|
||||||
JOIN clients c ON uh.client_id = c.id
|
JOIN clients c ON uh.client_id = c.id
|
||||||
WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ?
|
WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ?
|
||||||
|
GROUP BY uh.timestamp
|
||||||
ORDER BY uh.timestamp ASC
|
ORDER BY uh.timestamp ASC
|
||||||
'''
|
'''
|
||||||
|
|
||||||
@@ -451,7 +525,8 @@ class OpenVPNAPI:
|
|||||||
if target_table == 'usage_history':
|
if target_table == 'usage_history':
|
||||||
rate_cols = "SUM(bytes_received_rate_mbps) as total_rx_rate, SUM(bytes_sent_rate_mbps) as total_tx_rate,"
|
rate_cols = "SUM(bytes_received_rate_mbps) as total_rx_rate, SUM(bytes_sent_rate_mbps) as total_tx_rate,"
|
||||||
else:
|
else:
|
||||||
rate_cols = "0 as total_rx_rate, 0 as total_tx_rate,"
|
rate_cols = (f"{avg_rate_sql(target_table, 'SUM(bytes_received)', 'timestamp')} as total_rx_rate, "
|
||||||
|
f"{avg_rate_sql(target_table, 'SUM(bytes_sent)', 'timestamp')} as total_tx_rate,")
|
||||||
|
|
||||||
# Aggregation Query
|
# Aggregation Query
|
||||||
# Group by interval_seconds
|
# Group by interval_seconds
|
||||||
|
|||||||
+343
-99
@@ -1,11 +1,29 @@
|
|||||||
import sqlite3
|
import sqlite3
|
||||||
import time
|
import time
|
||||||
import os
|
import os
|
||||||
|
import calendar
|
||||||
|
import signal
|
||||||
|
import threading
|
||||||
import configparser
|
import configparser
|
||||||
import logging
|
import logging
|
||||||
|
from collections import namedtuple
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from db import DatabaseManager
|
from db import DatabaseManager
|
||||||
|
|
||||||
|
# Результат чтения файла статуса OpenVPN.
|
||||||
|
# valid - файл целостный, тик можно обрабатывать (False = тик пропустить целиком);
|
||||||
|
# clients - список сессий (пустой при stale или при невалидном чтении);
|
||||||
|
# stale - файл целостный, но устарел (OpenVPN остановлен), клиентов нет;
|
||||||
|
# reason - причина невалидности/устаревания (для лога).
|
||||||
|
StatusReading = namedtuple('StatusReading', ['valid', 'clients', 'stale', 'reason'])
|
||||||
|
|
||||||
|
# Время хранения "памяти" о завершённой сессии (ключ + последние счётчики), сек.
|
||||||
|
# Нужна, чтобы сессия с тем же ключом, вернувшаяся после льготного периода, не считалась с нуля.
|
||||||
|
SESSION_MEMORY_SECONDS = 3600
|
||||||
|
|
||||||
|
# Формат времени в таблице active_sessions (UTC для connected_since)
|
||||||
|
TS_FORMAT = '%Y-%m-%d %H:%M:%S'
|
||||||
|
|
||||||
# --- КЛАСС АГРЕГАЦИИ ДАННЫХ (TSDB LOGIC) ---
|
# --- КЛАСС АГРЕГАЦИИ ДАННЫХ (TSDB LOGIC) ---
|
||||||
class TimeSeriesAggregator:
|
class TimeSeriesAggregator:
|
||||||
def __init__(self, db_provider):
|
def __init__(self, db_provider):
|
||||||
@@ -101,7 +119,13 @@ class OpenVPNDataGatherer:
|
|||||||
# Инициализируем дату последней очистки вчерашним днем для корректного старта
|
# Инициализируем дату последней очистки вчерашним днем для корректного старта
|
||||||
self.last_cleanup_date = (datetime.now() - timedelta(days=1)).date()
|
self.last_cleanup_date = (datetime.now() - timedelta(days=1)).date()
|
||||||
|
|
||||||
self.last_cleanup_date = (datetime.now() - timedelta(days=1)).date()
|
# Момент запуска демона (epoch): сессии, начавшиеся раньше, считаются "продолжающимися"
|
||||||
|
self.started_at = self._now()
|
||||||
|
# Флаг остановки (SIGTERM/SIGINT) и счётчик подряд идущих пропущенных тиков
|
||||||
|
self.stop_event = threading.Event()
|
||||||
|
self.invalid_ticks = 0
|
||||||
|
# Проверка настроек цикла: неверное значение = отказ запуска
|
||||||
|
self._load_settings()
|
||||||
|
|
||||||
self.db_manager = DatabaseManager(config_file)
|
self.db_manager = DatabaseManager(config_file)
|
||||||
self.db_manager.init_database()
|
self.db_manager.init_database()
|
||||||
@@ -110,10 +134,75 @@ class OpenVPNDataGatherer:
|
|||||||
# Передаем ссылку на метод подключения к БД
|
# Передаем ссылку на метод подключения к БД
|
||||||
self.ts_aggregator = TimeSeriesAggregator(self.db_manager.get_connection)
|
self.ts_aggregator = TimeSeriesAggregator(self.db_manager.get_connection)
|
||||||
|
|
||||||
# In-Memory Cache для отслеживания сессий (CN, RealAddress) -> {last_bytes...}
|
# In-Memory Cache для отслеживания сессий:
|
||||||
|
# (CN, Client ID или RealAddress, connected_since_ts) -> {
|
||||||
|
# 'bytes_received', 'bytes_sent': счётчики на прошлом тике,
|
||||||
|
# 'last_seen': строка времени, 'connected_since': строка UTC (начало сессии),
|
||||||
|
# 'missing_ticks': сколько тиков подряд сессии нет в статусе (льготный период)}
|
||||||
# Используется для корректного расчета инкрементов при множественных сессиях одного CN
|
# Используется для корректного расчета инкрементов при множественных сессиях одного CN
|
||||||
self.session_cache = {}
|
self.session_cache = {}
|
||||||
|
|
||||||
|
# Базовая линия: ключ сессии -> (rx, tx, момент записи, epoch).
|
||||||
|
# Сюда попадают сессии из снимка active_sessions (после перезапуска демона)
|
||||||
|
# и сессии, удалённые из кэша после льготного периода.
|
||||||
|
self.baseline = {}
|
||||||
|
self._load_baseline()
|
||||||
|
|
||||||
|
def _now(self):
|
||||||
|
"""Текущее время (epoch). Вынесено в метод, чтобы тесты могли управлять временем."""
|
||||||
|
return time.time()
|
||||||
|
|
||||||
|
def _read_int_setting(self, key, default, minimum):
|
||||||
|
"""Читает целое из [openvpn_monitor] (ENV > config.ini > умолчание) и проверяет минимум."""
|
||||||
|
raw = self.get_config_value('openvpn_monitor', key, default)
|
||||||
|
try:
|
||||||
|
value = int(str(raw).strip())
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError(f"[openvpn_monitor] {key} must be an integer, got {raw!r}")
|
||||||
|
if value < minimum:
|
||||||
|
raise ValueError(f"[openvpn_monitor] {key} must be >= {minimum}, got {value}")
|
||||||
|
return value
|
||||||
|
|
||||||
|
def _load_settings(self):
|
||||||
|
"""Загрузка и проверка параметров цикла. При ошибке - понятное сообщение и выход с кодом 1."""
|
||||||
|
try:
|
||||||
|
self.interval = self._read_int_setting('check_interval', 10, 1)
|
||||||
|
self.grace_ticks = self._read_int_setting('session_grace_ticks', 3, 0)
|
||||||
|
self.stale_seconds = self._read_int_setting('status_stale_seconds', 60, 1)
|
||||||
|
self.invalid_max = self._read_int_setting('status_invalid_max', 6, 1)
|
||||||
|
except ValueError as e:
|
||||||
|
self.logger.error(f"Invalid configuration: {e}")
|
||||||
|
raise SystemExit(1)
|
||||||
|
|
||||||
|
def _load_baseline(self):
|
||||||
|
"""
|
||||||
|
Загрузка снимка active_sessions (последнее состояние до остановки демона) как базовой линии.
|
||||||
|
connected_since в таблице - UTC 'YYYY-MM-DD HH:MM:SS'; переводим в epoch для ключа сессии.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
conn = self.db_manager.get_connection()
|
||||||
|
try:
|
||||||
|
rows = conn.execute(
|
||||||
|
'SELECT common_name, real_address, bytes_received, bytes_sent, connected_since, session_id '
|
||||||
|
'FROM active_sessions'
|
||||||
|
).fetchall()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.warning(f"Could not load active_sessions snapshot: {e}")
|
||||||
|
return
|
||||||
|
|
||||||
|
for name, real_addr, rx, tx, since, session_id in rows:
|
||||||
|
try:
|
||||||
|
since_ts = calendar.timegm(time.strptime(str(since)[:19].replace('T', ' '), TS_FORMAT))
|
||||||
|
# Тот же ключ, что у сборщика; строки снимка без session_id совпадают по адресу
|
||||||
|
self.baseline[(name, session_id or real_addr, since_ts)] = (int(rx), int(tx), self.started_at)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
# Старый формат (локальное время первого наблюдения) - совпасть с ключом не может
|
||||||
|
continue
|
||||||
|
if self.baseline:
|
||||||
|
self.logger.info(f"Loaded {len(self.baseline)} sessions from active_sessions snapshot")
|
||||||
|
|
||||||
def load_config(self, config_file):
|
def load_config(self, config_file):
|
||||||
"""Загрузка конфигурации или создание дефолтной со сложной структурой"""
|
"""Загрузка конфигурации или создание дефолтной со сложной структурой"""
|
||||||
config = configparser.ConfigParser()
|
config = configparser.ConfigParser()
|
||||||
@@ -129,6 +218,9 @@ class OpenVPNDataGatherer:
|
|||||||
'log_path': '/var/log/openvpn/openvpn-status.log',
|
'log_path': '/var/log/openvpn/openvpn-status.log',
|
||||||
'db_path': 'openvpn_monitor.db',
|
'db_path': 'openvpn_monitor.db',
|
||||||
'check_interval': '10', # Интервал 10 секунд
|
'check_interval': '10', # Интервал 10 секунд
|
||||||
|
'session_grace_ticks': '3', # Тиков до удаления пропавшей из статуса сессии
|
||||||
|
'status_stale_seconds': '60', # Файл статуса старше этого = OpenVPN остановлен
|
||||||
|
'status_invalid_max': '6', # Подряд пропущенных тиков до уровня ERROR в логе
|
||||||
},
|
},
|
||||||
'logging': {
|
'logging': {
|
||||||
'level': 'INFO',
|
'level': 'INFO',
|
||||||
@@ -260,22 +352,52 @@ class OpenVPNDataGatherer:
|
|||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
def parse_log_file(self):
|
def parse_status(self, path, now=None):
|
||||||
"""
|
"""
|
||||||
Парсинг лога версии 2 (CSV формат).
|
Разбор файла статуса версии 2 (CSV формат) с проверкой целостности и свежести.
|
||||||
Ожидает формат: CLIENT_LIST,Common Name,Real Address,...,Bytes Received,Bytes Sent,...
|
Ожидает: TITLE,... / TIME,<текст>,<epoch> / CLIENT_LIST,Common Name,Real Address,...,
|
||||||
|
Bytes Received,Bytes Sent,Connected Since,Connected Since (time_t),... / END
|
||||||
|
|
||||||
|
Возвращает StatusReading:
|
||||||
|
- нет файла, ошибка чтения, нет TITLE, нет END последней строкой, нет TIME:
|
||||||
|
valid=False (тик нужно пропустить целиком, БД и кэш не трогать);
|
||||||
|
- TIME старше status_stale_seconds: valid=True, stale=True, клиентов нет (OpenVPN остановлен);
|
||||||
|
- иначе valid=True и список клиентов (пустой файл без CLIENT_LIST - штатный случай).
|
||||||
"""
|
"""
|
||||||
log_path = self.get_config_value('openvpn_monitor', 'log_path', '/var/log/openvpn/openvpn-status.log')
|
if now is None:
|
||||||
clients = []
|
now = self._now()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if not os.path.exists(log_path):
|
if not os.path.exists(path):
|
||||||
self.logger.warning(f"Log file not found: {log_path}")
|
return StatusReading(False, [], False, f"status file not found: {path}")
|
||||||
return clients
|
with open(path, 'r') as file:
|
||||||
|
lines = [line.strip() for line in file]
|
||||||
|
except Exception as e:
|
||||||
|
return StatusReading(False, [], False, f"cannot read status file: {e}")
|
||||||
|
|
||||||
|
lines = [line for line in lines if line]
|
||||||
|
if not any(line.startswith('TITLE') for line in lines):
|
||||||
|
return StatusReading(False, [], False, "no TITLE line (not a status file)")
|
||||||
|
if lines[-1] != 'END':
|
||||||
|
return StatusReading(False, [], False, "no END line (file is incomplete)")
|
||||||
|
|
||||||
|
status_time = None
|
||||||
|
clients = []
|
||||||
|
# Индекс колонки Client ID в строках CLIENT_LIST (None = в статусе колонки нет)
|
||||||
|
client_id_idx = None
|
||||||
|
for line in lines:
|
||||||
|
if line.startswith('HEADER,CLIENT_LIST,'):
|
||||||
|
# В строке заголовка первым идёт слово HEADER, в строках данных его нет: сдвиг на 1
|
||||||
|
header = [h.strip() for h in line.split(',')]
|
||||||
|
client_id_idx = header.index('Client ID') - 1 if 'Client ID' in header else None
|
||||||
|
continue
|
||||||
|
if line.startswith('TIME,'):
|
||||||
|
try:
|
||||||
|
status_time = int(line.split(',')[2])
|
||||||
|
except (IndexError, ValueError):
|
||||||
|
pass
|
||||||
|
continue
|
||||||
|
|
||||||
with open(log_path, 'r') as file:
|
|
||||||
for line in file:
|
|
||||||
line = line.strip()
|
|
||||||
# Фильтруем только строки с данными клиентов
|
# Фильтруем только строки с данными клиентов
|
||||||
if not line.startswith('CLIENT_LIST'):
|
if not line.startswith('CLIENT_LIST'):
|
||||||
continue
|
continue
|
||||||
@@ -286,6 +408,7 @@ class OpenVPNDataGatherer:
|
|||||||
# 2: Real Address
|
# 2: Real Address
|
||||||
# 5: Bytes Received
|
# 5: Bytes Received
|
||||||
# 6: Bytes Sent
|
# 6: Bytes Sent
|
||||||
|
# 8: Connected Since (time_t) - начало сессии, epoch
|
||||||
|
|
||||||
if len(parts) >= 8 and parts[1] != 'Common Name':
|
if len(parts) >= 8 and parts[1] != 'Common Name':
|
||||||
# SKIPPING 'UNDEF' CLIENTS
|
# SKIPPING 'UNDEF' CLIENTS
|
||||||
@@ -293,32 +416,102 @@ class OpenVPNDataGatherer:
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
since_ts = None
|
||||||
|
if len(parts) > 8:
|
||||||
|
try:
|
||||||
|
since_ts = int(parts[8].strip())
|
||||||
|
except ValueError:
|
||||||
|
since_ts = None
|
||||||
|
if since_ts is not None and since_ts <= 0:
|
||||||
|
since_ts = None
|
||||||
|
|
||||||
|
# Client ID не меняется при float (смене адреса): идентификатор сессии;
|
||||||
|
# нет колонки или не число - session_id None (ключ сессии с real_address)
|
||||||
|
session_id = None
|
||||||
|
if client_id_idx is not None and client_id_idx < len(parts):
|
||||||
|
try:
|
||||||
|
session_id = str(int(parts[client_id_idx].strip()))
|
||||||
|
except ValueError:
|
||||||
|
session_id = None
|
||||||
|
|
||||||
client = {
|
client = {
|
||||||
'common_name': parts[1].strip(),
|
'common_name': parts[1].strip(),
|
||||||
'real_address': parts[2].strip(),
|
'real_address': parts[2].strip(),
|
||||||
|
'session_id': session_id,
|
||||||
'bytes_received': int(parts[5].strip()),
|
'bytes_received': int(parts[5].strip()),
|
||||||
'bytes_sent': int(parts[6].strip()),
|
'bytes_sent': int(parts[6].strip()),
|
||||||
|
'connected_since_ts': since_ts,
|
||||||
'status': 'Active'
|
'status': 'Active'
|
||||||
}
|
}
|
||||||
clients.append(client)
|
clients.append(client)
|
||||||
except (ValueError, IndexError) as e:
|
except (ValueError, IndexError) as e:
|
||||||
self.logger.warning(f"Error parsing client line: {e}")
|
self.logger.warning(f"Error parsing client line: {e}")
|
||||||
|
|
||||||
|
if status_time is None:
|
||||||
|
return StatusReading(False, [], False, "no valid TIME line (cannot check freshness)")
|
||||||
|
|
||||||
|
age = now - status_time
|
||||||
|
if age > self.stale_seconds:
|
||||||
|
return StatusReading(True, [], True, f"status file is stale ({int(age)}s old): OpenVPN stopped?")
|
||||||
|
|
||||||
self.logger.debug(f"Parsed {len(clients)} active clients")
|
self.logger.debug(f"Parsed {len(clients)} active clients")
|
||||||
|
return StatusReading(True, clients, False, "")
|
||||||
|
|
||||||
except Exception as e:
|
def parse_log_file(self):
|
||||||
self.logger.error(f"Error parsing log file: {e}")
|
"""Читает файл статуса из [openvpn_monitor] log_path (см. parse_status). Возвращает StatusReading."""
|
||||||
|
log_path = self.get_config_value('openvpn_monitor', 'log_path', '/var/log/openvpn/openvpn-status.log')
|
||||||
|
return self.parse_status(log_path)
|
||||||
|
|
||||||
return clients
|
@staticmethod
|
||||||
|
def _delta(current, previous):
|
||||||
|
"""Прирост счётчика сессии; уменьшение счётчика при том же ключе = сброс (прирост = текущее)."""
|
||||||
|
return current if current < previous else current - previous
|
||||||
|
|
||||||
|
def _first_seen_increment(self, key, curr_recv, curr_sent):
|
||||||
|
"""
|
||||||
|
Прирост для сессии, которой нет в кэше (правила: DOCS/Changes/2026-10-05_Gatherer_Reliability_PLAN.md, 2.2).
|
||||||
|
Возвращает (inc_recv, inc_sent).
|
||||||
|
"""
|
||||||
|
name, sess_id, since_ts = key
|
||||||
|
|
||||||
|
if since_ts is None:
|
||||||
|
# Нестандартный статус: время начала сессии неизвестно, запасная эвристика по размеру счётчиков
|
||||||
|
self.logger.warning(f"No connected_since time_t for {name} ({sess_id}): using 10 MB heuristic")
|
||||||
|
threshold = 10 * 1024 * 1024
|
||||||
|
if curr_recv < threshold and curr_sent < threshold:
|
||||||
|
return curr_recv, curr_sent
|
||||||
|
return 0, 0
|
||||||
|
|
||||||
|
# Сессия известна: снимок active_sessions после перезапуска демона
|
||||||
|
# или сессия, удалённая из кэша после льготного периода (счётчики на последнем тике)
|
||||||
|
base = self.baseline.get(key)
|
||||||
|
if base is not None:
|
||||||
|
return self._delta(curr_recv, base[0]), self._delta(curr_sent, base[1])
|
||||||
|
|
||||||
|
# Сессия началась уже после запуска демона (с запасом 2 интервала): считаем с нуля
|
||||||
|
if since_ts >= self.started_at - 2 * self.interval:
|
||||||
|
return curr_recv, curr_sent
|
||||||
|
|
||||||
|
# Сессия старше демона, снимка нет: базовая линия, трафик до этого момента потерян
|
||||||
|
self.logger.warning(
|
||||||
|
f"Session of {name} ({sess_id}) started before the gatherer and has no snapshot: "
|
||||||
|
f"baseline set, {curr_recv} B received / {curr_sent} B sent before this moment are not counted"
|
||||||
|
)
|
||||||
|
return 0, 0
|
||||||
|
|
||||||
def update_client_status_and_bytes(self, active_clients):
|
def update_client_status_and_bytes(self, active_clients):
|
||||||
"""
|
"""
|
||||||
Обновление статусов и расчет инкрементов трафика.
|
Обновление статусов и расчет инкрементов трафика.
|
||||||
Использует In-Memory Cache (self.session_cache) для корректной обработки
|
Использует In-Memory Cache (self.session_cache) для корректной обработки
|
||||||
множественных сессий одного пользователя (Ping-Pong effect fix).
|
множественных сессий одного пользователя (Ping-Pong effect fix).
|
||||||
|
Изменения кэша накапливаются в new_cache и применяются только после успешного commit:
|
||||||
|
при откате транзакции кэш остаётся прежним, приращения не теряются.
|
||||||
|
При ошибке БД откатывает транзакцию и пробрасывает исключение (его обработает цикл).
|
||||||
"""
|
"""
|
||||||
conn = self.db_manager.get_connection()
|
conn = self.db_manager.get_connection()
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
|
now_ts = self._now()
|
||||||
|
last_seen_str = datetime.fromtimestamp(now_ts).strftime(TS_FORMAT)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 1. Загружаем текущее состояние CNs из БД для обновления статусов
|
# 1. Загружаем текущее состояние CNs из БД для обновления статусов
|
||||||
@@ -326,11 +519,12 @@ class OpenVPNDataGatherer:
|
|||||||
db_clients = {row[1]: {'id': row[0], 'status': row[2]} for row in cursor.fetchall()}
|
db_clients = {row[1]: {'id': row[0], 'status': row[2]} for row in cursor.fetchall()}
|
||||||
|
|
||||||
# Структура для агрегации инкрементов по Common Name перед записью в БД
|
# Структура для агрегации инкрементов по Common Name перед записью в БД
|
||||||
# cn -> { 'inc_rx': 0, 'inc_tx': 0, 'curr_rx': 0, 'curr_tx': 0, 'real_address': '...'}
|
# cn -> { 'inc_recv': 0, 'inc_tx': 0, 'max_rx': 0 (сумма текущих счётчиков сессий),
|
||||||
|
# 'max_tx': 0, 'real_address': '...' (сессия с самым поздним началом)}
|
||||||
cn_updates = {}
|
cn_updates = {}
|
||||||
|
|
||||||
# Множество активных ключей сессий (CN, RealAddr) для очистки кэша
|
# Новое состояние кэша сессий (применяется после commit) и активные CN
|
||||||
active_session_keys = set()
|
new_cache = {}
|
||||||
active_cns = set()
|
active_cns = set()
|
||||||
|
|
||||||
# 2. Обрабатываем каждую активную сессию
|
# 2. Обрабатываем каждую активную сессию
|
||||||
@@ -339,66 +533,39 @@ class OpenVPNDataGatherer:
|
|||||||
real_addr = client['real_address']
|
real_addr = client['real_address']
|
||||||
curr_recv = client['bytes_received']
|
curr_recv = client['bytes_received']
|
||||||
curr_sent = client['bytes_sent']
|
curr_sent = client['bytes_sent']
|
||||||
|
since_ts = client.get('connected_since_ts')
|
||||||
|
|
||||||
# Уникальный ключ сессии
|
# Уникальный ключ сессии: Client ID не меняется при float (смене адреса);
|
||||||
session_key = (name, real_addr)
|
# без Client ID - адрес. Переподключение (новый connected_since) - новая сессия
|
||||||
active_session_keys.add(session_key)
|
session_key = (name, client.get('session_id') or real_addr, since_ts)
|
||||||
active_cns.add(name)
|
active_cns.add(name)
|
||||||
|
|
||||||
# --- ЛОГИКА РАСЧЕТА ДЕЛЬТЫ (In-Memory) ---
|
# --- ЛОГИКА РАСЧЕТА ДЕЛЬТЫ (In-Memory) ---
|
||||||
if session_key in self.session_cache:
|
prev_state = self.session_cache.get(session_key)
|
||||||
prev_state = self.session_cache[session_key]
|
if prev_state is not None:
|
||||||
prev_recv = prev_state['bytes_received']
|
prev_recv = prev_state['bytes_received']
|
||||||
prev_sent = prev_state['bytes_sent']
|
prev_sent = prev_state['bytes_sent']
|
||||||
|
|
||||||
# Расчет RX
|
|
||||||
if curr_recv < prev_recv:
|
if curr_recv < prev_recv:
|
||||||
# Рестарт сессии (счетчик сбросился)
|
|
||||||
inc_recv = curr_recv
|
|
||||||
self.logger.info(f"Session reset detected for {session_key} (Recv)")
|
self.logger.info(f"Session reset detected for {session_key} (Recv)")
|
||||||
else:
|
|
||||||
inc_recv = curr_recv - prev_recv
|
|
||||||
|
|
||||||
# Расчет TX
|
|
||||||
if curr_sent < prev_sent:
|
if curr_sent < prev_sent:
|
||||||
inc_sent = curr_sent
|
|
||||||
self.logger.info(f"Session reset detected for {session_key} (Sent)")
|
self.logger.info(f"Session reset detected for {session_key} (Sent)")
|
||||||
|
inc_recv = self._delta(curr_recv, prev_recv)
|
||||||
|
inc_sent = self._delta(curr_sent, prev_sent)
|
||||||
|
connected_since = prev_state['connected_since']
|
||||||
else:
|
else:
|
||||||
inc_sent = curr_sent - prev_sent
|
# Сессия не в кэше: новая, продолжающаяся после перезапуска или вернувшаяся
|
||||||
|
inc_recv, inc_sent = self._first_seen_increment(session_key, curr_recv, curr_sent)
|
||||||
|
# В active_sessions пишем реальное начало сессии (UTC); без time_t - время первого наблюдения
|
||||||
|
connected_since = time.strftime(TS_FORMAT, time.gmtime(since_ts if since_ts else now_ts))
|
||||||
|
|
||||||
else:
|
new_cache[session_key] = {
|
||||||
# Новая сессия (или после рестарта сервиса)
|
|
||||||
# Если сервиса только запустился, мы не знаем предыдущего состояния.
|
|
||||||
# Чтобы избежать спайков, считаем инкремент = 0 для первого появления,
|
|
||||||
# если это похоже на продолжающуюся сессию (большие числа).
|
|
||||||
# Если числа маленькие (<10MB), считаем как новую.
|
|
||||||
|
|
||||||
# 10 MB threshold
|
|
||||||
threshold = 10 * 1024 * 1024
|
|
||||||
|
|
||||||
if curr_recv < threshold and curr_sent < threshold:
|
|
||||||
inc_recv = curr_recv
|
|
||||||
inc_sent = curr_sent
|
|
||||||
else:
|
|
||||||
# Скорее всего рестарт сервиса, пропускаем первый тик
|
|
||||||
inc_recv = 0
|
|
||||||
inc_sent = 0
|
|
||||||
self.logger.debug(f"New session tracking started for {session_key}. Initializing baseline.")
|
|
||||||
|
|
||||||
# Обновляем кэш
|
|
||||||
if session_key not in self.session_cache:
|
|
||||||
# New session
|
|
||||||
self.session_cache[session_key] = {
|
|
||||||
'bytes_received': curr_recv,
|
'bytes_received': curr_recv,
|
||||||
'bytes_sent': curr_sent,
|
'bytes_sent': curr_sent,
|
||||||
'last_seen': datetime.now(),
|
'last_seen': last_seen_str,
|
||||||
'connected_since': datetime.now() # Track start time
|
'connected_since': connected_since,
|
||||||
|
'missing_ticks': 0
|
||||||
}
|
}
|
||||||
else:
|
|
||||||
# Update existing
|
|
||||||
self.session_cache[session_key]['bytes_received'] = curr_recv
|
|
||||||
self.session_cache[session_key]['bytes_sent'] = curr_sent
|
|
||||||
self.session_cache[session_key]['last_seen'] = datetime.now()
|
|
||||||
|
|
||||||
# Добавляем в клиентский объект (для истории/графиков)
|
# Добавляем в клиентский объект (для истории/графиков)
|
||||||
# Важно: это инкремент конкретной сессии
|
# Важно: это инкремент конкретной сессии
|
||||||
@@ -412,24 +579,31 @@ class OpenVPNDataGatherer:
|
|||||||
if name not in cn_updates:
|
if name not in cn_updates:
|
||||||
cn_updates[name] = {
|
cn_updates[name] = {
|
||||||
'inc_recv': 0, 'inc_tx': 0,
|
'inc_recv': 0, 'inc_tx': 0,
|
||||||
'max_rx': 0, 'max_tx': 0, # Для last_bytes в БД сохраним текущие счетчики самой большой сессии (примерно)
|
'max_rx': 0, 'max_tx': 0, # Для last_bytes в БД: сумма текущих счётчиков всех сессий CN
|
||||||
'real_address': real_addr # Берем последний адрес
|
'real_address': real_addr,
|
||||||
|
'addr_since': since_ts or 0 # Начало сессии, чей адрес сохранён
|
||||||
}
|
}
|
||||||
|
|
||||||
cn_updates[name]['inc_recv'] += inc_recv
|
cn_updates[name]['inc_recv'] += inc_recv
|
||||||
cn_updates[name]['inc_tx'] += inc_sent
|
cn_updates[name]['inc_tx'] += inc_sent
|
||||||
# Сохраняем "текущее" значение как максимальное из сессий, чтобы в БД last_bytes было хоть что-то осмысленное
|
# last_bytes в БД = сумма текущих счётчиков всех сессий CN (нужно для UI)
|
||||||
# (хотя при in-memory подходе поле last_bytes в БД теряет смысл для логики, но нужно для UI)
|
cn_updates[name]['max_rx'] += curr_recv
|
||||||
cn_updates[name]['max_rx'] = max(cn_updates[name]['max_rx'], curr_recv)
|
cn_updates[name]['max_tx'] += curr_sent
|
||||||
cn_updates[name]['max_tx'] = max(cn_updates[name]['max_tx'], curr_sent)
|
# real_address = адрес сессии с самым поздним началом
|
||||||
|
if (since_ts or 0) >= cn_updates[name]['addr_since']:
|
||||||
|
cn_updates[name]['addr_since'] = since_ts or 0
|
||||||
cn_updates[name]['real_address'] = real_addr
|
cn_updates[name]['real_address'] = real_addr
|
||||||
|
|
||||||
# 3. Очистка кэша от мертвых сессий
|
# 3. Льготный период для сессий, которых нет в текущем статусе:
|
||||||
# Создаем список ключей для удаления, чтобы не менять словарь во время итерации
|
# запись остаётся в кэше, пока missing_ticks < session_grace_ticks
|
||||||
dead_sessions = [k for k in self.session_cache if k not in active_session_keys]
|
for key, state in self.session_cache.items():
|
||||||
for k in dead_sessions:
|
if key in new_cache:
|
||||||
del self.session_cache[k]
|
continue
|
||||||
self.logger.debug(f"Removed inactive session from cache: {k}")
|
missing = state['missing_ticks'] + 1
|
||||||
|
if missing < self.grace_ticks:
|
||||||
|
new_cache[key] = dict(state, missing_ticks=missing)
|
||||||
|
else:
|
||||||
|
self.logger.debug(f"Removed inactive session from cache: {key}")
|
||||||
|
|
||||||
# 4. Обновление БД (Upsert Clients)
|
# 4. Обновление БД (Upsert Clients)
|
||||||
for name, data in cn_updates.items():
|
for name, data in cn_updates.items():
|
||||||
@@ -463,14 +637,17 @@ class OpenVPNDataGatherer:
|
|||||||
client['db_id'] = db_id
|
client['db_id'] = db_id
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# INSERT (New Client)
|
# INSERT (New Client): итоги стартуют с прироста первого кадра, а не с нуля
|
||||||
|
# (иначе трафик первого тика нового клиента не попадал в total_bytes_*)
|
||||||
cursor.execute('''
|
cursor.execute('''
|
||||||
INSERT INTO clients
|
INSERT INTO clients
|
||||||
(common_name, real_address, status, total_bytes_received, total_bytes_sent, last_bytes_received, last_bytes_sent)
|
(common_name, real_address, status, total_bytes_received, total_bytes_sent, last_bytes_received, last_bytes_sent)
|
||||||
VALUES (?, ?, 'Active', 0, 0, ?, ?)
|
VALUES (?, ?, 'Active', ?, ?, ?, ?)
|
||||||
''', (
|
''', (
|
||||||
name,
|
name,
|
||||||
data['real_address'],
|
data['real_address'],
|
||||||
|
data['inc_recv'],
|
||||||
|
data['inc_tx'],
|
||||||
data['max_rx'],
|
data['max_rx'],
|
||||||
data['max_tx']
|
data['max_tx']
|
||||||
))
|
))
|
||||||
@@ -494,36 +671,61 @@ class OpenVPNDataGatherer:
|
|||||||
# Clear old state
|
# Clear old state
|
||||||
cursor.execute('DELETE FROM active_sessions')
|
cursor.execute('DELETE FROM active_sessions')
|
||||||
|
|
||||||
# Insert current state
|
# Insert current state (только сессии, присутствующие в статусе)
|
||||||
for client in active_clients:
|
for client in active_clients:
|
||||||
# client['db_id'] should be populated by now (from step 4)
|
# client['db_id'] should be populated by now (from step 4)
|
||||||
if 'db_id' in client and 'session_key' in client:
|
if 'db_id' in client and 'session_key' in client:
|
||||||
sess_data = self.session_cache.get(client['session_key'])
|
sess_data = new_cache.get(client['session_key'])
|
||||||
if sess_data:
|
if sess_data:
|
||||||
cursor.execute('''
|
cursor.execute('''
|
||||||
INSERT INTO active_sessions
|
INSERT INTO active_sessions
|
||||||
(client_id, common_name, real_address, bytes_received, bytes_sent, connected_since, last_seen)
|
(client_id, common_name, real_address, bytes_received, bytes_sent, connected_since, last_seen, session_id)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
''', (
|
''', (
|
||||||
client['db_id'],
|
client['db_id'],
|
||||||
client['common_name'],
|
client['common_name'],
|
||||||
client['real_address'],
|
client['real_address'],
|
||||||
client['bytes_received'],
|
client['bytes_received'],
|
||||||
client['bytes_sent'],
|
client['bytes_sent'],
|
||||||
sess_data.get('connected_since', datetime.now()),
|
sess_data['connected_since'],
|
||||||
sess_data.get('last_seen', datetime.now())
|
sess_data['last_seen'],
|
||||||
|
client.get('session_id')
|
||||||
))
|
))
|
||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
except Exception as e:
|
except Exception:
|
||||||
self.logger.error(f"Error updating client status: {e}")
|
# Кэш не менялся: приращения не потеряны, следующий тик посчитает разницу за весь интервал
|
||||||
conn.rollback()
|
conn.rollback()
|
||||||
|
raise
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
# 7. Применяем изменения кэша только после успешного commit
|
||||||
|
for key, state in self.session_cache.items():
|
||||||
|
if key not in new_cache and key[2] is not None:
|
||||||
|
# Сессия удалена из кэша: помним последние счётчики на случай возврата с тем же ключом
|
||||||
|
self.baseline[key] = (state['bytes_received'], state['bytes_sent'], now_ts)
|
||||||
|
self.session_cache = new_cache
|
||||||
|
for key in new_cache:
|
||||||
|
self.baseline.pop(key, None)
|
||||||
|
self.baseline = {k: v for k, v in self.baseline.items() if now_ts - v[2] < SESSION_MEMORY_SECONDS}
|
||||||
|
|
||||||
return active_clients
|
return active_clients
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def merge_sessions_by_cn(sessions):
|
||||||
|
"""Сворачивает список сессий в список по CN: одна запись на пользователя за тик (сумма приростов)."""
|
||||||
|
merged = {}
|
||||||
|
for s in sessions:
|
||||||
|
m = merged.setdefault(s['common_name'], {
|
||||||
|
'common_name': s['common_name'], 'db_id': s.get('db_id'),
|
||||||
|
'bytes_received_inc': 0, 'bytes_sent_inc': 0
|
||||||
|
})
|
||||||
|
m['bytes_received_inc'] += s.get('bytes_received_inc', 0)
|
||||||
|
m['bytes_sent_inc'] += s.get('bytes_sent_inc', 0)
|
||||||
|
return list(merged.values())
|
||||||
|
|
||||||
def calculate_rates(self, clients, time_diff):
|
def calculate_rates(self, clients, time_diff):
|
||||||
"""Расчет скорости в Mbps"""
|
"""Расчет скорости в Mbps"""
|
||||||
if time_diff <= 0:
|
if time_diff <= 0:
|
||||||
@@ -572,11 +774,28 @@ class OpenVPNDataGatherer:
|
|||||||
"""Один цикл мониторинга"""
|
"""Один цикл мониторинга"""
|
||||||
current_time = datetime.now()
|
current_time = datetime.now()
|
||||||
|
|
||||||
# 1. Получаем активных клиентов
|
# 1. Читаем файл статуса (с проверкой целостности и свежести)
|
||||||
active_clients = self.parse_log_file()
|
reading = self.parse_log_file()
|
||||||
|
|
||||||
|
if not reading.valid:
|
||||||
|
# Рваное чтение / нет файла: тик пропускаем целиком, БД и кэш не трогаем.
|
||||||
|
# last_check_time тоже не меняем: скорость следующего тика считается за весь интервал
|
||||||
|
self.invalid_ticks += 1
|
||||||
|
# В журнал: 1-й тик, порог status_invalid_max (ERROR), далее раз в 60 тиков.
|
||||||
|
# Иначе на свежей установке без запущенного OpenVPN сообщение шло бы каждые 10 с
|
||||||
|
n = self.invalid_ticks
|
||||||
|
if n == 1 or n == self.invalid_max or n % 60 == 0:
|
||||||
|
level = logging.ERROR if n >= self.invalid_max else logging.WARNING
|
||||||
|
self.logger.log(level, f"Skipping tick ({n} in a row): {reading.reason}")
|
||||||
|
else:
|
||||||
|
if self.invalid_ticks:
|
||||||
|
self.logger.info(f"Status file is readable again after {self.invalid_ticks} skipped ticks")
|
||||||
|
self.invalid_ticks = 0
|
||||||
|
if reading.stale:
|
||||||
|
self.logger.warning(reading.reason)
|
||||||
|
|
||||||
# 2. Обновляем статусы и считаем дельту трафика
|
# 2. Обновляем статусы и считаем дельту трафика
|
||||||
clients_with_updates = self.update_client_status_and_bytes(active_clients)
|
clients_with_updates = self.update_client_status_and_bytes(reading.clients)
|
||||||
|
|
||||||
if clients_with_updates:
|
if clients_with_updates:
|
||||||
# 3. Считаем интервал времени
|
# 3. Считаем интервал времени
|
||||||
@@ -584,8 +803,9 @@ class OpenVPNDataGatherer:
|
|||||||
if self.last_check_time:
|
if self.last_check_time:
|
||||||
time_diff = (current_time - self.last_check_time).total_seconds()
|
time_diff = (current_time - self.last_check_time).total_seconds()
|
||||||
|
|
||||||
# 4. Считаем скорости
|
# 4. Сворачиваем сессии в записи по CN и считаем скорости (сумма по сессиям)
|
||||||
clients_rated = self.calculate_rates(clients_with_updates, time_diff)
|
clients_rated = self.calculate_rates(
|
||||||
|
self.merge_sessions_by_cn(clients_with_updates), time_diff)
|
||||||
|
|
||||||
# 5. Сохраняем RAW историю (для графиков реального времени)
|
# 5. Сохраняем RAW историю (для графиков реального времени)
|
||||||
self.store_usage_history(clients_rated)
|
self.store_usage_history(clients_rated)
|
||||||
@@ -601,21 +821,45 @@ class OpenVPNDataGatherer:
|
|||||||
self.cleanup_old_data()
|
self.cleanup_old_data()
|
||||||
self.last_cleanup_date = current_time.date()
|
self.last_cleanup_date = current_time.date()
|
||||||
|
|
||||||
|
def _handle_signal(self, signum, frame):
|
||||||
|
"""SIGTERM/SIGINT: только выставляем флаг, текущий цикл доделывается до конца."""
|
||||||
|
self.logger.info(f"Signal {signum} received, stopping after the current cycle")
|
||||||
|
self.stop_event.set()
|
||||||
|
|
||||||
def start_monitoring(self):
|
def start_monitoring(self):
|
||||||
"""Запуск цикла"""
|
"""Запуск цикла. Цикл переживает любые исключения; остановка по SIGTERM/SIGINT штатная."""
|
||||||
interval = int(self.get_config_value('openvpn_monitor', 'check_interval', 10))
|
interval = self.interval
|
||||||
self.logger.info(f"Starting OpenVPN Monitoring. Interval: {interval}s")
|
self.logger.info(f"Starting OpenVPN Monitoring. Interval: {interval}s")
|
||||||
self.logger.info("Press Ctrl+C to stop")
|
self.logger.info("Press Ctrl+C to stop")
|
||||||
|
|
||||||
|
# Обработчики сигналов ставятся только в главном потоке; прежние восстанавливаем при выходе
|
||||||
|
previous = {}
|
||||||
try:
|
try:
|
||||||
while True:
|
for sig in (signal.SIGTERM, signal.SIGINT):
|
||||||
self.run_monitoring_cycle()
|
previous[sig] = signal.signal(sig, self._handle_signal)
|
||||||
time.sleep(interval)
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
failures = 0
|
||||||
self.logger.info("Monitoring stopped by user")
|
try:
|
||||||
except Exception as e:
|
while not self.stop_event.is_set():
|
||||||
self.logger.error(f"Critical error in main loop: {e}")
|
try:
|
||||||
|
self.run_monitoring_cycle()
|
||||||
|
failures = 0
|
||||||
|
except Exception:
|
||||||
|
failures += 1
|
||||||
|
self.logger.exception(f"Monitoring cycle failed ({failures} in a row)")
|
||||||
|
|
||||||
|
# Пауза: интервал, а при подряд идущих сбоях - экспоненциально до 60 с
|
||||||
|
delay = interval
|
||||||
|
if failures:
|
||||||
|
delay = max(interval, min(interval * 2 ** min(failures, 10), 60))
|
||||||
|
self.stop_event.wait(delay)
|
||||||
|
finally:
|
||||||
|
for sig, handler in previous.items():
|
||||||
|
signal.signal(sig, handler)
|
||||||
|
|
||||||
|
self.logger.info("Monitoring stopped")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
gatherer = OpenVPNDataGatherer()
|
gatherer = OpenVPNDataGatherer()
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-r requirements.txt
|
||||||
|
pytest
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
Flask>=3.0.0
|
Flask>=3.0.0,<4
|
||||||
Flask-Cors>=4.0.0
|
Flask-Cors>=4.0.0,<7
|
||||||
PyJWT>=2.10.0
|
PyJWT>=2.10.0,<3
|
||||||
pyotp>=2.9.0
|
pyotp>=2.9.0,<3
|
||||||
qrcode>=7.4.2
|
qrcode>=7.4.2,<9
|
||||||
bcrypt>=4.2.0
|
bcrypt>=4.2.0,<6
|
||||||
|
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"""JWT signing key rule (fail closed). Identical copy lives in APP_PROFILER/utils/secret_key.py."""
|
||||||
|
|
||||||
|
ENV_NAME = "OVPMON_API_SECRET_KEY"
|
||||||
|
LEGACY_ENV_NAME = "OVPMON_SECRET_KEY"
|
||||||
|
DEFAULT_KEY = "ovpmon-secret-change-me"
|
||||||
|
MIN_LENGTH = 32
|
||||||
|
|
||||||
|
HOW_TO_FIX = f"Generate one with: openssl rand -hex 32, and set it in {ENV_NAME} (or [api] secret_key in config.ini)."
|
||||||
|
|
||||||
|
|
||||||
|
class SecretKeyError(Exception):
|
||||||
|
"""The signing key is missing or weak. The message never contains the key value."""
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_secret_key(env, ini_value, legacy_env=None):
|
||||||
|
"""Return (key, source) where source is "environment" or "config.ini".
|
||||||
|
|
||||||
|
env: value of OVPMON_API_SECRET_KEY (or None); ini_value: [api] secret_key (or None);
|
||||||
|
legacy_env: value of OVPMON_SECRET_KEY (not used by the application, only for the hint).
|
||||||
|
Priority: environment > config.ini. Raises SecretKeyError; does not log or exit.
|
||||||
|
"""
|
||||||
|
if env is not None:
|
||||||
|
key, source = env, f"environment variable {ENV_NAME}"
|
||||||
|
result_source = "environment"
|
||||||
|
else:
|
||||||
|
key, source = ini_value, "[api] secret_key in config.ini"
|
||||||
|
result_source = "config.ini"
|
||||||
|
|
||||||
|
if key is None or not key.strip():
|
||||||
|
msg = f"JWT secret key is not set (checked {ENV_NAME} and [api] secret_key in config.ini)."
|
||||||
|
if legacy_env is not None and legacy_env.strip():
|
||||||
|
msg += (f" {LEGACY_ENV_NAME} is set but is not used by the application: "
|
||||||
|
f"rename it to {ENV_NAME}.")
|
||||||
|
raise SecretKeyError(f"{msg} {HOW_TO_FIX}")
|
||||||
|
|
||||||
|
lowered = key.strip().lower()
|
||||||
|
if lowered == DEFAULT_KEY or "change-me" in lowered or "changeme" in lowered:
|
||||||
|
raise SecretKeyError(f"JWT secret key from {source} is a placeholder/default value. {HOW_TO_FIX}")
|
||||||
|
if len(key) < MIN_LENGTH:
|
||||||
|
raise SecretKeyError(f"JWT secret key from {source} is too short "
|
||||||
|
f"({len(key)} characters, at least {MIN_LENGTH} required). {HOW_TO_FIX}")
|
||||||
|
return key, result_source
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import importlib
|
||||||
|
import sqlite3
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
MB = 1_000_000
|
||||||
|
FMT = '%Y-%m-%d %H:%M:%S'
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def api(tmp_path, monkeypatch):
|
||||||
|
"""OpenVPNAPI on a temporary migrated database (the module creates a global instance on import)."""
|
||||||
|
monkeypatch.chdir(tmp_path)
|
||||||
|
monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_DB_PATH", str(tmp_path / "api.db"))
|
||||||
|
monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False)
|
||||||
|
module = importlib.import_module("openvpn_api_v3")
|
||||||
|
return module.OpenVPNAPI()
|
||||||
|
|
||||||
|
|
||||||
|
def test_aggregated_history_speed_is_bucket_average(api):
|
||||||
|
now = datetime.utcnow()
|
||||||
|
full = (now - timedelta(hours=5)).replace(minute=0, second=0, microsecond=0) # complete hourly bucket
|
||||||
|
current = now - timedelta(seconds=1800) # bucket started 30 minutes ago: lasts 1800 s, not 3600 s
|
||||||
|
conn = sqlite3.connect(api.db_manager.db_path)
|
||||||
|
conn.execute("INSERT INTO clients (common_name) VALUES ('alice')")
|
||||||
|
cid = conn.execute("SELECT id FROM clients WHERE common_name='alice'").fetchone()[0]
|
||||||
|
for ts in (full, current):
|
||||||
|
conn.execute("INSERT INTO stats_hourly (timestamp, client_id, bytes_received, bytes_sent) VALUES (?,?,?,?)",
|
||||||
|
(ts.strftime(FMT), cid, 450 * MB, 90 * MB))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
res = api.get_client_history('alice', now - timedelta(days=7), now, resolution='hourly')
|
||||||
|
full_row, current_row = res['data']
|
||||||
|
# 450 MB over 3600 s = 1.0 Mbps (rx), 90 MB over 3600 s = 0.2 Mbps (tx)
|
||||||
|
assert full_row['bytes_received_rate_mbps'] == pytest.approx(1.0)
|
||||||
|
assert full_row['bytes_sent_rate_mbps'] == pytest.approx(0.2)
|
||||||
|
# the same volume over 1800 s: twice as fast
|
||||||
|
assert current_row['bytes_received_rate_mbps'] == pytest.approx(2.0, rel=0.01)
|
||||||
|
assert current_row['bytes_sent_rate_mbps'] == pytest.approx(0.4, rel=0.01)
|
||||||
|
|
||||||
|
# Analytics 7d reads the same table: the sum of clients per timestamp, speed is non-zero
|
||||||
|
history = api.get_analytics_data('7d')['global_history_24h']
|
||||||
|
assert max(p['total_rx_rate'] for p in history) == pytest.approx(2.0, rel=0.01)
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
import copy
|
||||||
|
import logging
|
||||||
|
import signal
|
||||||
|
import sqlite3
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from openvpn_gatherer_v3 import OpenVPNDataGatherer
|
||||||
|
|
||||||
|
MB = 1024 * 1024
|
||||||
|
T0 = 1_800_000_000 # fixed "now" of the fake clock (epoch)
|
||||||
|
|
||||||
|
HEADER = ("HEADER,CLIENT_LIST,Common Name,Real Address,Virtual Address,Virtual IPv6 Address,"
|
||||||
|
"Bytes Received,Bytes Sent,Connected Since,Connected Since (time_t),Username,Client ID,"
|
||||||
|
"Peer ID,Data Channel Cipher")
|
||||||
|
|
||||||
|
|
||||||
|
def write_status(path, now, clients, complete=True):
|
||||||
|
"""Synthetic OpenVPN status file v2. clients: (cn, real_address, rx, tx, connected_since_ts[, client_id])."""
|
||||||
|
lines = ["TITLE,OpenVPN 2.6.8 x86_64-pc-linux-gnu", f"TIME,Mon Jan 1 00:00:00 2027,{int(now)}", HEADER]
|
||||||
|
for cn, real, rx, tx, since, *cid in clients:
|
||||||
|
lines.append(f"CLIENT_LIST,{cn},{real},10.8.0.2,,{rx},{tx},Mon Jan 1 00:00:00 2027,{since},"
|
||||||
|
f"UNDEF,{cid[0] if cid else 1},0,AES-256-GCM")
|
||||||
|
lines += ["HEADER,ROUTING_TABLE,Virtual Address,Common Name,Real Address,Last Ref,Last Ref (time_t)",
|
||||||
|
"GLOBAL_STATS,Max bcast/mcast queue length,0"]
|
||||||
|
if complete:
|
||||||
|
lines.append("END")
|
||||||
|
with open(path, "w") as f:
|
||||||
|
f.write("\n".join(lines) + "\n")
|
||||||
|
|
||||||
|
|
||||||
|
class Clock:
|
||||||
|
def __init__(self):
|
||||||
|
self.t = T0
|
||||||
|
|
||||||
|
def __call__(self):
|
||||||
|
return self.t
|
||||||
|
|
||||||
|
|
||||||
|
class FakeEvent:
|
||||||
|
"""Replaces threading.Event: records the pauses instead of sleeping."""
|
||||||
|
def __init__(self):
|
||||||
|
self.flag = False
|
||||||
|
self.delays = []
|
||||||
|
|
||||||
|
def is_set(self):
|
||||||
|
return self.flag
|
||||||
|
|
||||||
|
def set(self):
|
||||||
|
self.flag = True
|
||||||
|
|
||||||
|
def wait(self, timeout):
|
||||||
|
self.delays.append(timeout)
|
||||||
|
return self.flag
|
||||||
|
|
||||||
|
|
||||||
|
class Env:
|
||||||
|
def __init__(self, tmp_path):
|
||||||
|
self.status = str(tmp_path / "status.log")
|
||||||
|
self.db = str(tmp_path / "gatherer.db")
|
||||||
|
self.clock = Clock()
|
||||||
|
|
||||||
|
def gatherer(self):
|
||||||
|
"""New daemon 'started' at the current fake time (config.ini and log go to the cwd = tmp_path)."""
|
||||||
|
g = OpenVPNDataGatherer()
|
||||||
|
g._now = self.clock
|
||||||
|
g.started_at = self.clock()
|
||||||
|
return g
|
||||||
|
|
||||||
|
def tick(self, g, clients, complete=True, advance=10):
|
||||||
|
self.clock.t += advance
|
||||||
|
write_status(self.status, self.clock.t, clients, complete)
|
||||||
|
g.run_monitoring_cycle()
|
||||||
|
|
||||||
|
def query(self, sql, args=()):
|
||||||
|
conn = sqlite3.connect(self.db)
|
||||||
|
try:
|
||||||
|
return conn.execute(sql, args).fetchall()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def totals(self, cn):
|
||||||
|
return self.query("SELECT total_bytes_received, total_bytes_sent FROM clients WHERE common_name=?",
|
||||||
|
(cn,))[0]
|
||||||
|
|
||||||
|
def history_sum(self):
|
||||||
|
return self.query("SELECT COALESCE(SUM(bytes_received),0), COUNT(*) FROM usage_history")[0]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def env(tmp_path, monkeypatch):
|
||||||
|
monkeypatch.chdir(tmp_path) # the gatherer writes config.ini and its log into the cwd
|
||||||
|
e = Env(tmp_path)
|
||||||
|
monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_DB_PATH", e.db)
|
||||||
|
monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_LOG_PATH", e.status)
|
||||||
|
monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False)
|
||||||
|
return e
|
||||||
|
|
||||||
|
|
||||||
|
def test_new_fast_session_is_counted_from_zero(env):
|
||||||
|
g = env.gatherer()
|
||||||
|
since = T0 + 5 # started 5 s before the first frame
|
||||||
|
env.tick(g, [("alice", "1.1.1.1:1000", 50 * MB, MB, since)])
|
||||||
|
|
||||||
|
# BUG-03: 50 MB in the very first frame must not be dropped as "a continuing session"
|
||||||
|
assert env.totals("alice") == (50 * MB, MB)
|
||||||
|
assert env.query("SELECT bytes_received FROM usage_history") == [(50 * MB,)]
|
||||||
|
# active_sessions holds the real session start (UTC), not the first observation time
|
||||||
|
assert env.query("SELECT connected_since FROM active_sessions") == \
|
||||||
|
[(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(since)),)]
|
||||||
|
|
||||||
|
env.tick(g, [("alice", "1.1.1.1:1000", 51 * MB, MB, since)])
|
||||||
|
assert env.totals("alice") == (51 * MB, MB)
|
||||||
|
|
||||||
|
|
||||||
|
def test_daemon_restart_uses_snapshot_or_sets_baseline(env, caplog):
|
||||||
|
since = T0 + 5
|
||||||
|
g1 = env.gatherer()
|
||||||
|
env.tick(g1, [("alice", "1.1.1.1:1000", 1000, 500, since)])
|
||||||
|
env.tick(g1, [("alice", "1.1.1.1:1000", 3000, 700, since)])
|
||||||
|
assert env.totals("alice") == (3000, 700)
|
||||||
|
|
||||||
|
# Daemon restarts; the session is older than the daemon and the snapshot is in active_sessions:
|
||||||
|
# the traffic of the downtime is counted, nothing is counted twice
|
||||||
|
env.clock.t += 100
|
||||||
|
g2 = env.gatherer()
|
||||||
|
env.tick(g2, [("alice", "1.1.1.1:1000", 9000, 1700, since)])
|
||||||
|
assert env.totals("alice") == (9000, 1700)
|
||||||
|
|
||||||
|
# Snapshot lost: baseline, increment 0, one line in the log with the client name
|
||||||
|
conn = sqlite3.connect(env.db)
|
||||||
|
conn.execute("DELETE FROM active_sessions")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
env.clock.t += 100
|
||||||
|
g3 = env.gatherer()
|
||||||
|
with caplog.at_level(logging.WARNING):
|
||||||
|
env.tick(g3, [("alice", "1.1.1.1:1000", 20000, 2000, since)])
|
||||||
|
assert env.totals("alice") == (9000, 1700)
|
||||||
|
assert any(r.levelno == logging.WARNING and "alice" in r.getMessage() for r in caplog.records)
|
||||||
|
# the baseline works from now on
|
||||||
|
env.tick(g3, [("alice", "1.1.1.1:1000", 21000, 2100, since)])
|
||||||
|
assert env.totals("alice") == (10000, 1800)
|
||||||
|
|
||||||
|
|
||||||
|
def test_torn_read_skips_the_tick(env):
|
||||||
|
g = env.gatherer()
|
||||||
|
since = T0 + 5
|
||||||
|
env.tick(g, [("alice", "1.1.1.1:1000", 1000, 100, since)])
|
||||||
|
db_before = (env.totals("alice"), env.history_sum(),
|
||||||
|
env.query("SELECT status FROM clients"), env.query("SELECT * FROM active_sessions"))
|
||||||
|
cache_before = copy.deepcopy(g.session_cache)
|
||||||
|
|
||||||
|
# Frame without END (read while OpenVPN rewrites the file): no clients visible
|
||||||
|
env.tick(g, [], complete=False)
|
||||||
|
|
||||||
|
assert g.invalid_ticks == 1
|
||||||
|
assert (env.totals("alice"), env.history_sum(),
|
||||||
|
env.query("SELECT status FROM clients"), env.query("SELECT * FROM active_sessions")) == db_before
|
||||||
|
assert g.session_cache == cache_before
|
||||||
|
|
||||||
|
# Next intact frame: the difference for both intervals, no duplicates
|
||||||
|
env.tick(g, [("alice", "1.1.1.1:1000", 3000, 300, since)])
|
||||||
|
assert g.invalid_ticks == 0
|
||||||
|
assert env.totals("alice") == (3000, 300)
|
||||||
|
assert env.history_sum() == (3000, 2)
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_status_file_logs_sparingly_and_reports_recovery(env, caplog):
|
||||||
|
g = env.gatherer()
|
||||||
|
caplog.set_level(logging.INFO)
|
||||||
|
for _ in range(125): # no status file at all (OpenVPN not started yet)
|
||||||
|
g.run_monitoring_cycle()
|
||||||
|
skipped = [r for r in caplog.records if "Skipping tick" in r.getMessage()]
|
||||||
|
# tick 1, the threshold (6, ERROR), then every 60th
|
||||||
|
assert [r.getMessage().split("(")[1].split(" ")[0] for r in skipped] == ["1", "6", "60", "120"]
|
||||||
|
assert [r.levelno for r in skipped] == [logging.WARNING, logging.ERROR, logging.ERROR, logging.ERROR]
|
||||||
|
assert g.invalid_ticks == 125
|
||||||
|
|
||||||
|
caplog.clear()
|
||||||
|
env.tick(g, [("alice", "1.1.1.1:1000", 1000, 100, T0 + 5)])
|
||||||
|
again = [r for r in caplog.records if "readable again" in r.getMessage()]
|
||||||
|
assert len(again) == 1 and again[0].levelno == logging.INFO and "125" in again[0].getMessage()
|
||||||
|
assert g.invalid_ticks == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_session_missing_for_a_tick_and_beyond_grace(env):
|
||||||
|
g = env.gatherer()
|
||||||
|
since = T0 + 5
|
||||||
|
|
||||||
|
def alice(rx, s):
|
||||||
|
return [("alice", "1.1.1.1:1000", rx, 0, s)]
|
||||||
|
|
||||||
|
env.tick(g, alice(1000, since))
|
||||||
|
|
||||||
|
# Missing for one tick, returns with the same key: continues, no double counting
|
||||||
|
env.tick(g, [])
|
||||||
|
env.tick(g, alice(1500, since))
|
||||||
|
assert env.totals("alice") == (1500, 0)
|
||||||
|
assert env.history_sum()[0] == 1500
|
||||||
|
assert env.query("SELECT status FROM clients") == [("Active",)]
|
||||||
|
|
||||||
|
# Grace period (3 ticks): kept for two missing ticks, forgotten on the third
|
||||||
|
env.tick(g, [])
|
||||||
|
env.tick(g, [])
|
||||||
|
assert len(g.session_cache) == 1 and list(g.session_cache.values())[0]["missing_ticks"] == 2
|
||||||
|
env.tick(g, [])
|
||||||
|
assert g.session_cache == {}
|
||||||
|
|
||||||
|
# Reconnect with a new connected_since: counted from zero (50 MB in the first frame)
|
||||||
|
env.tick(g, alice(50 * MB, env.clock.t + 10 - 5))
|
||||||
|
assert env.totals("alice") == (1500 + 50 * MB, 0)
|
||||||
|
assert len(g.session_cache) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_two_sessions_of_one_cn_are_one_record(env):
|
||||||
|
g = env.gatherer()
|
||||||
|
s1, s2 = T0 + 5, T0 + 8
|
||||||
|
|
||||||
|
def tick(rx1, rx2):
|
||||||
|
# скорость считается за 10 с (реальные часы теста не управляются)
|
||||||
|
g.last_check_time = datetime.now() - timedelta(seconds=10)
|
||||||
|
env.tick(g, [("alice", "1.1.1.1:1000", rx1, rx1 // 10, s1, 1),
|
||||||
|
("alice", "2.2.2.2:2000", rx2, rx2 // 10, s2, 2)])
|
||||||
|
|
||||||
|
tick(1000, 500)
|
||||||
|
tick(3000, 1500)
|
||||||
|
# Итоги = сумма обеих сессий; одна строка истории на тик, скорость = сумма сессий
|
||||||
|
assert env.totals("alice") == (4500, 450)
|
||||||
|
rows = env.query("SELECT bytes_received, bytes_received_rate_mbps FROM usage_history ORDER BY id")
|
||||||
|
assert [r[0] for r in rows] == [1500, 3000]
|
||||||
|
assert rows[1][1] == pytest.approx(3000 * 8 / 10 / 1_000_000, rel=0.01)
|
||||||
|
assert env.query("SELECT bytes_received FROM stats_5min") == [(4500,)]
|
||||||
|
|
||||||
|
# Одна сессия отключилась: статус Active, итог растёт только приростом оставшейся
|
||||||
|
env.tick(g, [("alice", "1.1.1.1:1000", 4000, 400, s1, 1)])
|
||||||
|
assert env.totals("alice") == (5500, 550)
|
||||||
|
assert env.query("SELECT status FROM clients") == [("Active",)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_float_keeps_the_session_by_client_id(env):
|
||||||
|
since = T0 + 5
|
||||||
|
g = env.gatherer()
|
||||||
|
env.tick(g, [("alice", "1.1.1.1:1000", 1000, 100, since, 7)])
|
||||||
|
# float: другой адрес, тот же Client ID и начало - прирост = разница счётчиков
|
||||||
|
env.tick(g, [("alice", "2.2.2.2:2000", 3000, 300, since, 7)])
|
||||||
|
assert env.totals("alice") == (3000, 300)
|
||||||
|
assert env.query("SELECT real_address, session_id FROM active_sessions") == [("2.2.2.2:2000", "7")]
|
||||||
|
|
||||||
|
# Перезапуск демона: базовая линия из снимка по Client ID, адрес снова другой
|
||||||
|
env.clock.t += 100
|
||||||
|
g2 = env.gatherer()
|
||||||
|
env.tick(g2, [("alice", "3.3.3.3:3000", 9000, 900, since, 7)])
|
||||||
|
assert env.totals("alice") == (9000, 900)
|
||||||
|
|
||||||
|
|
||||||
|
def test_loop_survives_exceptions_and_stops_on_signal(env):
|
||||||
|
g = env.gatherer()
|
||||||
|
g.stop_event = FakeEvent()
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def cycle():
|
||||||
|
calls.append(1)
|
||||||
|
if len(calls) <= 2:
|
||||||
|
raise RuntimeError("boom")
|
||||||
|
if len(calls) == 4:
|
||||||
|
g._handle_signal(signal.SIGTERM, None) # what the SIGTERM handler does
|
||||||
|
|
||||||
|
g.run_monitoring_cycle = cycle
|
||||||
|
g.start_monitoring() # returns normally, no exception escapes
|
||||||
|
|
||||||
|
# 2 failures (exponential pause), 1 success (reset), the cycle that got the signal finishes, then exit
|
||||||
|
assert len(calls) == 4
|
||||||
|
assert g.stop_event.delays == [20, 40, 10, 10]
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
import glob
|
||||||
|
import hashlib
|
||||||
|
import sqlite3
|
||||||
|
import threading
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import migrations
|
||||||
|
from db import DatabaseManager
|
||||||
|
|
||||||
|
CLIENTS_SQL = """
|
||||||
|
CREATE TABLE clients (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
common_name TEXT UNIQUE NOT NULL,
|
||||||
|
real_address TEXT,
|
||||||
|
status TEXT DEFAULT 'Active',
|
||||||
|
total_bytes_received INTEGER DEFAULT 0,
|
||||||
|
total_bytes_sent INTEGER DEFAULT 0,
|
||||||
|
last_bytes_received INTEGER DEFAULT 0,
|
||||||
|
last_bytes_sent INTEGER DEFAULT 0,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
CREATE TABLE usage_history (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
client_id INTEGER,
|
||||||
|
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
bytes_received INTEGER,
|
||||||
|
bytes_sent INTEGER,
|
||||||
|
bytes_received_rate_mbps REAL,
|
||||||
|
bytes_sent_rate_mbps REAL,
|
||||||
|
FOREIGN KEY (client_id) REFERENCES clients (id)
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_usage_ts ON usage_history(timestamp);
|
||||||
|
"""
|
||||||
|
|
||||||
|
STATS_SQL = "".join(f"""
|
||||||
|
CREATE TABLE {t} (
|
||||||
|
timestamp TEXT NOT NULL,
|
||||||
|
client_id INTEGER NOT NULL,
|
||||||
|
bytes_received INTEGER DEFAULT 0,
|
||||||
|
bytes_sent INTEGER DEFAULT 0,
|
||||||
|
PRIMARY KEY (timestamp, client_id),
|
||||||
|
FOREIGN KEY (client_id) REFERENCES clients (id)
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_{t}_ts ON {t}(timestamp);
|
||||||
|
""" for t in ["stats_5min", "stats_15min", "stats_hourly", "stats_6h", "stats_daily"])
|
||||||
|
|
||||||
|
# Oldest schema: APP/db.py at commit c9af0a5 (no active_sessions, users, login_attempts),
|
||||||
|
# plus a legacy users table without the 2FA columns (the case _ensure_column was written for;
|
||||||
|
# no commit holds that table definition, it is reconstructed from the migration step)
|
||||||
|
OLDEST_SQL = CLIENTS_SQL + STATS_SQL + """
|
||||||
|
CREATE TABLE users (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
username TEXT UNIQUE NOT NULL,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Baseline: APP_CORE/db.py at commit 3836049 (identical to the schema today)
|
||||||
|
BASELINE_SQL = CLIENTS_SQL + STATS_SQL + """
|
||||||
|
CREATE TABLE active_sessions (
|
||||||
|
client_id INTEGER,
|
||||||
|
common_name TEXT,
|
||||||
|
real_address TEXT,
|
||||||
|
bytes_received INTEGER,
|
||||||
|
bytes_sent INTEGER,
|
||||||
|
connected_since TIMESTAMP,
|
||||||
|
last_seen TIMESTAMP,
|
||||||
|
FOREIGN KEY (client_id) REFERENCES clients (id)
|
||||||
|
);
|
||||||
|
CREATE TABLE users (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
username TEXT UNIQUE NOT NULL,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
totp_secret TEXT,
|
||||||
|
is_2fa_enabled INTEGER DEFAULT 0,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
CREATE TABLE login_attempts (
|
||||||
|
ip_address TEXT PRIMARY KEY,
|
||||||
|
attempts INTEGER DEFAULT 0,
|
||||||
|
last_attempt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
|
||||||
|
ROWS_SQL = """
|
||||||
|
INSERT INTO clients (id, common_name, real_address, total_bytes_received, total_bytes_sent)
|
||||||
|
VALUES (1, 'alice', '10.0.0.1:1000', 1000, 2000);
|
||||||
|
INSERT INTO clients (id, common_name, real_address, total_bytes_received, total_bytes_sent)
|
||||||
|
VALUES (2, 'bob', '10.0.0.2:2000', 3000, 4000);
|
||||||
|
INSERT INTO usage_history (client_id, timestamp, bytes_received, bytes_sent)
|
||||||
|
VALUES (1, '2026-01-01 10:00:00', 10, 20);
|
||||||
|
INSERT INTO usage_history (client_id, timestamp, bytes_received, bytes_sent)
|
||||||
|
VALUES (2, '2026-01-01 10:00:10', 30, 40);
|
||||||
|
INSERT INTO stats_5min (timestamp, client_id, bytes_received, bytes_sent)
|
||||||
|
VALUES ('2026-01-01 10:00:00', 1, 10, 20);
|
||||||
|
INSERT INTO users (id, username, password_hash) VALUES (1, 'admin', 'hash');
|
||||||
|
"""
|
||||||
|
|
||||||
|
SCHEMAS = {"oldest_c9af0a5": OLDEST_SQL, "baseline_3836049": BASELINE_SQL}
|
||||||
|
DATA_QUERIES = [
|
||||||
|
"SELECT * FROM clients ORDER BY id",
|
||||||
|
"SELECT * FROM usage_history ORDER BY id",
|
||||||
|
"SELECT * FROM stats_5min",
|
||||||
|
"SELECT id, username, password_hash FROM users",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _auto_migrate(monkeypatch):
|
||||||
|
monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False)
|
||||||
|
|
||||||
|
|
||||||
|
def make_db(path, schema_sql, extra_sql=ROWS_SQL):
|
||||||
|
conn = sqlite3.connect(path)
|
||||||
|
conn.executescript(schema_sql + extra_sql)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def query(path, sql):
|
||||||
|
conn = sqlite3.connect(path)
|
||||||
|
try:
|
||||||
|
return conn.execute(sql).fetchall()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def table_names(path):
|
||||||
|
return {r[0] for r in query(path, "SELECT name FROM sqlite_master WHERE type='table'")}
|
||||||
|
|
||||||
|
|
||||||
|
def sha(path):
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
return hashlib.sha256(f.read()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("schema", SCHEMAS)
|
||||||
|
def test_old_schema_is_migrated_without_data_loss(tmp_path, schema):
|
||||||
|
db = str(tmp_path / "old.db")
|
||||||
|
make_db(db, SCHEMAS[schema])
|
||||||
|
before = [query(db, q) for q in DATA_QUERIES]
|
||||||
|
|
||||||
|
report = migrations.run(db)
|
||||||
|
|
||||||
|
# Original rows intact
|
||||||
|
assert [query(db, q) for q in DATA_QUERIES] == before
|
||||||
|
# Missing tables and columns are there, existing rows get the defaults
|
||||||
|
assert {"active_sessions", "users", "login_attempts"} <= table_names(db)
|
||||||
|
assert query(db, "SELECT totp_secret, is_2fa_enabled FROM users") == [(None, 0)]
|
||||||
|
assert query(db, "SELECT session_id FROM active_sessions") in ([], [(None,)]) # migration 2: column exists, NULL
|
||||||
|
# Stamped, and the backup is the untouched pre-migration copy
|
||||||
|
assert query(db, "SELECT version, name FROM schema_migrations") == [(1, "baseline"), (2, "session_id")]
|
||||||
|
backups = glob.glob(db + ".bak-*")
|
||||||
|
assert backups == [report.backup]
|
||||||
|
assert [query(backups[0], q) for q in DATA_QUERIES] == before
|
||||||
|
assert "schema_migrations" not in table_names(backups[0])
|
||||||
|
assert query(backups[0], "PRAGMA integrity_check") == [("ok",)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_second_run_is_a_noop(tmp_path):
|
||||||
|
db = str(tmp_path / "old.db")
|
||||||
|
make_db(db, OLDEST_SQL)
|
||||||
|
migrations.run(db)
|
||||||
|
first = sha(db)
|
||||||
|
|
||||||
|
report = migrations.run(db)
|
||||||
|
|
||||||
|
assert report.applied == [] and report.backup is None
|
||||||
|
assert len(glob.glob(db + ".bak-*")) == 1
|
||||||
|
assert sha(db) == first
|
||||||
|
|
||||||
|
|
||||||
|
def test_too_new_database_is_not_touched(tmp_path, monkeypatch):
|
||||||
|
db = str(tmp_path / "new.db")
|
||||||
|
make_db(db, BASELINE_SQL, ROWS_SQL + """
|
||||||
|
CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT);
|
||||||
|
INSERT INTO schema_migrations VALUES (9999, 'from the future', '2030-01-01T00:00:00Z');
|
||||||
|
""")
|
||||||
|
before = sha(db)
|
||||||
|
|
||||||
|
with pytest.raises(migrations.SchemaTooNew):
|
||||||
|
migrations.run(db)
|
||||||
|
|
||||||
|
# The service itself refuses to start: exit code 1, no traceback
|
||||||
|
monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_DB_PATH", db)
|
||||||
|
with pytest.raises(SystemExit) as exc:
|
||||||
|
DatabaseManager(str(tmp_path / "none.ini")).init_database()
|
||||||
|
assert exc.value.code == 1
|
||||||
|
|
||||||
|
assert sha(db) == before
|
||||||
|
assert glob.glob(db + ".bak-*") == []
|
||||||
|
assert len(query(db, "SELECT * FROM clients")) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_fresh_database_gets_full_schema_without_backup(tmp_path):
|
||||||
|
db = str(tmp_path / "fresh.db")
|
||||||
|
|
||||||
|
report = migrations.run(db)
|
||||||
|
|
||||||
|
assert report.created and report.backup is None
|
||||||
|
assert glob.glob(db + ".bak-*") == []
|
||||||
|
assert {"clients", "usage_history", "active_sessions", "users", "login_attempts",
|
||||||
|
"stats_5min", "stats_daily", "schema_migrations"} <= table_names(db)
|
||||||
|
assert query(db, "SELECT version FROM schema_migrations") == [(1,), (2,)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_auto_migrate_off_refuses_while_pending(tmp_path, monkeypatch):
|
||||||
|
db = str(tmp_path / "old.db")
|
||||||
|
make_db(db, OLDEST_SQL)
|
||||||
|
before = sha(db)
|
||||||
|
monkeypatch.setenv("OVPMON_AUTO_MIGRATE", "0")
|
||||||
|
|
||||||
|
with pytest.raises(migrations.MigrationPending, match="migrate.py"):
|
||||||
|
migrations.startup(db)
|
||||||
|
assert sha(db) == before
|
||||||
|
|
||||||
|
migrations.run(db)
|
||||||
|
migrations.startup(db) # up to date: allowed
|
||||||
|
|
||||||
|
|
||||||
|
def test_simultaneous_start_makes_one_backup(tmp_path):
|
||||||
|
db = str(tmp_path / "old.db")
|
||||||
|
make_db(db, OLDEST_SQL)
|
||||||
|
barrier = threading.Barrier(2)
|
||||||
|
reports, errors = [], []
|
||||||
|
|
||||||
|
def start():
|
||||||
|
try:
|
||||||
|
barrier.wait()
|
||||||
|
reports.append(migrations.run(db))
|
||||||
|
except Exception as e: # pragma: no cover
|
||||||
|
errors.append(e)
|
||||||
|
|
||||||
|
threads = [threading.Thread(target=start) for _ in range(2)]
|
||||||
|
for t in threads:
|
||||||
|
t.start()
|
||||||
|
for t in threads:
|
||||||
|
t.join()
|
||||||
|
|
||||||
|
assert errors == []
|
||||||
|
assert len(glob.glob(db + ".bak-*")) == 1
|
||||||
|
assert sorted(len(r.applied) for r in reports) == [0, len(migrations.MIGRATIONS)]
|
||||||
|
assert query(db, "SELECT version FROM schema_migrations") == [(1,), (2,)]
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import importlib
|
||||||
|
import sqlite3
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
FMT_SINCE = '2026-11-12 10:00:00'
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def api(tmp_path, monkeypatch):
|
||||||
|
monkeypatch.chdir(tmp_path)
|
||||||
|
monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_DB_PATH", str(tmp_path / "api.db"))
|
||||||
|
monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False)
|
||||||
|
module = importlib.import_module("openvpn_api_v3")
|
||||||
|
return module.OpenVPNAPI()
|
||||||
|
|
||||||
|
|
||||||
|
def test_stats_include_sessions(api):
|
||||||
|
conn = sqlite3.connect(api.db_manager.db_path)
|
||||||
|
for cn, status in (('alice', 'Active'), ('bob', 'Active'), ('carol', 'Disconnected')):
|
||||||
|
conn.execute("INSERT INTO clients (common_name, status, real_address) VALUES (?,?,?)",
|
||||||
|
(cn, status, '1.1.1.1:1000'))
|
||||||
|
ids = {cn: i for i, cn in conn.execute("SELECT id, common_name FROM clients")}
|
||||||
|
mb = 1024 * 1024
|
||||||
|
for cn, addr, rx, tx in (('alice', '1.1.1.1:1000', 2 * mb, mb), ('alice', '2.2.2.2:2000', 0, 0),
|
||||||
|
('bob', '3.3.3.3:3000', mb, mb)):
|
||||||
|
conn.execute("INSERT INTO active_sessions (client_id, common_name, real_address, bytes_received,"
|
||||||
|
" bytes_sent, connected_since, last_seen, session_id) VALUES (?,?,?,?,?,?,?,?)",
|
||||||
|
(ids[cn], cn, addr, rx, tx, FMT_SINCE, FMT_SINCE, None))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
by_cn = {c['common_name']: c for c in api.get_current_stats()}
|
||||||
|
assert by_cn['alice']['sessions_count'] == 2
|
||||||
|
assert {s['real_address'] for s in by_cn['alice']['sessions']} == {'1.1.1.1:1000', '2.2.2.2:2000'}
|
||||||
|
first = next(s for s in by_cn['alice']['sessions'] if s['real_address'] == '1.1.1.1:1000')
|
||||||
|
assert (first['received_mb'], first['sent_mb'], first['connected_since']) == (2.0, 1.0, FMT_SINCE)
|
||||||
|
assert by_cn['bob']['sessions_count'] == 1
|
||||||
|
assert by_cn['carol']['sessions_count'] == 0 and by_cn['carol']['sessions'] == []
|
||||||
|
# existing fields are unchanged
|
||||||
|
assert by_cn['alice']['real_address'] == '1.1.1.1:1000' and by_cn['alice']['status'] == 'Active'
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
|
from secret_key import resolve_secret_key, SecretKeyError
|
||||||
|
|
||||||
|
GOOD = "0123456789abcdef" * 4 # 64 hex characters
|
||||||
|
|
||||||
|
|
||||||
|
def test_weak_or_missing_key_is_refused():
|
||||||
|
for bad in (None, "", " ", "ovpmon-secret-change-me", "Change-Me-Please", "k" * 31):
|
||||||
|
with pytest.raises(SecretKeyError) as exc:
|
||||||
|
resolve_secret_key(bad, None)
|
||||||
|
assert "openssl rand -hex 32" in str(exc.value)
|
||||||
|
if bad and bad.strip():
|
||||||
|
assert bad not in str(exc.value) # the key value is never part of the message
|
||||||
|
# the same checks apply to the config.ini value
|
||||||
|
with pytest.raises(SecretKeyError):
|
||||||
|
resolve_secret_key(None, "ovpmon-secret-change-me")
|
||||||
|
# legacy variable name is called out explicitly
|
||||||
|
with pytest.raises(SecretKeyError) as exc:
|
||||||
|
resolve_secret_key(None, "", legacy_env=GOOD)
|
||||||
|
assert "OVPMON_SECRET_KEY" in str(exc.value) and "OVPMON_API_SECRET_KEY" in str(exc.value)
|
||||||
|
assert GOOD not in str(exc.value)
|
||||||
|
|
||||||
|
|
||||||
|
def test_good_key_and_priority():
|
||||||
|
assert resolve_secret_key(GOOD, None) == (GOOD, "environment")
|
||||||
|
assert resolve_secret_key(None, GOOD) == (GOOD, "config.ini")
|
||||||
|
# environment wins over config.ini, even when the config.ini value is the old default
|
||||||
|
assert resolve_secret_key(GOOD, "ovpmon-secret-change-me") == (GOOD, "environment")
|
||||||
@@ -11,7 +11,12 @@ COPY requirements.txt .
|
|||||||
RUN pip install --no-cache-dir -r requirements.txt
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
# Ensure DB directory exists
|
# Ensure DB directory exists
|
||||||
RUN mkdir -p /app/db
|
RUN mkdir -p /app/db /app/backups
|
||||||
|
|
||||||
|
# Migrations of the monitoring database (standard library only), from the build context 'core'
|
||||||
|
# (additional_contexts in docker-compose.yml). A restore migrates the package copy with them.
|
||||||
|
COPY --from=core migrations.py migrate.py db.py /opt/core/
|
||||||
|
ENV OVPMON_CORE_DIR=/opt/core
|
||||||
|
|
||||||
# Copy source code and entrypoint
|
# Copy source code and entrypoint
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|||||||
@@ -19,6 +19,9 @@ python3 -m venv venv
|
|||||||
source venv/bin/activate
|
source venv/bin/activate
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# JWT key (required, no built-in default; at least 32 characters). Must be the same value as for APP_CORE
|
||||||
|
export OVPMON_API_SECRET_KEY=$(openssl rand -hex 32)
|
||||||
|
|
||||||
# Run
|
# Run
|
||||||
python3 main.py
|
python3 main.py
|
||||||
# Swagger UI available at http://localhost:8000/docs
|
# Swagger UI available at http://localhost:8000/docs
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
[api]
|
[api]
|
||||||
# Secret key for JWT token verification.
|
# Secret key for JWT token verification.
|
||||||
# MUST match the key in APP_CORE/config.ini if not overridden by ENV.
|
# MUST match the key of APP_CORE (same OVPMON_API_SECRET_KEY or the same value in its config.ini).
|
||||||
secret_key = ovpmon-secret-change-me
|
# Set OVPMON_API_SECRET_KEY or this value; at least 32 characters, random (openssl rand -hex 32). There is no built-in default.
|
||||||
|
secret_key =
|
||||||
|
|
||||||
[profiler]
|
[profiler]
|
||||||
# Path to the profiler database relative to component root
|
# Path to the profiler database relative to component root
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
# utils.auth refuses to import without a strong JWT key (no built-in default), and tests import
|
||||||
|
# main: give them a throwaway key before anything is imported. A real key in the environment is
|
||||||
|
# left untouched.
|
||||||
|
os.environ.setdefault("OVPMON_API_SECRET_KEY", "x" * 64)
|
||||||
+18
-5
@@ -1,5 +1,6 @@
|
|||||||
import uvicorn
|
import uvicorn
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
import logging
|
||||||
import sys
|
import sys
|
||||||
import os
|
import os
|
||||||
|
|
||||||
@@ -7,16 +8,27 @@ import os
|
|||||||
import os
|
import os
|
||||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
|
||||||
from database import engine, Base
|
from database import db_path
|
||||||
from routers import system, server, profiles, server_process
|
import migrations
|
||||||
|
from routers import system, server, profiles, server_process, backup
|
||||||
from utils.logging import setup_logging
|
from utils.logging import setup_logging
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
# Create Database Tables
|
|
||||||
Base.metadata.create_all(bind=engine)
|
|
||||||
|
|
||||||
setup_logging()
|
setup_logging()
|
||||||
|
|
||||||
|
# Create or upgrade the database schema (versioned migrations, backup before any change).
|
||||||
|
# Exits with a clear message if the database is newer than this code or migrations are
|
||||||
|
# pending while OVPMON_AUTO_MIGRATE=0.
|
||||||
|
migrations.startup_or_exit(db_path)
|
||||||
|
|
||||||
|
# Settings, destinations and history of backup and restore (own SQLite file, see services/backup/store.py).
|
||||||
|
# A failure here must not stop the VPN management: the backup routes then report the error.
|
||||||
|
try:
|
||||||
|
from services.backup import store as backup_store
|
||||||
|
backup_store.init()
|
||||||
|
except Exception:
|
||||||
|
logging.getLogger(__name__).exception("Backup store is not available")
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="OpenVPN Profiler API",
|
title="OpenVPN Profiler API",
|
||||||
description="REST API for managing OpenVPN profiles and configuration",
|
description="REST API for managing OpenVPN profiles and configuration",
|
||||||
@@ -36,6 +48,7 @@ app.include_router(system.router, prefix="/api", tags=["System"])
|
|||||||
app.include_router(server.router, prefix="/api", tags=["Server"])
|
app.include_router(server.router, prefix="/api", tags=["Server"])
|
||||||
app.include_router(profiles.router, prefix="/api", tags=["Profiles"])
|
app.include_router(profiles.router, prefix="/api", tags=["Profiles"])
|
||||||
app.include_router(server_process.router, prefix="/api", tags=["Process Control"])
|
app.include_router(server_process.router, prefix="/api", tags=["Process Control"])
|
||||||
|
app.include_router(backup.router, prefix="/api", tags=["Backup"])
|
||||||
|
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
def read_root():
|
def read_root():
|
||||||
|
|||||||
Executable
+67
@@ -0,0 +1,67 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Apply pending database migrations (or only check for them).
|
||||||
|
|
||||||
|
python migrate.py apply pending migrations (backup first)
|
||||||
|
python migrate.py --check only report; exit 0 = up to date, 2 = pending, 1 = error / too new
|
||||||
|
python migrate.py --db PATH use this database file instead of the configured one
|
||||||
|
|
||||||
|
Run it from the component directory with the component's virtualenv, like the service.
|
||||||
|
The services apply pending migrations themselves at start (unless OVPMON_AUTO_MIGRATE=0).
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import migrations
|
||||||
|
from database import db_path as configured_db_path
|
||||||
|
|
||||||
|
EXIT_OK, EXIT_ERROR, EXIT_PENDING = 0, 1, 2
|
||||||
|
|
||||||
|
|
||||||
|
def default_db_path():
|
||||||
|
return configured_db_path
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
parser = argparse.ArgumentParser(description="Database schema migrations")
|
||||||
|
parser.add_argument("--check", action="store_true",
|
||||||
|
help="only report: exit 0 = up to date, 2 = pending, 1 = error")
|
||||||
|
parser.add_argument("--db", metavar="PATH", help="database file (default: from configuration)")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
|
||||||
|
db_path = args.db or default_db_path()
|
||||||
|
|
||||||
|
try:
|
||||||
|
st = migrations.status(db_path)
|
||||||
|
if st.too_new:
|
||||||
|
raise migrations._too_new_error(st)
|
||||||
|
print(f"Database: {db_path}" + ("" if st.exists else " (does not exist yet)"))
|
||||||
|
if not st.exists and not args.db:
|
||||||
|
print("Hint: the default database was used; for an installed system set OVPMON_PROFILER_DB_PATH "
|
||||||
|
"(see /etc/ovpmon/env) or pass --db PATH")
|
||||||
|
if args.check:
|
||||||
|
print(f"Schema version: {st.current} (latest known: {migrations.latest_version()})")
|
||||||
|
if not st.pending:
|
||||||
|
print("Pending: none, up to date")
|
||||||
|
return EXIT_OK
|
||||||
|
print("Pending: " + ", ".join(f"{m.version} ({m.name})" for m in st.pending))
|
||||||
|
return EXIT_PENDING
|
||||||
|
before = st.current
|
||||||
|
report = migrations.run(db_path)
|
||||||
|
except migrations.MigrationError as e:
|
||||||
|
print(f"ERROR: {e}", file=sys.stderr)
|
||||||
|
return EXIT_ERROR
|
||||||
|
|
||||||
|
print(f"Schema version: {before} -> {report.version}")
|
||||||
|
if report.applied:
|
||||||
|
print("Applied: " + ", ".join(f"{v} ({n})" for v, n in report.applied))
|
||||||
|
else:
|
||||||
|
print("Applied: nothing, already up to date")
|
||||||
|
print(f"Backup: {report.backup or 'none'}"
|
||||||
|
+ (" (new database)" if report.created else ""))
|
||||||
|
return EXIT_OK
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,447 @@
|
|||||||
|
"""Versioned, additive-only schema migrations for the component's SQLite database.
|
||||||
|
|
||||||
|
The generic part (everything above "Migrations of this component") is the same in
|
||||||
|
APP_CORE/migrations.py and APP_PROFILER/migrations.py: the components have separate
|
||||||
|
build contexts and virtualenvs, so each carries its own copy. Keep them in sync.
|
||||||
|
|
||||||
|
Safety rules:
|
||||||
|
- a migration only adds (tables, columns, indexes); it never drops or rewrites data;
|
||||||
|
- before the first change a consistent backup is made with the SQLite backup API
|
||||||
|
('<db>.bak-<UTC timestamp>'), unless the database is brand new;
|
||||||
|
- every migration runs in its own savepoint inside one write-locked transaction, so
|
||||||
|
two processes starting at the same time cannot race (the second one waits, then
|
||||||
|
finds nothing pending);
|
||||||
|
- afterwards PRAGMA integrity_check and the row counts of all pre-existing tables are
|
||||||
|
compared with the backup; on a mismatch everything is rolled back;
|
||||||
|
- a database with a higher schema version than the code knows is never touched.
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sqlite3
|
||||||
|
import stat
|
||||||
|
import sys
|
||||||
|
import urllib.parse
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Callable, Optional
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
BACKUPS_KEEP = 5 # number of '<db>.bak-*' files kept per database
|
||||||
|
LOCK_TIMEOUT = 60 # seconds a second process waits for the migration lock
|
||||||
|
|
||||||
|
|
||||||
|
class MigrationError(Exception):
|
||||||
|
"""A migration could not be applied or verified."""
|
||||||
|
|
||||||
|
|
||||||
|
class SchemaTooNew(MigrationError):
|
||||||
|
"""The database was migrated by a newer release than this code."""
|
||||||
|
|
||||||
|
|
||||||
|
class MigrationPending(MigrationError):
|
||||||
|
"""Migrations are pending but automatic migration is disabled."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Migration:
|
||||||
|
version: int
|
||||||
|
name: str
|
||||||
|
apply: Callable[[sqlite3.Connection], None] # runs inside a transaction, no commit
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Status:
|
||||||
|
db_path: str
|
||||||
|
exists: bool
|
||||||
|
fresh: bool # no tables and no recorded migrations
|
||||||
|
applied: dict = field(default_factory=dict) # version -> name
|
||||||
|
pending: list = field(default_factory=list) # [Migration]
|
||||||
|
too_new: Optional[int] = None # highest version if above the code's
|
||||||
|
|
||||||
|
@property
|
||||||
|
def current(self):
|
||||||
|
return max(self.applied) if self.applied else 0
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Report:
|
||||||
|
db_path: str
|
||||||
|
version: int # schema version after the run
|
||||||
|
applied: list = field(default_factory=list) # [(version, name)] applied by this run
|
||||||
|
backup: Optional[str] = None
|
||||||
|
created: bool = False # the database was new and got the current schema
|
||||||
|
|
||||||
|
|
||||||
|
def latest_version():
|
||||||
|
return max((m.version for m in MIGRATIONS), default=0)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_path(target):
|
||||||
|
"""Accept a path or a SQLAlchemy engine."""
|
||||||
|
if isinstance(target, (str, os.PathLike)):
|
||||||
|
return os.fspath(target)
|
||||||
|
url = getattr(target, "url", None)
|
||||||
|
if url is not None and url.database:
|
||||||
|
return url.database
|
||||||
|
raise TypeError(f"Cannot get a database path from {target!r}")
|
||||||
|
|
||||||
|
|
||||||
|
def _quote(name):
|
||||||
|
return '"' + name.replace('"', '""') + '"'
|
||||||
|
|
||||||
|
|
||||||
|
def _tables(conn):
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT name FROM sqlite_master WHERE type='table' "
|
||||||
|
"AND substr(name, 1, 7) != 'sqlite_' ORDER BY name")
|
||||||
|
return [r[0] for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def _read_status(conn, db_path):
|
||||||
|
tables = _tables(conn)
|
||||||
|
applied = {}
|
||||||
|
if "schema_migrations" in tables:
|
||||||
|
applied = {v: n for v, n in conn.execute("SELECT version, name FROM schema_migrations")}
|
||||||
|
known = latest_version()
|
||||||
|
too_new = max(applied) if applied and max(applied) > known else None
|
||||||
|
pending = sorted((m for m in MIGRATIONS if m.version not in applied), key=lambda m: m.version)
|
||||||
|
fresh = not [t for t in tables if t != "schema_migrations"] and not applied
|
||||||
|
return Status(db_path, True, fresh, applied, pending, too_new)
|
||||||
|
|
||||||
|
|
||||||
|
def _too_new_error(st):
|
||||||
|
return SchemaTooNew(
|
||||||
|
f"Database {st.db_path} has schema version {st.too_new}, but this release only knows "
|
||||||
|
f"versions up to {latest_version()}. It was migrated by a newer release. The database "
|
||||||
|
f"has not been touched and the service will not start. Install the newer release, or "
|
||||||
|
f"restore a matching backup ('{st.db_path}.bak-*') with the services stopped.")
|
||||||
|
|
||||||
|
|
||||||
|
def _quick_status(db_path):
|
||||||
|
"""Read-only look at the database, no lock and no changes. None if it cannot be read."""
|
||||||
|
if not os.path.exists(db_path):
|
||||||
|
return Status(db_path, False, True, {}, sorted(MIGRATIONS, key=lambda m: m.version))
|
||||||
|
uri = "file:%s?mode=ro" % urllib.parse.quote(os.path.abspath(db_path))
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(uri, uri=True, timeout=LOCK_TIMEOUT)
|
||||||
|
try:
|
||||||
|
return _read_status(conn, db_path)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
except sqlite3.Error:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def status(target):
|
||||||
|
"""Report applied and pending migrations without changing anything."""
|
||||||
|
db_path = _resolve_path(target)
|
||||||
|
st = _quick_status(db_path)
|
||||||
|
if st is None:
|
||||||
|
raise MigrationError(f"Cannot read database {db_path} (not a SQLite database, or locked)")
|
||||||
|
return st
|
||||||
|
|
||||||
|
|
||||||
|
def _integrity_problems(conn):
|
||||||
|
rows = [r[0] for r in conn.execute("PRAGMA integrity_check")]
|
||||||
|
return [] if rows == ["ok"] else rows[:5]
|
||||||
|
|
||||||
|
|
||||||
|
def _row_counts(conn):
|
||||||
|
return {t: conn.execute(f"SELECT COUNT(*) FROM {_quote(t)}").fetchone()[0]
|
||||||
|
for t in _tables(conn)}
|
||||||
|
|
||||||
|
|
||||||
|
def _backup(conn, db_path):
|
||||||
|
"""Consistent copy through the SQLite backup API. Returns (path, row counts of the copy)."""
|
||||||
|
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
|
||||||
|
dest = f"{db_path}.bak-{stamp}"
|
||||||
|
n = 0
|
||||||
|
while os.path.exists(dest):
|
||||||
|
n += 1
|
||||||
|
dest = f"{db_path}.bak-{stamp}-{n}"
|
||||||
|
tmp = dest + ".part"
|
||||||
|
try:
|
||||||
|
dst = sqlite3.connect(tmp)
|
||||||
|
# A separate read-only connection: the backup API stalls when the source connection
|
||||||
|
# itself holds the write lock. Nothing has been modified yet, so the copy is consistent.
|
||||||
|
src = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=LOCK_TIMEOUT)
|
||||||
|
try:
|
||||||
|
src.backup(dst)
|
||||||
|
problems = _integrity_problems(dst)
|
||||||
|
if problems:
|
||||||
|
raise MigrationError("backup copy failed the integrity check: " + "; ".join(problems))
|
||||||
|
counts = _row_counts(dst)
|
||||||
|
finally:
|
||||||
|
src.close()
|
||||||
|
dst.close()
|
||||||
|
# The copy holds the same secrets as the database: same permissions
|
||||||
|
os.chmod(tmp, stat.S_IMODE(os.stat(db_path).st_mode))
|
||||||
|
os.replace(tmp, dest)
|
||||||
|
except Exception as e:
|
||||||
|
try:
|
||||||
|
os.remove(tmp)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
raise MigrationError(f"Cannot back up {db_path} ({e}). Nothing was changed.") from e
|
||||||
|
logger.info(f"Database backup created: {dest}")
|
||||||
|
return dest, counts
|
||||||
|
|
||||||
|
|
||||||
|
def _prune_backups(db_path, keep=BACKUPS_KEEP):
|
||||||
|
"""Keep the newest `keep` backups of this database only."""
|
||||||
|
directory = os.path.dirname(os.path.abspath(db_path))
|
||||||
|
pattern = re.compile(re.escape(os.path.basename(db_path)) + r"\.bak-(\d{8}T\d{6})(?:-(\d+))?$")
|
||||||
|
found = []
|
||||||
|
for name in os.listdir(directory):
|
||||||
|
m = pattern.match(name)
|
||||||
|
if m:
|
||||||
|
found.append((m.group(1), int(m.group(2) or 0), name))
|
||||||
|
found.sort()
|
||||||
|
for _, _, name in (found[:-keep] if keep > 0 else found):
|
||||||
|
try:
|
||||||
|
os.remove(os.path.join(directory, name))
|
||||||
|
logger.info(f"Old database backup removed: {name}")
|
||||||
|
except OSError as e:
|
||||||
|
logger.warning(f"Cannot remove old backup {name}: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
def _stamp(conn, migration):
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",
|
||||||
|
(migration.version, migration.name,
|
||||||
|
datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")))
|
||||||
|
|
||||||
|
|
||||||
|
def run(target, fresh_schema=None):
|
||||||
|
"""Apply pending migrations to the database (path or SQLAlchemy engine).
|
||||||
|
|
||||||
|
fresh_schema(conn), if given, creates the complete current schema of a brand-new
|
||||||
|
database; all migrations are then recorded as applied without running them.
|
||||||
|
Raises SchemaTooNew / MigrationError; returns a Report."""
|
||||||
|
db_path = _resolve_path(target)
|
||||||
|
if fresh_schema is None:
|
||||||
|
fresh_schema = FRESH_SCHEMA
|
||||||
|
|
||||||
|
# Fast path: nothing to do, no lock, no write
|
||||||
|
st = _quick_status(db_path)
|
||||||
|
if st is not None:
|
||||||
|
if st.too_new:
|
||||||
|
raise _too_new_error(st)
|
||||||
|
if not st.pending:
|
||||||
|
return Report(db_path, st.current)
|
||||||
|
|
||||||
|
db_dir = os.path.dirname(db_path)
|
||||||
|
if db_dir:
|
||||||
|
os.makedirs(db_dir, exist_ok=True)
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(db_path, timeout=LOCK_TIMEOUT, isolation_level=None)
|
||||||
|
try:
|
||||||
|
report = _run_locked(conn, db_path, fresh_schema)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
except sqlite3.Error as e:
|
||||||
|
raise MigrationError(f"Database error while migrating {db_path}: {e}") from e
|
||||||
|
if report.backup:
|
||||||
|
_prune_backups(db_path)
|
||||||
|
return report
|
||||||
|
|
||||||
|
|
||||||
|
def _run_locked(conn, db_path, fresh_schema):
|
||||||
|
# The write lock is taken before anything is read or changed: a second process
|
||||||
|
# waits here, and then finds nothing pending (and makes no second backup)
|
||||||
|
conn.execute("BEGIN IMMEDIATE")
|
||||||
|
try:
|
||||||
|
st = _read_status(conn, db_path)
|
||||||
|
if st.too_new:
|
||||||
|
raise _too_new_error(st)
|
||||||
|
if not st.pending:
|
||||||
|
conn.execute("ROLLBACK")
|
||||||
|
return Report(db_path, st.current)
|
||||||
|
|
||||||
|
problems = _integrity_problems(conn)
|
||||||
|
if problems:
|
||||||
|
raise MigrationError(
|
||||||
|
f"Integrity check failed for {db_path}: {'; '.join(problems)}. Nothing was changed.")
|
||||||
|
|
||||||
|
backup, before = None, {}
|
||||||
|
if not st.fresh:
|
||||||
|
backup, before = _backup(conn, db_path)
|
||||||
|
where = f"backup: {backup}" if backup else "new database, no backup needed"
|
||||||
|
|
||||||
|
conn.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS schema_migrations ("
|
||||||
|
"version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT)")
|
||||||
|
applied = []
|
||||||
|
if st.fresh and fresh_schema is not None:
|
||||||
|
fresh_schema(conn)
|
||||||
|
for m in st.pending:
|
||||||
|
_stamp(conn, m)
|
||||||
|
applied.append((m.version, m.name))
|
||||||
|
else:
|
||||||
|
for m in st.pending:
|
||||||
|
logger.info(f"Applying migration {m.version} ({m.name}) to {db_path}")
|
||||||
|
conn.execute("SAVEPOINT migration")
|
||||||
|
try:
|
||||||
|
m.apply(conn)
|
||||||
|
_stamp(conn, m)
|
||||||
|
except Exception as e:
|
||||||
|
conn.execute("ROLLBACK TO migration")
|
||||||
|
conn.execute("RELEASE migration")
|
||||||
|
# Migrations completed before this one stay (each is complete in itself)
|
||||||
|
conn.execute("COMMIT" if applied else "ROLLBACK")
|
||||||
|
raise MigrationError(
|
||||||
|
f"Migration {m.version} ({m.name}) failed and was rolled back: {e} "
|
||||||
|
f"[{where}]. The service will not start; fix the cause and run migrate.py "
|
||||||
|
f"again.") from e
|
||||||
|
conn.execute("RELEASE migration")
|
||||||
|
applied.append((m.version, m.name))
|
||||||
|
|
||||||
|
# Verify before the commit: on any mismatch nothing is kept
|
||||||
|
problems = _integrity_problems(conn)
|
||||||
|
if problems:
|
||||||
|
raise MigrationError(
|
||||||
|
f"Integrity check failed after migration of {db_path}: {'; '.join(problems)}. "
|
||||||
|
f"The changes were rolled back. Backup: {backup or 'none (new database)'}")
|
||||||
|
after = _row_counts(conn)
|
||||||
|
for table, count in before.items():
|
||||||
|
if table == "schema_migrations":
|
||||||
|
continue # the bookkeeping table is expected to grow
|
||||||
|
if after.get(table) != count:
|
||||||
|
raise MigrationError(
|
||||||
|
f"Row count of table '{table}' changed during migration ({count} -> "
|
||||||
|
f"{after.get(table)}) in {db_path}. The changes were rolled back. "
|
||||||
|
f"Backup: {backup}")
|
||||||
|
|
||||||
|
conn.execute("COMMIT")
|
||||||
|
for version, name in applied:
|
||||||
|
logger.info(f"Migration {version} ({name}) applied to {db_path} [{where}]")
|
||||||
|
return Report(db_path, applied[-1][0], applied, backup, st.fresh)
|
||||||
|
except BaseException:
|
||||||
|
if conn.in_transaction:
|
||||||
|
conn.execute("ROLLBACK")
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def startup(target, fresh_schema=None):
|
||||||
|
"""Called when a service starts. Applies pending migrations, or, with
|
||||||
|
OVPMON_AUTO_MIGRATE=0, only checks and refuses while any are pending."""
|
||||||
|
db_path = _resolve_path(target)
|
||||||
|
if os.getenv("OVPMON_AUTO_MIGRATE", "1").strip() == "0":
|
||||||
|
st = status(db_path)
|
||||||
|
if st.too_new:
|
||||||
|
raise _too_new_error(st)
|
||||||
|
if st.pending:
|
||||||
|
names = ", ".join(f"{m.version} ({m.name})" for m in st.pending)
|
||||||
|
raise MigrationPending(
|
||||||
|
f"Database {db_path} is at schema version {st.current}, pending migrations: "
|
||||||
|
f"{names}. Automatic migration is disabled (OVPMON_AUTO_MIGRATE=0): run "
|
||||||
|
f"'python migrate.py' first.")
|
||||||
|
return Report(db_path, st.current)
|
||||||
|
report = run(target, fresh_schema)
|
||||||
|
logger.info(f"Database {db_path}: schema version {report.version}")
|
||||||
|
return report
|
||||||
|
|
||||||
|
|
||||||
|
def startup_or_exit(target, fresh_schema=None):
|
||||||
|
"""startup() for service entry points: a clear message and a non-zero exit
|
||||||
|
instead of a traceback when the database must not be used."""
|
||||||
|
try:
|
||||||
|
return startup(target, fresh_schema)
|
||||||
|
except MigrationError as e:
|
||||||
|
logger.critical(str(e))
|
||||||
|
print(f"FATAL: {e}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
# --- Migrations of this component -------------------------------------------
|
||||||
|
|
||||||
|
import json # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def _dialect():
|
||||||
|
from sqlalchemy.dialects import sqlite
|
||||||
|
return sqlite.dialect()
|
||||||
|
|
||||||
|
|
||||||
|
def _metadata():
|
||||||
|
"""Model metadata (imported lazily: models import database, which stays free of this module)."""
|
||||||
|
import models # noqa: F401 registers the tables
|
||||||
|
from database import Base
|
||||||
|
return Base.metadata
|
||||||
|
|
||||||
|
|
||||||
|
def _default_clause(column):
|
||||||
|
"""'DEFAULT <literal>' for a scalar Python default, so existing rows get the value.
|
||||||
|
JSON/list defaults become '[]'. Anything not constant (timestamps) stays NULL."""
|
||||||
|
default = column.default
|
||||||
|
if default is None:
|
||||||
|
return ""
|
||||||
|
if getattr(default, "is_scalar", False):
|
||||||
|
value = default.arg
|
||||||
|
elif getattr(default, "is_callable", False):
|
||||||
|
try:
|
||||||
|
value = default.arg(None)
|
||||||
|
except Exception:
|
||||||
|
return ""
|
||||||
|
else:
|
||||||
|
return ""
|
||||||
|
if isinstance(value, bool):
|
||||||
|
return f" DEFAULT {int(value)}"
|
||||||
|
if isinstance(value, (int, float)):
|
||||||
|
return f" DEFAULT {value}"
|
||||||
|
if isinstance(value, str):
|
||||||
|
return " DEFAULT '%s'" % value.replace("'", "''")
|
||||||
|
if isinstance(value, (list, dict)):
|
||||||
|
return " DEFAULT '%s'" % json.dumps(value)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _create_table(conn, table):
|
||||||
|
from sqlalchemy.schema import CreateIndex, CreateTable
|
||||||
|
dialect = _dialect()
|
||||||
|
conn.execute(str(CreateTable(table).compile(dialect=dialect)))
|
||||||
|
for index in table.indexes:
|
||||||
|
conn.execute(str(CreateIndex(index).compile(dialect=dialect)))
|
||||||
|
|
||||||
|
|
||||||
|
def _create_all(conn):
|
||||||
|
"""Same effect as Base.metadata.create_all(), on the migration's own connection."""
|
||||||
|
existing = set(_tables(conn))
|
||||||
|
for table in _metadata().sorted_tables:
|
||||||
|
if table.name not in existing:
|
||||||
|
_create_table(conn, table)
|
||||||
|
|
||||||
|
|
||||||
|
def _m001_baseline(conn):
|
||||||
|
"""Bring any database created by an earlier release up to the current models:
|
||||||
|
create missing tables, add missing columns (type and default from the metadata).
|
||||||
|
Replaces the standalone scripts add_columns.py and scripts/add_*.py and the old
|
||||||
|
ensure_columns(). Idempotent."""
|
||||||
|
dialect = _dialect()
|
||||||
|
existing = set(_tables(conn))
|
||||||
|
for table in _metadata().sorted_tables:
|
||||||
|
if table.name not in existing:
|
||||||
|
logger.info(f"Creating missing table {table.name}")
|
||||||
|
_create_table(conn, table)
|
||||||
|
continue
|
||||||
|
have = {r[1] for r in conn.execute(f"PRAGMA table_info({_quote(table.name)})")}
|
||||||
|
for column in table.columns:
|
||||||
|
if column.name in have:
|
||||||
|
continue
|
||||||
|
if column.primary_key:
|
||||||
|
raise MigrationError(f"Cannot add primary key column {table.name}.{column.name}")
|
||||||
|
ddl = (f"ALTER TABLE {_quote(table.name)} ADD COLUMN {_quote(column.name)} "
|
||||||
|
f"{column.type.compile(dialect=dialect)}{_default_clause(column)}")
|
||||||
|
logger.info(f"Adding missing column {column.name} to table {table.name}")
|
||||||
|
conn.execute(ddl)
|
||||||
|
|
||||||
|
|
||||||
|
MIGRATIONS = [
|
||||||
|
Migration(1, "baseline", _m001_baseline),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
# A brand-new database gets the complete current schema at once (create_all equivalent)
|
||||||
|
FRESH_SCHEMA = _create_all
|
||||||
@@ -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 sqlalchemy.sql import func
|
||||||
from database import Base
|
from database import Base
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
@@ -61,3 +61,4 @@ class UserProfile(Base):
|
|||||||
is_revoked = Column(Boolean, default=False)
|
is_revoked = Column(Boolean, default=False)
|
||||||
is_expired = Column(Boolean, default=False)
|
is_expired = Column(Boolean, default=False)
|
||||||
file_path = Column(String, nullable=True)
|
file_path = Column(String, nullable=True)
|
||||||
|
note = Column(Text, nullable=True)
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
-r requirements.txt
|
||||||
|
pytest
|
||||||
|
httpx
|
||||||
@@ -1,7 +1,13 @@
|
|||||||
fastapi
|
fastapi==0.143.3
|
||||||
uvicorn
|
starlette==1.8.0
|
||||||
|
uvicorn==0.54.0
|
||||||
|
pydantic==2.14.1
|
||||||
sqlalchemy
|
sqlalchemy
|
||||||
psutil
|
psutil
|
||||||
python-multipart
|
python-multipart
|
||||||
jinja2
|
jinja2
|
||||||
pyjwt
|
pyjwt
|
||||||
|
requests
|
||||||
|
cryptography
|
||||||
|
minio
|
||||||
|
paramiko
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
import re
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from utils.auth import verify_token
|
||||||
|
from services.backup import BackupError, Busy, Invalid, destinations, engine, package, store
|
||||||
|
|
||||||
|
router = APIRouter(dependencies=[Depends(verify_token)])
|
||||||
|
|
||||||
|
NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9 _.-]{0,63}$")
|
||||||
|
PASSPHRASE_MIN = 8
|
||||||
|
|
||||||
|
|
||||||
|
class SettingsUpdate(BaseModel):
|
||||||
|
passphrase: Optional[str] = Field(None, max_length=256) # set or change; never returned
|
||||||
|
clear_passphrase: bool = False
|
||||||
|
default_retention: Optional[int] = Field(None, ge=1, le=1000)
|
||||||
|
server_name: Optional[str] = Field(None, max_length=63) # '' clears it (fallback names are used)
|
||||||
|
|
||||||
|
|
||||||
|
class DestinationIn(BaseModel):
|
||||||
|
name: str = Field(..., max_length=64)
|
||||||
|
type: str = Field(..., max_length=20)
|
||||||
|
enabled: bool = True
|
||||||
|
retention_count: Optional[int] = Field(None, ge=1, le=1000)
|
||||||
|
params: dict = {}
|
||||||
|
secrets: dict = {} # absent, empty or masked values keep the stored secret
|
||||||
|
|
||||||
|
|
||||||
|
class TrustIn(BaseModel):
|
||||||
|
fingerprint: str = Field(..., max_length=80) # the one shown by Test
|
||||||
|
|
||||||
|
|
||||||
|
class RunIn(BaseModel):
|
||||||
|
destination_ids: Optional[list[int]] = None
|
||||||
|
|
||||||
|
|
||||||
|
class RestoreIn(BaseModel):
|
||||||
|
destination_id: int
|
||||||
|
package: str = Field(..., max_length=200)
|
||||||
|
passphrase: Optional[str] = Field(None, max_length=256)
|
||||||
|
|
||||||
|
|
||||||
|
def _fail(e: Exception):
|
||||||
|
"""BackupError family -> HTTP error. Messages never contain secrets."""
|
||||||
|
if isinstance(e, Busy):
|
||||||
|
raise HTTPException(status_code=409, detail=str(e))
|
||||||
|
if isinstance(e, destinations.DestinationError):
|
||||||
|
raise HTTPException(status_code=502, detail=str(e))
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
|
def _types_info():
|
||||||
|
return [{"id": t, "label": cls.label, "remote": t in destinations.REMOTE_TYPES, "fields": cls.FIELDS,
|
||||||
|
"pins_host_key": bool(cls.PIN_PARAMS)}
|
||||||
|
for t, cls in destinations.DESTINATION_TYPES.items()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/backup/settings")
|
||||||
|
def get_settings():
|
||||||
|
effective, source = engine.effective_server_name()
|
||||||
|
return {
|
||||||
|
"encryption_enabled": store.has_passphrase(),
|
||||||
|
"default_retention": store.default_retention(),
|
||||||
|
"server_name": store.get_server_name(),
|
||||||
|
"effective_server_name": effective,
|
||||||
|
"server_name_source": source,
|
||||||
|
"local_root": destinations.local_root(),
|
||||||
|
"types": _types_info(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/backup/settings")
|
||||||
|
def update_settings(body: SettingsUpdate):
|
||||||
|
if engine.is_running():
|
||||||
|
raise HTTPException(status_code=409, detail="A backup or restore is running")
|
||||||
|
if body.passphrase is not None and body.clear_passphrase:
|
||||||
|
raise HTTPException(status_code=400, detail="Give a passphrase or clear it, not both")
|
||||||
|
server_name = (body.server_name or "").strip()
|
||||||
|
if server_name and not package.SERVER_NAME_RE.match(server_name):
|
||||||
|
raise HTTPException(status_code=400, detail="Server name: 1-63 letters, digits, '.' or '-', "
|
||||||
|
"starting with a letter or digit")
|
||||||
|
if body.passphrase is not None:
|
||||||
|
if len(body.passphrase) < PASSPHRASE_MIN:
|
||||||
|
raise HTTPException(status_code=400, detail=f"Passphrase must have at least {PASSPHRASE_MIN} characters")
|
||||||
|
store.set_passphrase(body.passphrase)
|
||||||
|
if body.clear_passphrase:
|
||||||
|
remote = [d["name"] for d in store.list_destinations()
|
||||||
|
if d["enabled"] and d["type"] in destinations.REMOTE_TYPES]
|
||||||
|
if remote:
|
||||||
|
raise HTTPException(status_code=400, detail="Remote destinations need a passphrase: disable or "
|
||||||
|
f"delete them first ({', '.join(remote)})")
|
||||||
|
store.set_passphrase(None)
|
||||||
|
if body.default_retention is not None:
|
||||||
|
store.set_default_retention(body.default_retention)
|
||||||
|
if body.server_name is not None:
|
||||||
|
store.set_server_name(server_name)
|
||||||
|
return get_settings()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/backup/destinations")
|
||||||
|
def list_destinations():
|
||||||
|
return store.list_destinations()
|
||||||
|
|
||||||
|
|
||||||
|
def _prepare(body: DestinationIn, previous: Optional[dict]):
|
||||||
|
cls = destinations.DESTINATION_TYPES.get(body.type)
|
||||||
|
if cls is None:
|
||||||
|
raise HTTPException(status_code=400, detail=f"Unsupported destination type: {body.type}")
|
||||||
|
name = body.name.strip()
|
||||||
|
if not NAME_RE.match(name):
|
||||||
|
raise HTTPException(status_code=400, detail="Name: 1-64 letters, digits, spaces, '.', '_' or '-'")
|
||||||
|
same_type = bool(previous and previous["type"] == body.type)
|
||||||
|
# Secrets of another type never carry over
|
||||||
|
keep = previous["secrets"] if same_type else {}
|
||||||
|
given = {k: v for k, v in body.secrets.items() if isinstance(v, str) and v and v != store.MASK}
|
||||||
|
# A pinned host key comes only from the trust call, never from the client
|
||||||
|
client_params = {k: v for k, v in body.params.items() if k not in cls.PIN_PARAMS}
|
||||||
|
try:
|
||||||
|
params, secrets = cls.validate(client_params, given, keep)
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
if same_type and cls.PIN_PARAMS:
|
||||||
|
old = previous["params"]
|
||||||
|
if all(old.get(k) == params.get(k) for k in cls.PIN_DEPENDS): # same server: the pin stays
|
||||||
|
params.update({k: old[k] for k in cls.PIN_PARAMS if old.get(k)})
|
||||||
|
retention = body.retention_count or (previous["retention_count"] if previous else store.default_retention())
|
||||||
|
return name, params, secrets, retention
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/backup/destinations", status_code=201)
|
||||||
|
def create_destination(body: DestinationIn):
|
||||||
|
name, params, secrets, retention = _prepare(body, None)
|
||||||
|
try:
|
||||||
|
dest_id = store.save_destination(None, name, body.type, body.enabled, retention, params, secrets)
|
||||||
|
except BackupError as e:
|
||||||
|
raise HTTPException(status_code=409, detail=str(e))
|
||||||
|
return store.get_destination(dest_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/backup/destinations/{dest_id}")
|
||||||
|
def update_destination(dest_id: int, body: DestinationIn):
|
||||||
|
if engine.is_running():
|
||||||
|
raise HTTPException(status_code=409, detail="A backup or restore is running")
|
||||||
|
previous = store.get_destination(dest_id, with_secrets=True)
|
||||||
|
if not previous:
|
||||||
|
raise HTTPException(status_code=404, detail="Destination not found")
|
||||||
|
name, params, secrets, retention = _prepare(body, previous)
|
||||||
|
try:
|
||||||
|
store.save_destination(dest_id, name, body.type, body.enabled, retention, params, secrets)
|
||||||
|
except BackupError as e:
|
||||||
|
raise HTTPException(status_code=409, detail=str(e))
|
||||||
|
return store.get_destination(dest_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/backup/destinations/{dest_id}")
|
||||||
|
def delete_destination(dest_id: int):
|
||||||
|
if engine.is_running():
|
||||||
|
raise HTTPException(status_code=409, detail="A backup or restore is running")
|
||||||
|
if not store.delete_destination(dest_id):
|
||||||
|
raise HTTPException(status_code=404, detail="Destination not found")
|
||||||
|
return {"message": "Destination deleted"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/backup/destinations/{dest_id}/test")
|
||||||
|
def test_destination(dest_id: int):
|
||||||
|
try:
|
||||||
|
return engine.test_destination(dest_id)
|
||||||
|
except BackupError as e:
|
||||||
|
_fail(e)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/backup/destinations/{dest_id}/trust-host-key")
|
||||||
|
def trust_host_key(dest_id: int, body: TrustIn):
|
||||||
|
if engine.is_running():
|
||||||
|
raise HTTPException(status_code=409, detail="A backup or restore is running")
|
||||||
|
try:
|
||||||
|
return engine.trust_host_key(dest_id, body.fingerprint.strip())
|
||||||
|
except BackupError as e:
|
||||||
|
_fail(e)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/backup/destinations/{dest_id}/packages")
|
||||||
|
def list_packages(dest_id: int):
|
||||||
|
try:
|
||||||
|
return {"packages": engine.list_packages(dest_id)}
|
||||||
|
except BackupError as e:
|
||||||
|
_fail(e)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/backup/run", status_code=202)
|
||||||
|
def run_backup(body: RunIn = RunIn()):
|
||||||
|
try:
|
||||||
|
engine.start_backup(body.destination_ids)
|
||||||
|
except BackupError as e:
|
||||||
|
_fail(e)
|
||||||
|
return {"state": "running"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/backup/restore", status_code=202)
|
||||||
|
def run_restore(body: RestoreIn):
|
||||||
|
try:
|
||||||
|
engine.start_restore(body.destination_id, body.package, body.passphrase)
|
||||||
|
except BackupError as e:
|
||||||
|
_fail(e)
|
||||||
|
return {"state": "running"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/backup/status")
|
||||||
|
def get_status():
|
||||||
|
return engine.status()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/backup/history")
|
||||||
|
def get_history(limit: int = Query(20, ge=1, le=100)):
|
||||||
|
return store.history_list(limit)
|
||||||
@@ -4,8 +4,9 @@ from fastapi.responses import FileResponse
|
|||||||
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 utils.guards import forbid_during_restore
|
||||||
from models import UserProfile
|
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 services import pki, generator
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
@@ -69,11 +70,18 @@ def list_profiles(db: Session = Depends(get_db)):
|
|||||||
|
|
||||||
return updated_profiles
|
return updated_profiles
|
||||||
|
|
||||||
@router.post("/profiles", response_model=UserProfileSchema)
|
@router.post("/profiles", response_model=UserProfileSchema, dependencies=[Depends(forbid_during_restore)])
|
||||||
def create_profile(
|
def create_profile(
|
||||||
profile_in: UserProfileCreate,
|
profile_in: UserProfileCreate,
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
):
|
):
|
||||||
|
if pki.is_init_running():
|
||||||
|
raise HTTPException(status_code=409, detail="PKI initialization is running")
|
||||||
|
try:
|
||||||
|
pki.require_pki_ready()
|
||||||
|
except pki.PkiNotReady as e:
|
||||||
|
raise HTTPException(status_code=409, detail=str(e))
|
||||||
|
|
||||||
# Check existing
|
# Check existing
|
||||||
existing = db.query(UserProfile).filter(UserProfile.username == profile_in.username).first()
|
existing = db.query(UserProfile).filter(UserProfile.username == profile_in.username).first()
|
||||||
if existing:
|
if existing:
|
||||||
@@ -116,7 +124,18 @@ def create_profile(
|
|||||||
db.refresh(new_profile)
|
db.refresh(new_profile)
|
||||||
return new_profile
|
return new_profile
|
||||||
|
|
||||||
@router.delete("/profiles/{profile_id}")
|
@router.put("/profiles/{profile_id}/note", response_model=UserProfileSchema, dependencies=[Depends(forbid_during_restore)])
|
||||||
|
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}", dependencies=[Depends(forbid_during_restore)])
|
||||||
def revoke_profile(profile_id: int, db: Session = Depends(get_db)):
|
def revoke_profile(profile_id: int, db: Session = Depends(get_db)):
|
||||||
profile = db.query(UserProfile).filter(UserProfile.id == profile_id).first()
|
profile = db.query(UserProfile).filter(UserProfile.id == profile_id).first()
|
||||||
if not profile:
|
if not profile:
|
||||||
|
|||||||
@@ -4,18 +4,20 @@ 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 utils.guards import forbid_during_restore
|
||||||
|
from services import generator, process, config, pki
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
router = APIRouter(dependencies=[Depends(verify_token)])
|
router = APIRouter(dependencies=[Depends(verify_token)])
|
||||||
|
|
||||||
@router.post("/server/configure")
|
@router.post("/server/configure", dependencies=[Depends(forbid_during_restore)])
|
||||||
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 = process.openvpn_config_path()
|
||||||
|
|
||||||
# Unprivileged service: render to the staging dir, the root helper validates and installs it
|
# Unprivileged service: render to the staging dir, the root helper validates and installs it
|
||||||
if not process.is_container() and os.geteuid() != 0:
|
if not process.is_container() and os.geteuid() != 0:
|
||||||
@@ -46,6 +48,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:
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
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 utils.guards import forbid_during_restore
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from fastapi import Depends
|
from fastapi import Depends
|
||||||
|
|
||||||
@@ -20,8 +23,8 @@ class ProcessStats(BaseModel):
|
|||||||
memory_mb: float
|
memory_mb: float
|
||||||
uptime: Optional[str] = None
|
uptime: Optional[str] = None
|
||||||
|
|
||||||
@router.post("/server/process/{action}", response_model=ProcessActionResponse)
|
@router.post("/server/process/{action}", response_model=ProcessActionResponse, dependencies=[Depends(forbid_during_restore)])
|
||||||
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 +32,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":
|
||||||
|
|||||||
@@ -1,18 +1,21 @@
|
|||||||
|
from typing import Literal, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
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 utils.guards import forbid_during_restore
|
||||||
from schemas import (
|
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)])
|
||||||
|
|
||||||
@router.get("/config", response_model=ConfigResponse)
|
@router.get("/config", response_model=ConfigResponse)
|
||||||
def get_config(
|
def get_config(
|
||||||
section: str = Query(None, enum=["server", "pki"]),
|
section: Optional[Literal["server", "pki"]] = Query(None),
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
):
|
):
|
||||||
response = ConfigResponse()
|
response = ConfigResponse()
|
||||||
@@ -22,29 +25,38 @@ def get_config(
|
|||||||
response.pki = config.get_pki_settings(db)
|
response.pki = config.get_pki_settings(db)
|
||||||
return response
|
return response
|
||||||
|
|
||||||
@router.put("/config/server", response_model=SystemSettings)
|
@router.put("/config/server", response_model=SystemSettings, dependencies=[Depends(forbid_during_restore)])
|
||||||
def update_server_config(
|
def update_server_config(
|
||||||
settings: SystemSettingsUpdate,
|
settings: SystemSettingsUpdate,
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
):
|
):
|
||||||
return config.update_system_settings(db, settings)
|
return config.update_system_settings(db, settings)
|
||||||
|
|
||||||
@router.put("/config/pki", response_model=PKISetting)
|
@router.put("/config/pki", response_model=PKISetting, dependencies=[Depends(forbid_during_restore)])
|
||||||
def update_pki_config(
|
def update_pki_config(
|
||||||
settings: PKISettingUpdate,
|
settings: PKISettingUpdate,
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
):
|
):
|
||||||
return config.update_pki_settings(db, settings)
|
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)):
|
def init_system_pki(db: Session = Depends(get_db)):
|
||||||
try:
|
try:
|
||||||
msg = pki.init_pki(db)
|
pki.start_init_async(db)
|
||||||
return {"message": msg}
|
except pki.InitConflict as e:
|
||||||
except Exception as e:
|
raise HTTPException(status_code=409, detail=str(e))
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
return {"state": "running"}
|
||||||
|
|
||||||
@router.delete("/system/pki")
|
@router.get("/system/init/status")
|
||||||
|
def get_init_status(db: Session = Depends(get_db)):
|
||||||
|
return pki.init_status(db)
|
||||||
|
|
||||||
|
@router.delete("/system/pki", dependencies=[Depends(forbid_during_restore)])
|
||||||
def clear_system_pki(db: Session = Depends(get_db)):
|
def clear_system_pki(db: Session = Depends(get_db)):
|
||||||
|
if pki.is_init_running():
|
||||||
|
raise HTTPException(status_code=409, detail="PKI initialization is running")
|
||||||
|
# Do not pull the keys from under a running server
|
||||||
|
if process.get_process_stats()["status"] == "running":
|
||||||
|
raise HTTPException(status_code=409, detail="Stop OpenVPN first")
|
||||||
msg = pki.clear_pki(db)
|
msg = pki.clear_pki(db)
|
||||||
return {"message": msg}
|
return {"message": msg}
|
||||||
@@ -224,6 +224,18 @@ class UserProfile(UserProfileBase):
|
|||||||
is_revoked: bool = False
|
is_revoked: bool = False
|
||||||
is_expired: bool = False
|
is_expired: bool = False
|
||||||
file_path: Optional[str] = None
|
file_path: Optional[str] = None
|
||||||
|
note: Optional[str] = None
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
from_attributes = True
|
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
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
"""Backup and restore of the application data (databases, PKI, client profiles).
|
||||||
|
|
||||||
|
Modules:
|
||||||
|
package.py package format (tar.gz + manifest), snapshots, safe extraction
|
||||||
|
crypto.py optional package encryption (AES-256-GCM, scrypt)
|
||||||
|
destinations.py where packages go: common interface, local folder and S3 (minio)
|
||||||
|
store.py settings, destinations and history in a separate SQLite file
|
||||||
|
engine.py backup job and restore engine (one background job at a time)
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class BackupError(Exception):
|
||||||
|
"""A backup or restore step failed. The message is safe to show to the user (no secrets)."""
|
||||||
|
|
||||||
|
|
||||||
|
class Invalid(BackupError):
|
||||||
|
"""The request cannot be accepted as it is (API: 400)."""
|
||||||
|
|
||||||
|
|
||||||
|
class Busy(BackupError):
|
||||||
|
"""Another backup or restore job is running (API: 409)."""
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
"""Package encryption: AES-256-GCM in chunks, key from the passphrase with scrypt.
|
||||||
|
|
||||||
|
File layout:
|
||||||
|
magic "OVPBAKE1" | log2(N) 1 byte | r 1 byte | p 1 byte | salt 16 | nonce prefix 8 (header, 35 bytes)
|
||||||
|
then chunks of CHUNK bytes of plaintext, each stored as ciphertext + 16 byte tag.
|
||||||
|
Chunk i uses the nonce prefix || i (4 bytes, big endian). The header and a "final chunk" flag
|
||||||
|
are authenticated data of every chunk, so a truncated, reordered or modified file is rejected.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import struct
|
||||||
|
|
||||||
|
from cryptography.exceptions import InvalidTag
|
||||||
|
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||||
|
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
|
||||||
|
|
||||||
|
from . import BackupError
|
||||||
|
|
||||||
|
MAGIC = b"OVPBAKE1"
|
||||||
|
HEADER_LEN = len(MAGIC) + 3 + 16 + 8
|
||||||
|
CHUNK = 1024 * 1024
|
||||||
|
TAG = 16
|
||||||
|
SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P = 15, 8, 1 # about 32 MiB of memory
|
||||||
|
# Bounds for the parameters read from a file: a crafted header must not exhaust memory or CPU
|
||||||
|
MAX_LOG_N, MAX_R, MAX_P = 20, 16, 4
|
||||||
|
|
||||||
|
|
||||||
|
class WrongPassphrase(BackupError):
|
||||||
|
"""Wrong passphrase, or the file is damaged (AES-GCM cannot tell the two apart)."""
|
||||||
|
|
||||||
|
|
||||||
|
def is_encrypted(path: str) -> bool:
|
||||||
|
try:
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
return f.read(len(MAGIC)) == MAGIC
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _derive(passphrase: str, salt: bytes, log_n: int, r: int, p: int) -> bytes:
|
||||||
|
return Scrypt(salt=salt, length=32, n=2 ** log_n, r=r, p=p).derive(passphrase.encode("utf-8"))
|
||||||
|
|
||||||
|
|
||||||
|
def _nonce(prefix: bytes, index: int) -> bytes:
|
||||||
|
return prefix + struct.pack(">I", index)
|
||||||
|
|
||||||
|
|
||||||
|
def _aad(header: bytes, final: bool) -> bytes:
|
||||||
|
return header + (b"\x01" if final else b"\x00")
|
||||||
|
|
||||||
|
|
||||||
|
def encrypt_file(src: str, dst: str, passphrase: str) -> None:
|
||||||
|
if not passphrase:
|
||||||
|
raise BackupError("Passphrase is empty")
|
||||||
|
salt, prefix = os.urandom(16), os.urandom(8)
|
||||||
|
header = MAGIC + bytes([SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P]) + salt + prefix
|
||||||
|
aes = AESGCM(_derive(passphrase, salt, SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P))
|
||||||
|
fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with open(src, "rb") as fin, os.fdopen(fd, "wb") as fout:
|
||||||
|
fout.write(header)
|
||||||
|
index = 0
|
||||||
|
block = fin.read(CHUNK)
|
||||||
|
while True:
|
||||||
|
nxt = fin.read(CHUNK)
|
||||||
|
final = not nxt
|
||||||
|
fout.write(aes.encrypt(_nonce(prefix, index), block, _aad(header, final)))
|
||||||
|
if final:
|
||||||
|
break
|
||||||
|
block, index = nxt, index + 1
|
||||||
|
|
||||||
|
|
||||||
|
def decrypt_file(src: str, dst: str, passphrase: str) -> None:
|
||||||
|
if not passphrase:
|
||||||
|
raise WrongPassphrase("Passphrase is required for an encrypted package")
|
||||||
|
with open(src, "rb") as fin:
|
||||||
|
header = fin.read(HEADER_LEN)
|
||||||
|
if len(header) != HEADER_LEN or not header.startswith(MAGIC):
|
||||||
|
raise BackupError("Not an encrypted package (bad header)")
|
||||||
|
log_n, r, p = header[8], header[9], header[10]
|
||||||
|
if not (1 <= log_n <= MAX_LOG_N and 1 <= r <= MAX_R and 1 <= p <= MAX_P):
|
||||||
|
raise BackupError("Encrypted package has unsupported key derivation parameters")
|
||||||
|
salt, prefix = header[11:27], header[27:35]
|
||||||
|
aes = AESGCM(_derive(passphrase, salt, log_n, r, p))
|
||||||
|
fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as fout:
|
||||||
|
index = 0
|
||||||
|
block = fin.read(CHUNK + TAG)
|
||||||
|
if not block:
|
||||||
|
raise BackupError("Encrypted package is truncated")
|
||||||
|
while True:
|
||||||
|
nxt = fin.read(CHUNK + TAG)
|
||||||
|
final = not nxt
|
||||||
|
try:
|
||||||
|
fout.write(aes.decrypt(_nonce(prefix, index), block, _aad(header, final)))
|
||||||
|
except InvalidTag:
|
||||||
|
raise WrongPassphrase("Wrong passphrase, or the package is damaged") from None
|
||||||
|
if final:
|
||||||
|
break
|
||||||
|
block, index = nxt, index + 1
|
||||||
@@ -0,0 +1,876 @@
|
|||||||
|
"""Backup destinations. Every type implements the same interface:
|
||||||
|
|
||||||
|
test() check the connection and the right to write and delete; returns a message
|
||||||
|
put(local_path, name) store a file under name
|
||||||
|
list() [{"name", "size", "mtime"}] of the files in the destination folder
|
||||||
|
get(name, local_path) download to a local file
|
||||||
|
delete(name) remove a file
|
||||||
|
|
||||||
|
Implemented: "local", "s3", "sftp" and "ftp". To add a type (smb): write a Destination subclass
|
||||||
|
with FIELDS, validate() and the five methods, and add it to DESTINATION_TYPES. The API accepts
|
||||||
|
exactly the types of that registry.
|
||||||
|
"""
|
||||||
|
import hmac
|
||||||
|
import hashlib
|
||||||
|
import base64
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
|
import stat
|
||||||
|
import uuid
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from . import BackupError
|
||||||
|
from .package import PACKAGE_RE
|
||||||
|
|
||||||
|
DEFAULT_LOCAL_ROOT = "/var/lib/ovpmon/backups"
|
||||||
|
SAFE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
|
||||||
|
FOLDER_SEGMENT_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
|
||||||
|
HOST_RE = re.compile(r"^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$")
|
||||||
|
BUCKET_RE = re.compile(r"^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$")
|
||||||
|
REGION_RE = re.compile(r"^[A-Za-z0-9-]{1,40}$")
|
||||||
|
|
||||||
|
|
||||||
|
class DestinationError(BackupError):
|
||||||
|
"""The destination refused or could not be reached. The message never contains secrets."""
|
||||||
|
|
||||||
|
|
||||||
|
class NeedsTrust(DestinationError):
|
||||||
|
"""The SSH host key of the server is not pinned yet (or changed). Carries what the server showed."""
|
||||||
|
|
||||||
|
def __init__(self, message: str, fingerprint: str, key_type: str, changed: bool = False):
|
||||||
|
super().__init__(message)
|
||||||
|
self.fingerprint, self.key_type, self.changed = fingerprint, key_type, changed
|
||||||
|
|
||||||
|
|
||||||
|
def local_root() -> str:
|
||||||
|
return os.environ.get("OVPMON_BACKUP_LOCAL_ROOT", "").strip() or DEFAULT_LOCAL_ROOT
|
||||||
|
|
||||||
|
|
||||||
|
def _check_name(name: str) -> str:
|
||||||
|
if not isinstance(name, str) or not SAFE_NAME_RE.match(name) or ".." in name:
|
||||||
|
raise DestinationError("Invalid file name")
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
def _short(e: Exception) -> str:
|
||||||
|
return f"{type(e).__name__}: {str(e)[:300]}"
|
||||||
|
|
||||||
|
|
||||||
|
class Destination:
|
||||||
|
type = ""
|
||||||
|
label = ""
|
||||||
|
# Field description for the UI: name, label, kind (text|number|bool|secret|secret_multiline),
|
||||||
|
# required, default, hint; optional warning + warn_if (shown while the value equals warn_if)
|
||||||
|
FIELDS: list = []
|
||||||
|
# Parameters set by pinning a host key (never accepted from the client, kept while the parameters
|
||||||
|
# of PIN_DEPENDS stay the same); empty for types without pinning
|
||||||
|
PIN_PARAMS: tuple = ()
|
||||||
|
PIN_DEPENDS: tuple = ()
|
||||||
|
|
||||||
|
def __init__(self, params: dict, secrets: dict):
|
||||||
|
self.params = params
|
||||||
|
self.secrets = secrets
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def validate(cls, params: dict, secrets: dict, previous_secrets: Optional[dict] = None):
|
||||||
|
"""Return (clean_params, clean_secrets) or raise ValueError with a message for the user."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def test(self) -> str:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def put(self, local_path: str, name: str) -> None:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def list(self) -> list:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def get(self, name: str, local_path: str) -> None:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def delete(self, name: str) -> None:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def fetch_host_key(self):
|
||||||
|
"""(fingerprint, key type) the server shows now; no credentials are sent. Pinning types only."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
|
||||||
|
def _unknown_keys(given: dict, allowed: set, what: str):
|
||||||
|
extra = sorted(set(given) - allowed)
|
||||||
|
if extra:
|
||||||
|
raise ValueError(f"Unknown {what}: {', '.join(extra)}")
|
||||||
|
|
||||||
|
|
||||||
|
# --- local folder --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class LocalDestination(Destination):
|
||||||
|
"""A sub folder inside the root OVPMON_BACKUP_LOCAL_ROOT. Paths outside the root and
|
||||||
|
symbolic links are rejected."""
|
||||||
|
type = "local"
|
||||||
|
label = "Local folder"
|
||||||
|
FIELDS = [
|
||||||
|
{"name": "folder", "label": "Folder (inside the backup root)", "kind": "text", "required": True,
|
||||||
|
"default": "default", "hint": "Sub folder of the server's backup root, for example 'daily'"},
|
||||||
|
]
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def validate(cls, params, secrets, previous_secrets=None):
|
||||||
|
_unknown_keys(params, {"folder"}, "parameters")
|
||||||
|
if secrets:
|
||||||
|
raise ValueError("A local destination has no secrets")
|
||||||
|
folder = str(params.get("folder", "")).strip().strip("/")
|
||||||
|
if not folder:
|
||||||
|
raise ValueError("Folder is required")
|
||||||
|
parts = folder.split("/")
|
||||||
|
if len(parts) > 4 or not all(FOLDER_SEGMENT_RE.match(p) and ".." not in p for p in parts):
|
||||||
|
raise ValueError("Folder must be a relative path of letters, digits, '.', '_' and '-' "
|
||||||
|
"(no '..', no leading dot, at most 4 levels)")
|
||||||
|
return {"folder": "/".join(parts)}, {}
|
||||||
|
|
||||||
|
def _root(self) -> str:
|
||||||
|
root = local_root()
|
||||||
|
try:
|
||||||
|
os.makedirs(root, mode=0o700, exist_ok=True)
|
||||||
|
except OSError as e:
|
||||||
|
raise DestinationError(f"Backup root {root} is not usable: {e.strerror or e}") from e
|
||||||
|
return os.path.realpath(root)
|
||||||
|
|
||||||
|
def _dir(self, create: bool) -> str:
|
||||||
|
root = self._root()
|
||||||
|
current = root
|
||||||
|
for part in self.params["folder"].split("/"):
|
||||||
|
current = os.path.join(current, part)
|
||||||
|
try:
|
||||||
|
st = os.lstat(current)
|
||||||
|
except FileNotFoundError:
|
||||||
|
if not create:
|
||||||
|
raise DestinationError("Folder does not exist yet") from None
|
||||||
|
try:
|
||||||
|
os.mkdir(current, 0o700)
|
||||||
|
except OSError as e:
|
||||||
|
raise DestinationError(f"Cannot create the folder: {e.strerror or e}") from e
|
||||||
|
continue
|
||||||
|
if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode):
|
||||||
|
raise DestinationError("Folder is a symbolic link or not a directory: refused")
|
||||||
|
real = os.path.realpath(current)
|
||||||
|
if real != root and not real.startswith(root + os.sep):
|
||||||
|
raise DestinationError("Folder is outside the backup root: refused")
|
||||||
|
return real
|
||||||
|
|
||||||
|
def test(self) -> str:
|
||||||
|
directory = self._dir(create=True)
|
||||||
|
probe = os.path.join(directory, f".ovpmon-test-{uuid.uuid4().hex[:8]}")
|
||||||
|
try:
|
||||||
|
with open(probe, "wb") as f:
|
||||||
|
f.write(b"ok")
|
||||||
|
os.remove(probe)
|
||||||
|
except OSError as e:
|
||||||
|
raise DestinationError(f"Cannot write to the folder: {e.strerror or e}") from e
|
||||||
|
free = shutil.disk_usage(directory).free // (1024 * 1024)
|
||||||
|
return f"Folder is writable ({free} MB free)"
|
||||||
|
|
||||||
|
def put(self, local_path, name):
|
||||||
|
_check_name(name)
|
||||||
|
directory = self._dir(create=True)
|
||||||
|
final = os.path.join(directory, name)
|
||||||
|
tmp = os.path.join(directory, f".{name}.part")
|
||||||
|
try:
|
||||||
|
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as out, open(local_path, "rb") as src:
|
||||||
|
shutil.copyfileobj(src, out, 1024 * 1024)
|
||||||
|
os.replace(tmp, final)
|
||||||
|
except OSError as e:
|
||||||
|
try:
|
||||||
|
os.remove(tmp)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
raise DestinationError(f"Cannot write the package: {e.strerror or e}") from e
|
||||||
|
|
||||||
|
def list(self):
|
||||||
|
try:
|
||||||
|
directory = self._dir(create=False)
|
||||||
|
except DestinationError as e:
|
||||||
|
if "does not exist" in str(e):
|
||||||
|
return []
|
||||||
|
raise
|
||||||
|
out = []
|
||||||
|
with os.scandir(directory) as it:
|
||||||
|
for entry in it:
|
||||||
|
try:
|
||||||
|
st = entry.stat(follow_symlinks=False)
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
if stat.S_ISREG(st.st_mode) and not entry.name.startswith("."):
|
||||||
|
out.append({"name": entry.name, "size": st.st_size, "mtime": st.st_mtime})
|
||||||
|
return out
|
||||||
|
|
||||||
|
def get(self, name, local_path):
|
||||||
|
_check_name(name)
|
||||||
|
path = os.path.join(self._dir(create=False), name)
|
||||||
|
try:
|
||||||
|
st = os.lstat(path)
|
||||||
|
if not stat.S_ISREG(st.st_mode):
|
||||||
|
raise DestinationError("Not a regular file: refused")
|
||||||
|
fd = os.open(local_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as out, open(path, "rb") as src:
|
||||||
|
shutil.copyfileobj(src, out, 1024 * 1024)
|
||||||
|
except OSError as e:
|
||||||
|
raise DestinationError(f"Cannot read the package: {e.strerror or e}") from e
|
||||||
|
|
||||||
|
def delete(self, name):
|
||||||
|
_check_name(name)
|
||||||
|
path = os.path.join(self._dir(create=False), name)
|
||||||
|
try:
|
||||||
|
if stat.S_ISREG(os.lstat(path).st_mode):
|
||||||
|
os.remove(path)
|
||||||
|
except FileNotFoundError:
|
||||||
|
pass
|
||||||
|
except OSError as e:
|
||||||
|
raise DestinationError(f"Cannot delete the package: {e.strerror or e}") from e
|
||||||
|
|
||||||
|
|
||||||
|
# --- S3 (minio client) ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
class S3Destination(Destination):
|
||||||
|
"""AWS S3 or a compatible store, through the minio Python SDK."""
|
||||||
|
type = "s3"
|
||||||
|
label = "S3 bucket"
|
||||||
|
FIELDS = [
|
||||||
|
{"name": "endpoint", "label": "Endpoint (host[:port])", "kind": "text", "required": True,
|
||||||
|
"default": "s3.amazonaws.com", "hint": "Without http:// or https://"},
|
||||||
|
{"name": "secure", "label": "Use TLS (https)", "kind": "bool", "required": False, "default": True},
|
||||||
|
{"name": "region", "label": "Region (optional)", "kind": "text", "required": False, "default": ""},
|
||||||
|
{"name": "bucket", "label": "Bucket", "kind": "text", "required": True, "default": ""},
|
||||||
|
{"name": "prefix", "label": "Prefix (optional)", "kind": "text", "required": False, "default": "",
|
||||||
|
"hint": "Folder inside the bucket, for example 'ovpmon/'"},
|
||||||
|
{"name": "access_key", "label": "Access key", "kind": "secret", "required": True},
|
||||||
|
{"name": "secret_key", "label": "Secret key", "kind": "secret", "required": True},
|
||||||
|
]
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def validate(cls, params, secrets, previous_secrets=None):
|
||||||
|
_unknown_keys(params, {"endpoint", "secure", "region", "bucket", "prefix"}, "parameters")
|
||||||
|
_unknown_keys(secrets, {"access_key", "secret_key"}, "secrets")
|
||||||
|
endpoint = str(params.get("endpoint", "")).strip()
|
||||||
|
host, _, port = endpoint.partition(":")
|
||||||
|
if not endpoint or "/" in endpoint or not HOST_RE.match(host) or (port and not (port.isdigit() and 0 < int(port) < 65536)):
|
||||||
|
raise ValueError("Endpoint must be host[:port] without http:// or a path")
|
||||||
|
bucket = str(params.get("bucket", "")).strip()
|
||||||
|
if not BUCKET_RE.match(bucket) or ".." in bucket:
|
||||||
|
raise ValueError("Bucket name is invalid (3-63 lowercase letters, digits, '.' and '-')")
|
||||||
|
region = str(params.get("region", "") or "").strip()
|
||||||
|
if region and not REGION_RE.match(region):
|
||||||
|
raise ValueError("Region is invalid")
|
||||||
|
prefix = str(params.get("prefix", "") or "").strip().strip("/")
|
||||||
|
if prefix:
|
||||||
|
parts = prefix.split("/")
|
||||||
|
if len(prefix) > 200 or not all(re.match(r"^[A-Za-z0-9][A-Za-z0-9._ -]{0,63}$", p) for p in parts) or ".." in prefix:
|
||||||
|
raise ValueError("Prefix is invalid: use folders of letters, digits, '.', '_', '-' and spaces")
|
||||||
|
prefix += "/"
|
||||||
|
clean_secrets = {}
|
||||||
|
previous = previous_secrets or {}
|
||||||
|
for key in ("access_key", "secret_key"):
|
||||||
|
value = str(secrets.get(key) or "").strip() or previous.get(key, "")
|
||||||
|
if not value:
|
||||||
|
raise ValueError(f"{'Access key' if key == 'access_key' else 'Secret key'} is required")
|
||||||
|
if len(value) > 512:
|
||||||
|
raise ValueError("Key is too long")
|
||||||
|
clean_secrets[key] = value
|
||||||
|
clean = {"endpoint": endpoint, "secure": bool(params.get("secure", True)),
|
||||||
|
"region": region, "bucket": bucket, "prefix": prefix}
|
||||||
|
return clean, clean_secrets
|
||||||
|
|
||||||
|
def _client(self):
|
||||||
|
try:
|
||||||
|
import urllib3
|
||||||
|
from minio import Minio
|
||||||
|
except ImportError as e: # the package is in requirements.txt; this is a broken installation
|
||||||
|
raise DestinationError("The 'minio' library is not installed") from e
|
||||||
|
http = urllib3.PoolManager(timeout=urllib3.Timeout(connect=10, read=120),
|
||||||
|
retries=urllib3.Retry(total=2, backoff_factor=0.5))
|
||||||
|
return Minio(self.params["endpoint"], access_key=self.secrets["access_key"],
|
||||||
|
secret_key=self.secrets["secret_key"], secure=self.params["secure"],
|
||||||
|
region=self.params["region"] or None, http_client=http)
|
||||||
|
|
||||||
|
def _call(self, fn):
|
||||||
|
from minio.error import S3Error
|
||||||
|
try:
|
||||||
|
return fn()
|
||||||
|
except DestinationError:
|
||||||
|
raise
|
||||||
|
except S3Error as e:
|
||||||
|
raise DestinationError(f"S3 error {e.code}: {str(e.message)[:200]}") from e
|
||||||
|
except Exception as e:
|
||||||
|
raise DestinationError(_short(e)) from e
|
||||||
|
|
||||||
|
def _key(self, name: str) -> str:
|
||||||
|
return self.params["prefix"] + _check_name(name)
|
||||||
|
|
||||||
|
def test(self) -> str:
|
||||||
|
client = self._client()
|
||||||
|
bucket = self.params["bucket"]
|
||||||
|
|
||||||
|
def probe():
|
||||||
|
if not client.bucket_exists(bucket):
|
||||||
|
raise DestinationError(f"Bucket '{bucket}' does not exist or is not visible to this key")
|
||||||
|
key = self.params["prefix"] + f".ovpmon-test-{uuid.uuid4().hex[:8]}"
|
||||||
|
import io
|
||||||
|
client.put_object(bucket, key, io.BytesIO(b"ok"), 2)
|
||||||
|
try:
|
||||||
|
client.remove_object(bucket, key)
|
||||||
|
except Exception:
|
||||||
|
return "Bucket is writable, but deleting objects is not allowed (rotation will not work)"
|
||||||
|
return "Bucket is reachable, write and delete work"
|
||||||
|
return self._call(probe)
|
||||||
|
|
||||||
|
def put(self, local_path, name):
|
||||||
|
client = self._client()
|
||||||
|
self._call(lambda: client.fput_object(self.params["bucket"], self._key(name), local_path,
|
||||||
|
content_type="application/octet-stream"))
|
||||||
|
|
||||||
|
def list(self):
|
||||||
|
client = self._client()
|
||||||
|
prefix = self.params["prefix"]
|
||||||
|
|
||||||
|
def run():
|
||||||
|
out = []
|
||||||
|
for obj in client.list_objects(self.params["bucket"], prefix=prefix or None, recursive=False):
|
||||||
|
if obj.is_dir or not obj.object_name.startswith(prefix):
|
||||||
|
continue
|
||||||
|
name = obj.object_name[len(prefix):]
|
||||||
|
if "/" in name or not name:
|
||||||
|
continue
|
||||||
|
mtime = obj.last_modified.timestamp() if obj.last_modified else None
|
||||||
|
out.append({"name": name, "size": obj.size or 0, "mtime": mtime})
|
||||||
|
return out
|
||||||
|
return self._call(run)
|
||||||
|
|
||||||
|
def get(self, name, local_path):
|
||||||
|
client = self._client()
|
||||||
|
|
||||||
|
def run():
|
||||||
|
resp = client.get_object(self.params["bucket"], self._key(name))
|
||||||
|
try:
|
||||||
|
fd = os.open(local_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as out:
|
||||||
|
shutil.copyfileobj(resp, out, 1024 * 1024)
|
||||||
|
finally:
|
||||||
|
resp.close()
|
||||||
|
resp.release_conn()
|
||||||
|
self._call(run)
|
||||||
|
|
||||||
|
def delete(self, name):
|
||||||
|
client = self._client()
|
||||||
|
self._call(lambda: client.remove_object(self.params["bucket"], self._key(name)))
|
||||||
|
|
||||||
|
|
||||||
|
# --- shared by SFTP and FTP ----------------------------------------------------------------
|
||||||
|
|
||||||
|
CONNECT_TIMEOUT = 15 # seconds: connection, banner, login
|
||||||
|
TRANSFER_TIMEOUT = 120 # seconds without data on an open transfer
|
||||||
|
USER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._@-]{0,127}$")
|
||||||
|
FINGERPRINT_RE = re.compile(r"^SHA256:[A-Za-z0-9+/]{43}$")
|
||||||
|
|
||||||
|
|
||||||
|
def _check_host_port(params: dict, default_port: int):
|
||||||
|
host = str(params.get("host", "")).strip()
|
||||||
|
if not host or not HOST_RE.match(host):
|
||||||
|
raise ValueError("Host must be a host name or an IPv4 address")
|
||||||
|
try:
|
||||||
|
port = int(params.get("port") or default_port)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise ValueError("Port must be a number") from None
|
||||||
|
if not 0 < port < 65536:
|
||||||
|
raise ValueError("Port must be between 1 and 65535")
|
||||||
|
return host, port
|
||||||
|
|
||||||
|
|
||||||
|
def _check_username(params: dict) -> str:
|
||||||
|
user = str(params.get("username", "")).strip()
|
||||||
|
if not USER_RE.match(user):
|
||||||
|
raise ValueError("User name is required (letters, digits, '.', '_', '-', '@')")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _check_directory(params: dict) -> str:
|
||||||
|
"""Remote directory: the same rule as the local folder (relative, no '..', at most 4 levels)."""
|
||||||
|
directory = str(params.get("directory", "")).strip().rstrip("/")
|
||||||
|
if not directory:
|
||||||
|
raise ValueError("Directory is required")
|
||||||
|
if directory.startswith("/"):
|
||||||
|
raise ValueError("Directory must be relative to the login directory of the user (no leading '/')")
|
||||||
|
parts = directory.split("/")
|
||||||
|
if len(parts) > 4 or not all(FOLDER_SEGMENT_RE.match(p) and ".." not in p for p in parts):
|
||||||
|
raise ValueError("Directory must be a relative path of letters, digits, '.', '_' and '-' "
|
||||||
|
"(no '..', no leading dot, at most 4 levels)")
|
||||||
|
return "/".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def _secret_value(secrets: dict, key: str, label: str, limit: int = 512) -> str:
|
||||||
|
value = str(secrets.get(key) or "").strip()
|
||||||
|
if len(value) > limit:
|
||||||
|
raise ValueError(f"{label} is too long")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _ssh_fingerprint(key) -> str:
|
||||||
|
return "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode("ascii").rstrip("=")
|
||||||
|
|
||||||
|
|
||||||
|
# --- SFTP (paramiko) -----------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _paramiko():
|
||||||
|
try:
|
||||||
|
import paramiko
|
||||||
|
except ImportError as e: # the package is in requirements.txt; this is a broken installation
|
||||||
|
raise DestinationError("The 'paramiko' library is not installed") from e
|
||||||
|
return paramiko
|
||||||
|
|
||||||
|
|
||||||
|
def _load_private_key(text: str, passphrase: str):
|
||||||
|
"""paramiko key object of a PEM / OpenSSH private key text. ValueError without any key material."""
|
||||||
|
paramiko = _paramiko()
|
||||||
|
for cls in (paramiko.Ed25519Key, paramiko.ECDSAKey, paramiko.RSAKey):
|
||||||
|
try:
|
||||||
|
return cls.from_private_key(io.StringIO(text), password=passphrase or None)
|
||||||
|
except Exception:
|
||||||
|
continue # not this key type, or a wrong passphrase: the message below covers both
|
||||||
|
raise ValueError("The private key cannot be read: check the key text and its passphrase "
|
||||||
|
"(supported: RSA, ECDSA, Ed25519; OpenSSH or PEM)")
|
||||||
|
|
||||||
|
|
||||||
|
class SFTPDestination(Destination):
|
||||||
|
"""SFTP server. The SSH host key is pinned by its SHA-256 fingerprint: the first Test shows it,
|
||||||
|
the administrator confirms it ('Trust'), after that every connection must present exactly that
|
||||||
|
key. Nothing is copied, listed, read or deleted while the key is not pinned."""
|
||||||
|
type = "sftp"
|
||||||
|
label = "SFTP server"
|
||||||
|
PIN_PARAMS = ("host_key", "host_key_type")
|
||||||
|
PIN_DEPENDS = ("host", "port")
|
||||||
|
FIELDS = [
|
||||||
|
{"name": "host", "label": "Host", "kind": "text", "required": True, "default": "",
|
||||||
|
"hint": "Host name or IPv4 address"},
|
||||||
|
{"name": "port", "label": "Port", "kind": "number", "required": True, "default": 22},
|
||||||
|
{"name": "username", "label": "User name", "kind": "text", "required": True, "default": ""},
|
||||||
|
{"name": "directory", "label": "Directory", "kind": "text", "required": True, "default": "ovpmon-backups",
|
||||||
|
"hint": "Relative to the login directory of the user; created if missing"},
|
||||||
|
{"name": "password", "label": "Password", "kind": "secret", "required": False,
|
||||||
|
"hint": "Password or private key: give one of them"},
|
||||||
|
{"name": "private_key", "label": "Private key (PEM / OpenSSH text)", "kind": "secret_multiline",
|
||||||
|
"required": False},
|
||||||
|
{"name": "key_passphrase", "label": "Private key passphrase (if the key is encrypted)", "kind": "secret",
|
||||||
|
"required": False},
|
||||||
|
]
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def validate(cls, params, secrets, previous_secrets=None):
|
||||||
|
_unknown_keys(params, {"host", "port", "username", "directory"}, "parameters")
|
||||||
|
_unknown_keys(secrets, {"password", "private_key", "key_passphrase"}, "secrets")
|
||||||
|
host, port = _check_host_port(params, 22)
|
||||||
|
clean = {"host": host, "port": port, "username": _check_username(params),
|
||||||
|
"directory": _check_directory(params)}
|
||||||
|
previous = previous_secrets or {}
|
||||||
|
password = _secret_value(secrets, "password", "Password")
|
||||||
|
key = _secret_value(secrets, "private_key", "Private key", 16384).replace("\r\n", "\n")
|
||||||
|
phrase = _secret_value(secrets, "key_passphrase", "Key passphrase")
|
||||||
|
if password and key:
|
||||||
|
raise ValueError("Give a password or a private key, not both")
|
||||||
|
if not password and not key:
|
||||||
|
# nothing new: keep what is stored (a new passphrase goes with the stored key)
|
||||||
|
password, key = previous.get("password", ""), previous.get("private_key", "")
|
||||||
|
phrase = phrase or previous.get("key_passphrase", "")
|
||||||
|
if not password and not key:
|
||||||
|
raise ValueError("A password or a private key is required")
|
||||||
|
if key:
|
||||||
|
if "PRIVATE KEY" not in key:
|
||||||
|
raise ValueError("The private key must be the text of the key file (-----BEGIN ... PRIVATE KEY-----)")
|
||||||
|
_load_private_key(key + "\n", phrase)
|
||||||
|
clean_secrets = {"private_key": key.strip() + "\n"}
|
||||||
|
if phrase:
|
||||||
|
clean_secrets["key_passphrase"] = phrase
|
||||||
|
else:
|
||||||
|
clean_secrets = {"password": password}
|
||||||
|
return clean, clean_secrets
|
||||||
|
|
||||||
|
# -- connection --
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _policy(pinned: Optional[str], seen: dict):
|
||||||
|
"""Host key policy: records what the server shows and accepts ONLY the pinned fingerprint.
|
||||||
|
Unknown keys are rejected (never added automatically)."""
|
||||||
|
paramiko = _paramiko()
|
||||||
|
|
||||||
|
class PinnedPolicy(paramiko.MissingHostKeyPolicy):
|
||||||
|
def missing_host_key(self, client, hostname, key):
|
||||||
|
seen["fingerprint"], seen["key_type"] = _ssh_fingerprint(key), key.get_name()
|
||||||
|
if not pinned or not hmac.compare_digest(seen["fingerprint"], pinned):
|
||||||
|
raise paramiko.SSHException("host key is not trusted")
|
||||||
|
return PinnedPolicy()
|
||||||
|
|
||||||
|
def _connect(self, allow_trust: bool = False):
|
||||||
|
"""Open the SSH connection and return the client. allow_trust: for Test and the pinning
|
||||||
|
call; a key that is unknown or changed then raises NeedsTrust with the fingerprint."""
|
||||||
|
paramiko = _paramiko()
|
||||||
|
pinned = self.params.get("host_key") or None
|
||||||
|
if not pinned and not allow_trust:
|
||||||
|
raise DestinationError("The host key of the server is not trusted yet: run Test and confirm the fingerprint")
|
||||||
|
pkey = None
|
||||||
|
if self.secrets.get("private_key"):
|
||||||
|
try:
|
||||||
|
pkey = _load_private_key(self.secrets["private_key"], self.secrets.get("key_passphrase", ""))
|
||||||
|
except ValueError as e:
|
||||||
|
raise DestinationError(str(e)) from None
|
||||||
|
seen: dict = {}
|
||||||
|
client = paramiko.SSHClient() # no known_hosts is loaded: every key goes to the policy
|
||||||
|
client.set_missing_host_key_policy(self._policy(pinned, seen))
|
||||||
|
try:
|
||||||
|
client.connect(self.params["host"], port=self.params["port"], username=self.params["username"],
|
||||||
|
password=self.secrets.get("password") or None, pkey=pkey,
|
||||||
|
timeout=CONNECT_TIMEOUT, banner_timeout=CONNECT_TIMEOUT, auth_timeout=CONNECT_TIMEOUT,
|
||||||
|
allow_agent=False, look_for_keys=False)
|
||||||
|
except Exception as e:
|
||||||
|
client.close()
|
||||||
|
fp = seen.get("fingerprint")
|
||||||
|
if fp and fp != pinned:
|
||||||
|
if allow_trust:
|
||||||
|
raise NeedsTrust(
|
||||||
|
("The host key changed: it differs from the trusted one" if pinned
|
||||||
|
else "The host key of the server is not trusted yet"),
|
||||||
|
fp, seen.get("key_type", ""), changed=bool(pinned)) from None
|
||||||
|
raise DestinationError("The host key of the server changed: connection refused. "
|
||||||
|
"Run Test to see the new fingerprint and trust it if the change is expected") from None
|
||||||
|
raise DestinationError(self._explain(e)) from None
|
||||||
|
return client
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _explain(e: Exception) -> str:
|
||||||
|
paramiko = _paramiko()
|
||||||
|
if isinstance(e, paramiko.AuthenticationException):
|
||||||
|
return "Authentication failed: check the user name and the password or key"
|
||||||
|
if isinstance(e, (socket.timeout, TimeoutError)):
|
||||||
|
return "Connection timed out"
|
||||||
|
if isinstance(e, socket.gaierror):
|
||||||
|
return "Host name cannot be resolved"
|
||||||
|
if isinstance(e, ConnectionRefusedError):
|
||||||
|
return "Connection refused"
|
||||||
|
if isinstance(e, paramiko.SSHException):
|
||||||
|
return f"SSH error: {str(e)[:200]}"
|
||||||
|
if isinstance(e, OSError):
|
||||||
|
return f"Network error: {e.strerror or type(e).__name__}"
|
||||||
|
return _short(e)
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _session(self, allow_trust: bool = False):
|
||||||
|
client = self._connect(allow_trust)
|
||||||
|
try:
|
||||||
|
sftp = client.open_sftp()
|
||||||
|
sftp.get_channel().settimeout(TRANSFER_TIMEOUT)
|
||||||
|
yield sftp
|
||||||
|
except DestinationError:
|
||||||
|
raise
|
||||||
|
except FileNotFoundError:
|
||||||
|
raise DestinationError("File or directory not found on the server") from None
|
||||||
|
except Exception as e:
|
||||||
|
raise DestinationError(self._explain(e)) from None
|
||||||
|
finally:
|
||||||
|
client.close()
|
||||||
|
|
||||||
|
def fetch_host_key(self):
|
||||||
|
try:
|
||||||
|
self._connect(allow_trust=True).close()
|
||||||
|
except NeedsTrust as n:
|
||||||
|
return n.fingerprint, n.key_type
|
||||||
|
return self.params.get("host_key", ""), self.params.get("host_key_type", "")
|
||||||
|
|
||||||
|
# -- operations --
|
||||||
|
|
||||||
|
def _dir(self, sftp, create: bool) -> str:
|
||||||
|
"""Change into the directory (creating the levels when asked). Returns the path."""
|
||||||
|
path = ""
|
||||||
|
for part in self.params["directory"].split("/"):
|
||||||
|
path = f"{path}/{part}" if path else part
|
||||||
|
try:
|
||||||
|
if not stat.S_ISDIR(sftp.stat(path).st_mode):
|
||||||
|
raise DestinationError(f"'{path}' on the server is not a directory")
|
||||||
|
except FileNotFoundError:
|
||||||
|
if not create:
|
||||||
|
raise DestinationError("Directory does not exist yet") from None
|
||||||
|
sftp.mkdir(path, 0o700)
|
||||||
|
return path
|
||||||
|
|
||||||
|
def test(self) -> str:
|
||||||
|
with self._session(allow_trust=True) as sftp:
|
||||||
|
directory = self._dir(sftp, create=True)
|
||||||
|
probe = f"{directory}/.ovpmon-test-{uuid.uuid4().hex[:8]}"
|
||||||
|
sftp.putfo(io.BytesIO(b"ok"), probe)
|
||||||
|
try:
|
||||||
|
sftp.remove(probe)
|
||||||
|
except Exception:
|
||||||
|
return "Server is writable, but deleting files is not allowed (rotation will not work)"
|
||||||
|
return "SFTP server is reachable, host key matches, write and delete work"
|
||||||
|
|
||||||
|
def put(self, local_path, name):
|
||||||
|
_check_name(name)
|
||||||
|
with self._session() as sftp:
|
||||||
|
directory = self._dir(sftp, create=True)
|
||||||
|
final, tmp = f"{directory}/{name}", f"{directory}/.{name}.part"
|
||||||
|
try:
|
||||||
|
sftp.put(local_path, tmp, confirm=True)
|
||||||
|
try:
|
||||||
|
sftp.posix_rename(tmp, final)
|
||||||
|
except OSError: # the server has no posix-rename extension
|
||||||
|
sftp.rename(tmp, final)
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
sftp.remove(tmp)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
raise
|
||||||
|
|
||||||
|
def list(self):
|
||||||
|
with self._session() as sftp:
|
||||||
|
try:
|
||||||
|
directory = self._dir(sftp, create=False)
|
||||||
|
except DestinationError as e:
|
||||||
|
if "does not exist" in str(e):
|
||||||
|
return []
|
||||||
|
raise
|
||||||
|
return [{"name": a.filename, "size": a.st_size or 0, "mtime": a.st_mtime}
|
||||||
|
for a in sftp.listdir_attr(directory)
|
||||||
|
if stat.S_ISREG(a.st_mode or 0) and PACKAGE_RE.match(a.filename)]
|
||||||
|
|
||||||
|
def get(self, name, local_path):
|
||||||
|
_check_name(name)
|
||||||
|
with self._session() as sftp:
|
||||||
|
remote = f"{self._dir(sftp, create=False)}/{name}"
|
||||||
|
fd = os.open(local_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as out:
|
||||||
|
sftp.getfo(remote, out)
|
||||||
|
|
||||||
|
def delete(self, name):
|
||||||
|
_check_name(name)
|
||||||
|
with self._session() as sftp:
|
||||||
|
try:
|
||||||
|
sftp.remove(f"{self._dir(sftp, create=False)}/{name}")
|
||||||
|
except FileNotFoundError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# --- FTP / FTPS (ftplib) -------------------------------------------------------------------
|
||||||
|
|
||||||
|
class FTPDestination(Destination):
|
||||||
|
"""FTP server; explicit FTPS (AUTH TLS) with certificate verification by default. Plain FTP and a
|
||||||
|
disabled certificate check are allowed explicitly (the UI warns)."""
|
||||||
|
type = "ftp"
|
||||||
|
label = "FTP / FTPS server"
|
||||||
|
FIELDS = [
|
||||||
|
{"name": "host", "label": "Host", "kind": "text", "required": True, "default": "",
|
||||||
|
"hint": "Host name or IPv4 address"},
|
||||||
|
{"name": "port", "label": "Port", "kind": "number", "required": True, "default": 21},
|
||||||
|
{"name": "username", "label": "User name", "kind": "text", "required": True, "default": ""},
|
||||||
|
{"name": "directory", "label": "Directory", "kind": "text", "required": True, "default": "ovpmon-backups",
|
||||||
|
"hint": "Relative to the login directory of the user; created if missing"},
|
||||||
|
{"name": "tls", "label": "Use TLS (explicit FTPS)", "kind": "bool", "required": False, "default": True,
|
||||||
|
"warning": "Without TLS the password and the packages travel in clear text. Use only inside a trusted network.",
|
||||||
|
"warn_if": False},
|
||||||
|
{"name": "verify_cert", "label": "Verify the server certificate", "kind": "bool", "required": False,
|
||||||
|
"default": True,
|
||||||
|
"warning": "Certificate verification is off: the server cannot be told from an impostor. Use only for a self-signed certificate in a trusted network.",
|
||||||
|
"warn_if": False},
|
||||||
|
{"name": "passive", "label": "Passive mode", "kind": "bool", "required": False, "default": True},
|
||||||
|
{"name": "password", "label": "Password", "kind": "secret", "required": True},
|
||||||
|
]
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def validate(cls, params, secrets, previous_secrets=None):
|
||||||
|
_unknown_keys(params, {"host", "port", "username", "directory", "tls", "verify_cert", "passive"}, "parameters")
|
||||||
|
_unknown_keys(secrets, {"password"}, "secrets")
|
||||||
|
host, port = _check_host_port(params, 21)
|
||||||
|
clean = {"host": host, "port": port, "username": _check_username(params),
|
||||||
|
"directory": _check_directory(params),
|
||||||
|
"tls": bool(params.get("tls", True)), "verify_cert": bool(params.get("verify_cert", True)),
|
||||||
|
"passive": bool(params.get("passive", True))}
|
||||||
|
password = _secret_value(secrets, "password", "Password") or (previous_secrets or {}).get("password", "")
|
||||||
|
if not password:
|
||||||
|
raise ValueError("Password is required")
|
||||||
|
return clean, {"password": password}
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _session(self, create_dir: bool = False):
|
||||||
|
import ftplib
|
||||||
|
p = self.params
|
||||||
|
try:
|
||||||
|
if p["tls"]:
|
||||||
|
ctx = ssl.create_default_context()
|
||||||
|
if not p["verify_cert"]:
|
||||||
|
ctx.check_hostname = False
|
||||||
|
ctx.verify_mode = ssl.CERT_NONE
|
||||||
|
ftp = ftplib.FTP_TLS(context=ctx, timeout=TRANSFER_TIMEOUT)
|
||||||
|
else:
|
||||||
|
ftp = ftplib.FTP(timeout=TRANSFER_TIMEOUT)
|
||||||
|
except Exception as e:
|
||||||
|
raise DestinationError(_short(e)) from None
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
ftp.connect(p["host"], p["port"], timeout=CONNECT_TIMEOUT)
|
||||||
|
ftp.login(p["username"], self.secrets["password"])
|
||||||
|
ftp.timeout = TRANSFER_TIMEOUT # transfers (data connections) wait longer than the login
|
||||||
|
ftp.sock.settimeout(TRANSFER_TIMEOUT)
|
||||||
|
if p["tls"]:
|
||||||
|
ftp.prot_p() # TLS for the data connection too
|
||||||
|
ftp.set_pasv(p["passive"])
|
||||||
|
self._cd(ftp, create_dir)
|
||||||
|
yield ftp
|
||||||
|
except DestinationError:
|
||||||
|
raise
|
||||||
|
except Exception as e:
|
||||||
|
raise DestinationError(self._explain(e)) from None
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
ftp.quit()
|
||||||
|
except Exception:
|
||||||
|
ftp.close()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _explain(e: Exception) -> str:
|
||||||
|
import ftplib
|
||||||
|
if isinstance(e, ssl.SSLCertVerificationError):
|
||||||
|
return f"TLS certificate check failed: {(e.verify_message or 'invalid certificate')[:150]}. " \
|
||||||
|
"For a self-signed certificate turn the verification off in the destination"
|
||||||
|
if isinstance(e, ssl.SSLError):
|
||||||
|
return f"TLS error: {(e.reason or type(e).__name__)}"
|
||||||
|
if isinstance(e, ftplib.error_perm):
|
||||||
|
text = str(e)[:200]
|
||||||
|
return "Login failed: check the user name and the password" if text.startswith("530") else f"Server refused: {text}"
|
||||||
|
if isinstance(e, ftplib.Error):
|
||||||
|
return f"FTP error: {str(e)[:200]}"
|
||||||
|
if isinstance(e, (socket.timeout, TimeoutError)):
|
||||||
|
return "Connection timed out"
|
||||||
|
if isinstance(e, socket.gaierror):
|
||||||
|
return "Host name cannot be resolved"
|
||||||
|
if isinstance(e, ConnectionRefusedError):
|
||||||
|
return "Connection refused"
|
||||||
|
if isinstance(e, EOFError):
|
||||||
|
return "The server closed the connection"
|
||||||
|
if isinstance(e, OSError):
|
||||||
|
return f"Network error: {e.strerror or type(e).__name__}"
|
||||||
|
return _short(e)
|
||||||
|
|
||||||
|
def _cd(self, ftp, create: bool) -> None:
|
||||||
|
import ftplib
|
||||||
|
for part in self.params["directory"].split("/"):
|
||||||
|
try:
|
||||||
|
ftp.cwd(part)
|
||||||
|
except ftplib.error_perm:
|
||||||
|
if not create:
|
||||||
|
raise DestinationError("Directory does not exist yet") from None
|
||||||
|
ftp.mkd(part)
|
||||||
|
ftp.cwd(part)
|
||||||
|
|
||||||
|
def test(self) -> str:
|
||||||
|
with self._session(create_dir=True) as ftp:
|
||||||
|
probe = f".ovpmon-test-{uuid.uuid4().hex[:8]}"
|
||||||
|
ftp.storbinary(f"STOR {probe}", io.BytesIO(b"ok"))
|
||||||
|
try:
|
||||||
|
ftp.delete(probe)
|
||||||
|
except Exception:
|
||||||
|
return "Server is writable, but deleting files is not allowed (rotation will not work)"
|
||||||
|
mode = "TLS" if self.params["tls"] else "NO TLS (clear text)"
|
||||||
|
return f"FTP server is reachable ({mode}), write and delete work"
|
||||||
|
|
||||||
|
def put(self, local_path, name):
|
||||||
|
_check_name(name)
|
||||||
|
tmp = f".{name}.part"
|
||||||
|
with self._session(create_dir=True) as ftp:
|
||||||
|
try:
|
||||||
|
with open(local_path, "rb") as src:
|
||||||
|
ftp.storbinary(f"STOR {tmp}", src, blocksize=1024 * 1024)
|
||||||
|
ftp.rename(tmp, name)
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
ftp.delete(tmp)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
raise
|
||||||
|
|
||||||
|
def list(self):
|
||||||
|
try:
|
||||||
|
with self._session() as ftp:
|
||||||
|
return self._packages(ftp)
|
||||||
|
except DestinationError as e:
|
||||||
|
if "does not exist" in str(e):
|
||||||
|
return []
|
||||||
|
raise
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _packages(ftp):
|
||||||
|
import ftplib
|
||||||
|
out = []
|
||||||
|
try:
|
||||||
|
for name, facts in ftp.mlsd(facts=["type", "size", "modify"]):
|
||||||
|
if facts.get("type") == "file" and PACKAGE_RE.match(name):
|
||||||
|
out.append({"name": name, "size": int(facts.get("size") or 0),
|
||||||
|
"mtime": FTPDestination._mtime(facts.get("modify"))})
|
||||||
|
return out
|
||||||
|
except ftplib.error_perm:
|
||||||
|
out = [] # no MLSD on this server: names first, then size and time of our packages
|
||||||
|
ftp.voidcmd("TYPE I")
|
||||||
|
for entry in ftp.nlst():
|
||||||
|
name = entry.rsplit("/", 1)[-1]
|
||||||
|
if not PACKAGE_RE.match(name):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
size = ftp.size(name) or 0
|
||||||
|
except ftplib.Error:
|
||||||
|
size = 0
|
||||||
|
try:
|
||||||
|
mtime = FTPDestination._mtime(ftp.voidcmd(f"MDTM {name}").split()[-1])
|
||||||
|
except ftplib.Error:
|
||||||
|
mtime = None
|
||||||
|
out.append({"name": name, "size": size, "mtime": mtime})
|
||||||
|
return out
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _mtime(modify):
|
||||||
|
try:
|
||||||
|
return datetime.strptime(modify[:14], "%Y%m%d%H%M%S").replace(tzinfo=timezone.utc).timestamp()
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def get(self, name, local_path):
|
||||||
|
_check_name(name)
|
||||||
|
with self._session() as ftp:
|
||||||
|
ftp.voidcmd("TYPE I")
|
||||||
|
fd = os.open(local_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as out:
|
||||||
|
ftp.retrbinary(f"RETR {name}", out.write, blocksize=1024 * 1024)
|
||||||
|
|
||||||
|
def delete(self, name):
|
||||||
|
_check_name(name)
|
||||||
|
with self._session() as ftp:
|
||||||
|
ftp.delete(name)
|
||||||
|
|
||||||
|
|
||||||
|
# Registry: the API accepts exactly these types. smb comes in a later pass.
|
||||||
|
DESTINATION_TYPES = {
|
||||||
|
LocalDestination.type: LocalDestination,
|
||||||
|
S3Destination.type: S3Destination,
|
||||||
|
SFTPDestination.type: SFTPDestination,
|
||||||
|
FTPDestination.type: FTPDestination,
|
||||||
|
}
|
||||||
|
|
||||||
|
REMOTE_TYPES = {t for t in DESTINATION_TYPES if t != "local"} # these need an encryption passphrase
|
||||||
|
|
||||||
|
|
||||||
|
def build_destination(dtype: str, params: dict, secrets: dict) -> Destination:
|
||||||
|
cls = DESTINATION_TYPES.get(dtype)
|
||||||
|
if cls is None:
|
||||||
|
raise BackupError(f"Unsupported destination type: {dtype}")
|
||||||
|
return cls(params, secrets)
|
||||||
@@ -0,0 +1,657 @@
|
|||||||
|
"""Backup job and restore engine.
|
||||||
|
|
||||||
|
One background job at a time for the whole service (a backup or a restore), like the async PKI
|
||||||
|
initialization: the state lives in memory of the single Profiler process, results go to the history
|
||||||
|
in ovpmon_backup.db.
|
||||||
|
"""
|
||||||
|
import copy
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import sqlite3
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
import migrations
|
||||||
|
from database import SessionLocal, engine as sa_engine
|
||||||
|
|
||||||
|
from . import BackupError, Busy, Invalid, crypto, destinations, package, store
|
||||||
|
from services import pki, process
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
PRE_RESTORE_FOLDER = "pre-restore"
|
||||||
|
PRE_RESTORE_KEEP = 5
|
||||||
|
|
||||||
|
_lock = threading.Lock()
|
||||||
|
_job = {"kind": None, "state": "idle", "stages": [], "results": [], "warnings": [],
|
||||||
|
"started_at": None, "finished_at": None, "message": None, "relogin": False}
|
||||||
|
|
||||||
|
|
||||||
|
# --- paths ---------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def profiler_db_path() -> str:
|
||||||
|
from database import db_path
|
||||||
|
return os.path.abspath(db_path)
|
||||||
|
|
||||||
|
|
||||||
|
def monitor_db_path() -> str:
|
||||||
|
env = os.environ.get("OVPMON_OPENVPN_MONITOR_DB_PATH", "").strip()
|
||||||
|
return os.path.abspath(env) if env else os.path.join(os.path.dirname(profiler_db_path()), "openvpn_monitor.db")
|
||||||
|
|
||||||
|
|
||||||
|
def pki_dir() -> str:
|
||||||
|
return pki.PKI_DIR
|
||||||
|
|
||||||
|
|
||||||
|
def client_dir() -> str:
|
||||||
|
return os.path.join(os.getcwd(), "client-config")
|
||||||
|
|
||||||
|
|
||||||
|
def runtime() -> str:
|
||||||
|
return "container" if process.is_container() else "host"
|
||||||
|
|
||||||
|
|
||||||
|
def _work_dir() -> str:
|
||||||
|
"""Temporary directory for a job: next to the local backups (they have room by definition),
|
||||||
|
else the system temporary directory."""
|
||||||
|
base = os.environ.get("OVPMON_BACKUP_WORK_DIR", "").strip() or os.path.join(destinations.local_root(), ".work")
|
||||||
|
try:
|
||||||
|
os.makedirs(base, mode=0o700, exist_ok=True)
|
||||||
|
except OSError:
|
||||||
|
base = None
|
||||||
|
return tempfile.mkdtemp(prefix="job-", dir=base)
|
||||||
|
|
||||||
|
|
||||||
|
# --- job state -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _now() -> str:
|
||||||
|
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||||
|
|
||||||
|
|
||||||
|
def status() -> dict:
|
||||||
|
with _lock:
|
||||||
|
return copy.deepcopy(_job)
|
||||||
|
|
||||||
|
|
||||||
|
def is_running() -> bool:
|
||||||
|
with _lock:
|
||||||
|
return _job["state"] == "running"
|
||||||
|
|
||||||
|
|
||||||
|
def _claim(kind: str, stages: list, results: list) -> None:
|
||||||
|
with _lock:
|
||||||
|
if _job["state"] == "running":
|
||||||
|
raise Busy(f"A {_job['kind']} is already running")
|
||||||
|
_job.update(kind=kind, state="running", stages=[{"name": n, "state": "pending"} for n in stages],
|
||||||
|
results=results, warnings=[], started_at=_now(), finished_at=None, message=None,
|
||||||
|
relogin=False)
|
||||||
|
|
||||||
|
|
||||||
|
def _stage(name: str, state: str = "running") -> None:
|
||||||
|
with _lock:
|
||||||
|
for s in _job["stages"]:
|
||||||
|
if s["name"] == name:
|
||||||
|
s["state"] = state
|
||||||
|
elif s["state"] == "running" and state == "running":
|
||||||
|
s["state"] = "done"
|
||||||
|
|
||||||
|
|
||||||
|
def _warn(text: str) -> None:
|
||||||
|
logger.warning(f"[BACKUP] {text}")
|
||||||
|
with _lock:
|
||||||
|
_job["warnings"].append(text)
|
||||||
|
|
||||||
|
|
||||||
|
def _finish(state: str, message: str, relogin: bool = False) -> None:
|
||||||
|
with _lock:
|
||||||
|
for s in _job["stages"]:
|
||||||
|
if s["state"] == "running":
|
||||||
|
s["state"] = "done" if state in ("done", "partial") else "error"
|
||||||
|
_job.update(state=state, message=message, finished_at=_now(), relogin=relogin)
|
||||||
|
|
||||||
|
|
||||||
|
def _result(index: int, **fields) -> None:
|
||||||
|
with _lock:
|
||||||
|
_job["results"][index].update(fields)
|
||||||
|
|
||||||
|
|
||||||
|
# --- destinations --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def build_dest(rec: dict) -> destinations.Destination:
|
||||||
|
if not rec.get("secrets_ok", True):
|
||||||
|
raise BackupError("Stored secrets of this destination cannot be decrypted "
|
||||||
|
"(the JWT secret changed). Edit the destination and enter them again.")
|
||||||
|
return destinations.build_destination(rec["type"], rec["params"], rec["secrets"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_destination(dest_id: int) -> dict:
|
||||||
|
rec = store.get_destination(dest_id, with_secrets=True)
|
||||||
|
if not rec:
|
||||||
|
raise Invalid("Destination not found")
|
||||||
|
try:
|
||||||
|
message = build_dest(rec).test()
|
||||||
|
except destinations.NeedsTrust as e:
|
||||||
|
# SFTP: the host key is not pinned (or changed): show it, the administrator decides
|
||||||
|
store.set_last_result(dest_id, False, str(e))
|
||||||
|
return {"ok": False, "message": str(e), "needs_trust": True, "fingerprint": e.fingerprint,
|
||||||
|
"key_type": e.key_type, "key_changed": e.changed}
|
||||||
|
except BackupError as e:
|
||||||
|
store.set_last_result(dest_id, False, str(e))
|
||||||
|
return {"ok": False, "message": str(e)}
|
||||||
|
except Exception as e: # a driver error that is not mapped: report it, never crash the API
|
||||||
|
logger.exception("Destination test failed")
|
||||||
|
message = f"{type(e).__name__}: {str(e)[:200]}"
|
||||||
|
store.set_last_result(dest_id, False, message)
|
||||||
|
return {"ok": False, "message": message}
|
||||||
|
store.set_last_result(dest_id, True, message)
|
||||||
|
return {"ok": True, "message": message}
|
||||||
|
|
||||||
|
|
||||||
|
def effective_server_name() -> tuple:
|
||||||
|
"""(name, source): the server name of the settings, else the public address from the VPN
|
||||||
|
settings, else the host name. The name goes into the package names."""
|
||||||
|
name = store.get_server_name()
|
||||||
|
if name and package.SERVER_NAME_RE.match(name):
|
||||||
|
return name, "setting"
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(f"file:{profiler_db_path()}?mode=ro", uri=True, timeout=5)
|
||||||
|
try:
|
||||||
|
row = conn.execute("SELECT public_ip FROM system_settings LIMIT 1").fetchone()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
name = package.sanitize_name(row[0]) if row and row[0] else ""
|
||||||
|
if name:
|
||||||
|
return name, "public_ip"
|
||||||
|
except sqlite3.Error:
|
||||||
|
pass # no settings yet (or the column is absent): fall through
|
||||||
|
return package.host_name(), "hostname"
|
||||||
|
|
||||||
|
|
||||||
|
def trust_host_key(dest_id: int, fingerprint: str) -> dict:
|
||||||
|
"""Pin the host key the server shows now, if it is the one the administrator saw (`fingerprint`)."""
|
||||||
|
rec = store.get_destination(dest_id, with_secrets=True)
|
||||||
|
if not rec:
|
||||||
|
raise Invalid("Destination not found")
|
||||||
|
cls = destinations.DESTINATION_TYPES.get(rec["type"])
|
||||||
|
if not cls or not cls.PIN_PARAMS:
|
||||||
|
raise Invalid("This destination type has no host key")
|
||||||
|
if not destinations.FINGERPRINT_RE.match(fingerprint or ""):
|
||||||
|
raise Invalid("Invalid fingerprint")
|
||||||
|
shown, key_type = build_dest(rec).fetch_host_key()
|
||||||
|
if shown != fingerprint:
|
||||||
|
raise Invalid("The server now shows a different host key than the one you saw: run Test again")
|
||||||
|
params = dict(rec["params"], host_key=shown, host_key_type=key_type)
|
||||||
|
store.save_destination(rec["id"], rec["name"], rec["type"], rec["enabled"], rec["retention_count"],
|
||||||
|
params, rec["secrets"])
|
||||||
|
store.set_last_result(rec["id"], True, f"Host key {shown} trusted")
|
||||||
|
return store.get_destination(rec["id"])
|
||||||
|
|
||||||
|
|
||||||
|
def list_packages(dest_id: int) -> list:
|
||||||
|
"""Packages of our name pattern in the destination, newest first."""
|
||||||
|
rec = store.get_destination(dest_id, with_secrets=True)
|
||||||
|
if not rec:
|
||||||
|
raise Invalid("Destination not found")
|
||||||
|
items = []
|
||||||
|
for obj in build_dest(rec).list():
|
||||||
|
meta = package.parse_package_name(obj["name"])
|
||||||
|
if meta:
|
||||||
|
items.append({"name": obj["name"], "server_name": meta["host"], "created_at": meta["created_at"],
|
||||||
|
"encrypted": meta["encrypted"], "size": obj["size"],
|
||||||
|
"_key": (meta["stamp"], meta["seq"], obj["name"])})
|
||||||
|
items.sort(key=lambda i: i["_key"], reverse=True)
|
||||||
|
for i in items:
|
||||||
|
del i["_key"]
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def put_unique(dest: destinations.Destination, path: str, base_name: str) -> str:
|
||||||
|
"""Store the package under base_name, or under -2, -3 ... when the destination already has a
|
||||||
|
package of that second. Returns the name used."""
|
||||||
|
meta = package.parse_package_name(base_name)
|
||||||
|
name = package.unique_package_name(meta["host"], meta["stamp"], meta["encrypted"],
|
||||||
|
(o["name"] for o in dest.list()))
|
||||||
|
dest.put(path, name)
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
def rotate(dest: destinations.Destination, keep: int, keep_name: str, server_name: str) -> int:
|
||||||
|
"""Delete the oldest packages of this server name beyond `keep` (never keep_name). Packages
|
||||||
|
with another name in the same folder (other servers, or made under an earlier name or by host
|
||||||
|
name) are not ours to delete. Returns the number removed."""
|
||||||
|
mine = []
|
||||||
|
for obj in dest.list():
|
||||||
|
meta = package.parse_package_name(obj["name"])
|
||||||
|
if meta and meta["host"] == server_name:
|
||||||
|
mine.append(((meta["stamp"], meta["seq"]), obj["name"]))
|
||||||
|
mine.sort(reverse=True)
|
||||||
|
removed = 0
|
||||||
|
for _key, name in mine[max(keep, 1):]:
|
||||||
|
if name != keep_name:
|
||||||
|
dest.delete(name)
|
||||||
|
removed += 1
|
||||||
|
return removed
|
||||||
|
|
||||||
|
|
||||||
|
# --- package creation ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
def create_package(work: str, passphrase: Optional[str]):
|
||||||
|
"""Build (and encrypt, if a passphrase is given) a package in `work`. Returns (path, name, manifest);
|
||||||
|
name is the plain name, a destination may add -2, -3 when that second is taken (put_unique)."""
|
||||||
|
stamp = package.utc_stamp()
|
||||||
|
server_name, _source = effective_server_name()
|
||||||
|
plain = os.path.join(work, "package.tar.gz")
|
||||||
|
manifest = package.build_package(plain, work, profiler_db_path(), monitor_db_path(),
|
||||||
|
pki_dir(), client_dir(), runtime(), server_name)
|
||||||
|
path = plain
|
||||||
|
if passphrase:
|
||||||
|
path = os.path.join(work, "package.enc")
|
||||||
|
crypto.encrypt_file(plain, path, passphrase)
|
||||||
|
os.remove(plain)
|
||||||
|
return path, package.package_name(server_name, stamp, bool(passphrase)), manifest
|
||||||
|
|
||||||
|
|
||||||
|
# --- backup job ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def start_backup(destination_ids: Optional[list] = None) -> None:
|
||||||
|
all_dests = store.list_destinations(with_secrets=True)
|
||||||
|
if destination_ids is None:
|
||||||
|
selected = [d for d in all_dests if d["enabled"]]
|
||||||
|
else:
|
||||||
|
by_id = {d["id"]: d for d in all_dests}
|
||||||
|
selected = []
|
||||||
|
for i in dict.fromkeys(destination_ids):
|
||||||
|
if i not in by_id:
|
||||||
|
raise Invalid(f"Destination {i} not found")
|
||||||
|
if not by_id[i]["enabled"]:
|
||||||
|
raise Invalid(f"Destination '{by_id[i]['name']}' is disabled")
|
||||||
|
selected.append(by_id[i])
|
||||||
|
if not selected:
|
||||||
|
raise Invalid("No destinations selected: add and enable a destination first")
|
||||||
|
if any(d["type"] in destinations.REMOTE_TYPES for d in selected) and not store.has_passphrase():
|
||||||
|
raise Invalid("A passphrase is required for remote destinations: set the encryption passphrase first")
|
||||||
|
passphrase = store.get_passphrase()
|
||||||
|
stages = ["package"] + (["encrypt"] if passphrase else []) + ["upload"]
|
||||||
|
results = [{"destination_id": d["id"], "name": d["name"], "type": d["type"], "state": "pending",
|
||||||
|
"message": None, "package": None} for d in selected]
|
||||||
|
_claim("backup", stages, results)
|
||||||
|
hist_id = store.history_start("backup")
|
||||||
|
threading.Thread(target=_backup_worker, args=(selected, passphrase, hist_id), daemon=True).start()
|
||||||
|
|
||||||
|
|
||||||
|
def _backup_worker(selected: list, passphrase: Optional[str], hist_id: int) -> None:
|
||||||
|
work = None
|
||||||
|
try:
|
||||||
|
work = _work_dir()
|
||||||
|
_stage("package")
|
||||||
|
# create_package encrypts too: show the second stage once the tar is written
|
||||||
|
path, name, manifest = create_package(work, passphrase)
|
||||||
|
if passphrase:
|
||||||
|
_stage("encrypt", "done")
|
||||||
|
_stage("upload")
|
||||||
|
size = os.path.getsize(path)
|
||||||
|
server_name = manifest["server_name"]
|
||||||
|
for i, rec in enumerate(selected):
|
||||||
|
_result(i, state="running")
|
||||||
|
try:
|
||||||
|
dest = build_dest(rec)
|
||||||
|
stored = put_unique(dest, path, name)
|
||||||
|
note = f"{stored} ({size // 1024} KB)"
|
||||||
|
try:
|
||||||
|
removed = rotate(dest, rec["retention_count"], stored, server_name)
|
||||||
|
if removed:
|
||||||
|
note += f", {removed} old removed"
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"[BACKUP] rotation failed for '{rec['name']}': {type(e).__name__}")
|
||||||
|
note += f", rotation failed: {str(e)[:150]}"
|
||||||
|
_result(i, state="ok", message=note, package=stored)
|
||||||
|
store.set_last_result(rec["id"], True, note)
|
||||||
|
except Exception as e:
|
||||||
|
msg = str(e)[:300] if isinstance(e, BackupError) else f"{type(e).__name__}: {str(e)[:200]}"
|
||||||
|
logger.error(f"[BACKUP] destination '{rec['name']}' failed: {msg}")
|
||||||
|
_result(i, state="error", message=msg)
|
||||||
|
store.set_last_result(rec["id"], False, msg)
|
||||||
|
with _lock:
|
||||||
|
results = copy.deepcopy(_job["results"])
|
||||||
|
ok = sum(1 for r in results if r["state"] == "ok")
|
||||||
|
if ok == len(results):
|
||||||
|
state, message = "done", f"Backup stored in {ok} destination(s)"
|
||||||
|
elif ok:
|
||||||
|
state, message = "partial", f"Backup stored in {ok} of {len(results)} destinations"
|
||||||
|
else:
|
||||||
|
state, message = "error", "Backup failed in every destination"
|
||||||
|
_finish(state, message)
|
||||||
|
store.history_finish(hist_id, state, message, results)
|
||||||
|
except Exception as e:
|
||||||
|
logger.exception("Backup failed")
|
||||||
|
message = str(e)[:500] if isinstance(e, BackupError) else f"Backup failed: {type(e).__name__}: {str(e)[:300]}"
|
||||||
|
for i in range(len(selected)):
|
||||||
|
_result(i, state="skipped", message="Package was not created")
|
||||||
|
_finish("error", message)
|
||||||
|
store.history_finish(hist_id, "error", message, [])
|
||||||
|
finally:
|
||||||
|
if work:
|
||||||
|
shutil.rmtree(work, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
# --- restore -------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
RESTORE_STAGES = ["download", "decrypt", "verify", "prepare", "safety_backup", "stop_openvpn",
|
||||||
|
"replace", "finalize"]
|
||||||
|
|
||||||
|
|
||||||
|
def start_restore(destination_id: int, package_name: str, passphrase: Optional[str]) -> None:
|
||||||
|
rec = store.get_destination(destination_id, with_secrets=True)
|
||||||
|
if not rec:
|
||||||
|
raise Invalid("Destination not found")
|
||||||
|
meta = package.parse_package_name(package_name)
|
||||||
|
if not meta:
|
||||||
|
raise Invalid("Invalid package name")
|
||||||
|
if meta["encrypted"] and not passphrase:
|
||||||
|
raise Invalid("The package is encrypted: enter its passphrase")
|
||||||
|
if pki.is_init_running():
|
||||||
|
raise Busy("PKI initialization is running")
|
||||||
|
if is_running():
|
||||||
|
raise Busy(f"A {status()['kind']} is already running")
|
||||||
|
# Only names from the destination's listing are restored
|
||||||
|
if package_name not in {o["name"] for o in build_dest(rec).list()}:
|
||||||
|
raise Invalid("The package is not in the destination")
|
||||||
|
stages = [s for s in RESTORE_STAGES if s != "decrypt" or meta["encrypted"]]
|
||||||
|
_claim("restore", stages, [{"destination_id": rec["id"], "name": rec["name"], "type": rec["type"],
|
||||||
|
"state": "running", "message": None, "package": package_name}])
|
||||||
|
pki.set_restore_running(True)
|
||||||
|
hist_id = store.history_start("restore")
|
||||||
|
threading.Thread(target=_restore_worker, args=(rec, package_name, meta["encrypted"], passphrase, hist_id),
|
||||||
|
daemon=True).start()
|
||||||
|
|
||||||
|
|
||||||
|
def core_dir() -> Optional[str]:
|
||||||
|
"""Directory of the monitoring component (it owns the migrations of openvpn_monitor.db):
|
||||||
|
migrate.py with migrations.py and db.py (standard library only).
|
||||||
|
OVPMON_CORE_DIR (profiler image: /opt/core), else APP_CORE next to APP_PROFILER (system
|
||||||
|
services, all-in-one container). None for an old profiler image without that directory."""
|
||||||
|
env = os.environ.get("OVPMON_CORE_DIR", "").strip()
|
||||||
|
if not env:
|
||||||
|
code = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
env = os.path.join(os.path.dirname(code), "APP_CORE")
|
||||||
|
if all(os.path.isfile(os.path.join(env, f)) for f in ("migrate.py", "migrations.py", "db.py")):
|
||||||
|
return env
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _migrate_monitor(db_file: str) -> None:
|
||||||
|
"""Bring the monitoring database of the package up to this release's schema.
|
||||||
|
|
||||||
|
The migrations live in the monitoring component, which this process cannot import (separate
|
||||||
|
virtualenv). Its own migrate.py runs on the staged copy with the interpreter of APP_CORE/venv
|
||||||
|
(or this one: the code uses the standard library only). Without the code on disk (an old
|
||||||
|
profiler image) only a package with exactly the schema of the running monitoring database is
|
||||||
|
accepted: the monitoring services would otherwise read an unmigrated database."""
|
||||||
|
version = package.schema_version(db_file)
|
||||||
|
core = core_dir()
|
||||||
|
if core:
|
||||||
|
venv_python = os.path.join(core, "venv", "bin", "python")
|
||||||
|
python = venv_python if os.path.isfile(venv_python) else sys.executable
|
||||||
|
try:
|
||||||
|
r = subprocess.run([python, "migrate.py", "--db", db_file], cwd=core, capture_output=True,
|
||||||
|
text=True, timeout=300)
|
||||||
|
except (OSError, subprocess.TimeoutExpired) as e:
|
||||||
|
raise BackupError(f"Cannot run the monitoring database migration: {e}") from e
|
||||||
|
if r.returncode != 0:
|
||||||
|
lines = [ln for ln in (r.stderr or r.stdout or "").strip().splitlines() if ln.strip()]
|
||||||
|
raise BackupError("The monitoring database of the package cannot be migrated: "
|
||||||
|
+ (lines[-1][:300] if lines else f"exit code {r.returncode}"))
|
||||||
|
return
|
||||||
|
live = package.schema_version(monitor_db_path())
|
||||||
|
if not live:
|
||||||
|
raise BackupError("The monitoring database schema cannot be checked: the monitoring component "
|
||||||
|
"is not available to this service and its database is not initialized")
|
||||||
|
if version != live:
|
||||||
|
which = "newer" if (version or 0) > live else "older"
|
||||||
|
raise BackupError(
|
||||||
|
f"The package has a {which} monitoring database schema ({version}) than this installation "
|
||||||
|
f"({live}). The migration code of the monitoring component (OVPMON_CORE_DIR) is not "
|
||||||
|
f"available to this service. Rebuild the profiler image or restore on the same release.")
|
||||||
|
|
||||||
|
|
||||||
|
def _prepare_staged(extracted: str, manifest: dict) -> None:
|
||||||
|
"""Checks and migrations on the unpacked copies: nothing of the running system is touched yet."""
|
||||||
|
prof = os.path.join(extracted, package.DB_PROFILER)
|
||||||
|
mon = os.path.join(extracted, package.DB_MONITOR)
|
||||||
|
for path in (prof, mon):
|
||||||
|
if not package.integrity_ok(path):
|
||||||
|
raise BackupError(f"{os.path.basename(path)} in the package failed the integrity check")
|
||||||
|
version, latest = package.schema_version(prof), migrations.latest_version()
|
||||||
|
if version is None or version > latest:
|
||||||
|
raise BackupError(f"The package was made by a newer release (profiler database schema {version}, "
|
||||||
|
f"this release knows up to {latest}). Update this installation first.")
|
||||||
|
try:
|
||||||
|
migrations.run(prof)
|
||||||
|
except migrations.MigrationError as e:
|
||||||
|
raise BackupError(f"The profiler database of the package cannot be migrated: {str(e)[:300]}") from e
|
||||||
|
_migrate_monitor(mon)
|
||||||
|
|
||||||
|
|
||||||
|
def _safety_backup() -> str:
|
||||||
|
"""Package of the current state in the local pre-restore folder. Raises when it cannot be made."""
|
||||||
|
try:
|
||||||
|
passphrase = store.get_passphrase()
|
||||||
|
except BackupError:
|
||||||
|
passphrase = None
|
||||||
|
_warn("The safety copy is not encrypted: the stored passphrase cannot be decrypted")
|
||||||
|
work = _work_dir()
|
||||||
|
try:
|
||||||
|
path, name, manifest = create_package(work, passphrase)
|
||||||
|
dest = destinations.LocalDestination({"folder": PRE_RESTORE_FOLDER}, {})
|
||||||
|
name = put_unique(dest, path, name)
|
||||||
|
try:
|
||||||
|
rotate(dest, PRE_RESTORE_KEEP, name, manifest["server_name"])
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"[BACKUP] pre-restore rotation failed: {type(e).__name__}")
|
||||||
|
return name
|
||||||
|
finally:
|
||||||
|
shutil.rmtree(work, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _replace_db(target: str, new_file: str, tag: str, undo: list) -> None:
|
||||||
|
"""Atomic replacement of a database file. The old file (and its -wal/-shm) is kept under a
|
||||||
|
.old-<tag> name until the whole restore succeeded."""
|
||||||
|
tmp = f"{target}.restore-{tag}"
|
||||||
|
old = f"{target}.old-{tag}"
|
||||||
|
shutil.copyfile(new_file, tmp)
|
||||||
|
os.chmod(tmp, (os.stat(target).st_mode & 0o777) if os.path.exists(target) else 0o600)
|
||||||
|
if os.path.exists(target):
|
||||||
|
try:
|
||||||
|
os.link(target, old)
|
||||||
|
except OSError:
|
||||||
|
shutil.copy2(target, old)
|
||||||
|
undo.append(("db", target, old))
|
||||||
|
# A leftover journal of the old database must never be applied to the new file
|
||||||
|
for suffix in ("-wal", "-shm"):
|
||||||
|
if os.path.exists(target + suffix):
|
||||||
|
os.replace(target + suffix, old + suffix)
|
||||||
|
else:
|
||||||
|
undo.append(("db_new", target, old))
|
||||||
|
os.replace(tmp, target)
|
||||||
|
|
||||||
|
|
||||||
|
def _swap_dir(target: str, extracted: str, tag: str, undo: list) -> None:
|
||||||
|
"""Replace the CONTENT of a directory (the directory itself may be a volume mount point):
|
||||||
|
old entries move into .restore-old-<tag>, new ones come from .restore-new-<tag>."""
|
||||||
|
os.makedirs(target, mode=0o700, exist_ok=True)
|
||||||
|
staged = os.path.join(target, f".restore-new-{tag}")
|
||||||
|
old = os.path.join(target, f".restore-old-{tag}")
|
||||||
|
if os.path.isdir(extracted):
|
||||||
|
shutil.copytree(extracted, staged)
|
||||||
|
else:
|
||||||
|
os.mkdir(staged, 0o700)
|
||||||
|
os.mkdir(old, 0o700)
|
||||||
|
undo.append(("dir", target, old, staged))
|
||||||
|
for name in os.listdir(target):
|
||||||
|
if not name.startswith(".restore-"):
|
||||||
|
os.replace(os.path.join(target, name), os.path.join(old, name))
|
||||||
|
for name in os.listdir(staged):
|
||||||
|
os.replace(os.path.join(staged, name), os.path.join(target, name))
|
||||||
|
os.rmdir(staged)
|
||||||
|
|
||||||
|
|
||||||
|
def _remove(path: str) -> None:
|
||||||
|
if os.path.isdir(path) and not os.path.islink(path):
|
||||||
|
shutil.rmtree(path, ignore_errors=True)
|
||||||
|
elif os.path.lexists(path):
|
||||||
|
os.remove(path)
|
||||||
|
|
||||||
|
|
||||||
|
def _rollback(undo: list) -> None:
|
||||||
|
for item in reversed(undo):
|
||||||
|
try:
|
||||||
|
if item[0] == "db":
|
||||||
|
_, target, old = item
|
||||||
|
for suffix in ("", "-wal", "-shm"):
|
||||||
|
if os.path.exists(old + suffix):
|
||||||
|
os.replace(old + suffix, target + suffix)
|
||||||
|
elif item[0] == "db_new":
|
||||||
|
_remove(item[1])
|
||||||
|
else:
|
||||||
|
_, target, old, staged = item
|
||||||
|
for name in os.listdir(target):
|
||||||
|
if not name.startswith(".restore-"):
|
||||||
|
_remove(os.path.join(target, name))
|
||||||
|
for name in os.listdir(old):
|
||||||
|
os.replace(os.path.join(old, name), os.path.join(target, name))
|
||||||
|
shutil.rmtree(old, ignore_errors=True)
|
||||||
|
shutil.rmtree(staged, ignore_errors=True)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("[BACKUP] rollback step failed")
|
||||||
|
|
||||||
|
|
||||||
|
def _commit(undo: list) -> None:
|
||||||
|
for item in undo:
|
||||||
|
if item[0] == "db":
|
||||||
|
for suffix in ("", "-wal", "-shm"):
|
||||||
|
if os.path.lexists(item[2] + suffix):
|
||||||
|
_remove(item[2] + suffix)
|
||||||
|
elif item[0] == "dir":
|
||||||
|
shutil.rmtree(item[2], ignore_errors=True)
|
||||||
|
shutil.rmtree(item[3], ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_server_config() -> bool:
|
||||||
|
"""Regenerate server.conf and publish the CRL through the same code as POST /server/configure."""
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from routers import server as server_router
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
server_router.configure_server(db)
|
||||||
|
return True
|
||||||
|
except HTTPException as e:
|
||||||
|
_warn(f"server.conf was not regenerated: {e.detail}")
|
||||||
|
except Exception as e:
|
||||||
|
_warn(f"server.conf was not regenerated: {type(e).__name__}: {str(e)[:200]}")
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _start_openvpn(was_running: bool) -> None:
|
||||||
|
if not was_running:
|
||||||
|
return
|
||||||
|
res = process.control_service("start")
|
||||||
|
if res.get("status") == "error":
|
||||||
|
_warn(f"OpenVPN was running before the restore, but could not be started: {res.get('message')}")
|
||||||
|
|
||||||
|
|
||||||
|
def _restore_worker(rec: dict, name: str, encrypted: bool, passphrase: Optional[str], hist_id: int) -> None:
|
||||||
|
work = None
|
||||||
|
undo = []
|
||||||
|
was_running = False
|
||||||
|
stopped = False
|
||||||
|
committed = False
|
||||||
|
try:
|
||||||
|
work = _work_dir()
|
||||||
|
downloaded = os.path.join(work, "downloaded")
|
||||||
|
_stage("download")
|
||||||
|
build_dest(rec).get(name, downloaded)
|
||||||
|
|
||||||
|
archive = downloaded
|
||||||
|
if encrypted:
|
||||||
|
_stage("decrypt")
|
||||||
|
archive = os.path.join(work, "package.tar.gz")
|
||||||
|
crypto.decrypt_file(downloaded, archive, passphrase)
|
||||||
|
os.remove(downloaded)
|
||||||
|
elif crypto.is_encrypted(downloaded):
|
||||||
|
raise BackupError("The package is encrypted but its name says it is not")
|
||||||
|
|
||||||
|
_stage("verify")
|
||||||
|
extracted = os.path.join(work, "extracted")
|
||||||
|
manifest = package.safe_extract(archive, extracted)
|
||||||
|
os.remove(archive)
|
||||||
|
|
||||||
|
_stage("prepare")
|
||||||
|
_prepare_staged(extracted, manifest)
|
||||||
|
|
||||||
|
_stage("safety_backup")
|
||||||
|
safety = _safety_backup()
|
||||||
|
|
||||||
|
_stage("stop_openvpn")
|
||||||
|
was_running = process.get_process_stats().get("status") == "running"
|
||||||
|
if was_running:
|
||||||
|
res = process.control_service("stop")
|
||||||
|
if res.get("status") == "error":
|
||||||
|
raise BackupError(f"Cannot stop OpenVPN: {res.get('message')}")
|
||||||
|
stopped = True
|
||||||
|
|
||||||
|
_stage("replace")
|
||||||
|
tag = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
|
||||||
|
try:
|
||||||
|
sa_engine.dispose()
|
||||||
|
_swap_dir(pki_dir(), os.path.join(extracted, "pki"), tag, undo)
|
||||||
|
_swap_dir(client_dir(), os.path.join(extracted, "client-config"), tag, undo)
|
||||||
|
_replace_db(monitor_db_path(), os.path.join(extracted, package.DB_MONITOR), tag, undo)
|
||||||
|
_replace_db(profiler_db_path(), os.path.join(extracted, package.DB_PROFILER), tag, undo)
|
||||||
|
marker = pki._marker_path()
|
||||||
|
if os.path.exists(marker):
|
||||||
|
os.remove(marker)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("[BACKUP] replacement failed, rolling back")
|
||||||
|
_rollback(undo)
|
||||||
|
sa_engine.dispose()
|
||||||
|
raise
|
||||||
|
_commit(undo)
|
||||||
|
committed = True
|
||||||
|
sa_engine.dispose()
|
||||||
|
|
||||||
|
_stage("finalize")
|
||||||
|
configured = _apply_server_config()
|
||||||
|
if configured:
|
||||||
|
_start_openvpn(was_running)
|
||||||
|
elif was_running:
|
||||||
|
_warn("OpenVPN was running before the restore and was not started")
|
||||||
|
message = f"Restored from {name}. The previous state is saved as {PRE_RESTORE_FOLDER}/{safety}"
|
||||||
|
_result(0, state="ok", message=message)
|
||||||
|
_finish("done", message, relogin=True)
|
||||||
|
store.history_finish(hist_id, "done", message, status()["results"])
|
||||||
|
except Exception as e:
|
||||||
|
logger.exception("Restore failed")
|
||||||
|
message = str(e)[:500] if isinstance(e, BackupError) else f"Restore failed: {type(e).__name__}: {str(e)[:300]}"
|
||||||
|
if committed:
|
||||||
|
message += ". The data was restored, but the final steps failed (see the log)."
|
||||||
|
else:
|
||||||
|
message += ". Nothing was changed." if not undo else ". The previous state was put back."
|
||||||
|
if stopped:
|
||||||
|
try:
|
||||||
|
_start_openvpn(True)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("[BACKUP] OpenVPN start after a failed restore")
|
||||||
|
_result(0, state="error", message=message)
|
||||||
|
_finish("error", message)
|
||||||
|
store.history_finish(hist_id, "error", message, status()["results"])
|
||||||
|
finally:
|
||||||
|
pki.set_restore_running(False)
|
||||||
|
if work:
|
||||||
|
shutil.rmtree(work, ignore_errors=True)
|
||||||
@@ -0,0 +1,335 @@
|
|||||||
|
"""Backup package: naming, building (snapshots), reading and safe extraction.
|
||||||
|
|
||||||
|
A package is a tar.gz named ovpmon-backup_<server-name>_<YYYYMMDDTHHMMSS>Z.ovpbak (plus .enc when
|
||||||
|
encrypted; -2, -3 after the Z when several packages are made in the same second) with this content:
|
||||||
|
db/openvpn_monitor.db, db/ovpn_profiler.db consistent online snapshots (sqlite3 backup API)
|
||||||
|
pki/... the easy-rsa PKI directory
|
||||||
|
client-config/*.ovpn issued client profiles
|
||||||
|
manifest.json format version, server name, schema versions, SHA-256 of every file
|
||||||
|
"""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import socket
|
||||||
|
import sqlite3
|
||||||
|
import stat
|
||||||
|
import tarfile
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from . import BackupError
|
||||||
|
|
||||||
|
FORMAT_NAME = "ovpmon-backup"
|
||||||
|
FORMAT_VERSION = 1
|
||||||
|
MANIFEST = "manifest.json"
|
||||||
|
DB_MONITOR = "db/openvpn_monitor.db"
|
||||||
|
DB_PROFILER = "db/ovpn_profiler.db"
|
||||||
|
TOP_LEVEL = {"db", "pki", "client-config", MANIFEST} # allowlist of top-level names
|
||||||
|
|
||||||
|
SERVER_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9.-]{0,62}$")
|
||||||
|
# Packages of the first pass carry the host name in the same place; they match too
|
||||||
|
PACKAGE_RE = re.compile(
|
||||||
|
r"^ovpmon-backup_(?P<host>[A-Za-z0-9][A-Za-z0-9.-]{0,62})_(?P<ts>\d{8}T\d{6}Z)(?:-(?P<seq>\d{1,3}))?"
|
||||||
|
r"\.ovpbak(?P<enc>\.enc)?$")
|
||||||
|
|
||||||
|
MAX_FILES = 200000
|
||||||
|
MAX_UNPACKED = int(os.environ.get("OVPMON_BACKUP_MAX_UNPACKED_BYTES", str(20 * 1024 ** 3)))
|
||||||
|
MAX_MANIFEST = 64 * 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
|
def sanitize_name(text: str) -> str:
|
||||||
|
"""Make a server name of arbitrary text (host name, address); empty when nothing is left."""
|
||||||
|
name = re.sub(r"[^A-Za-z0-9.-]", "-", text or "")[:63].strip("-.")
|
||||||
|
return name if SERVER_NAME_RE.match(name) else ""
|
||||||
|
|
||||||
|
|
||||||
|
def host_name() -> str:
|
||||||
|
return sanitize_name(socket.gethostname()) or "host"
|
||||||
|
|
||||||
|
|
||||||
|
def utc_stamp(now=None) -> str:
|
||||||
|
return (now or datetime.now(timezone.utc)).strftime("%Y%m%dT%H%M%SZ")
|
||||||
|
|
||||||
|
|
||||||
|
def package_name(server: str, stamp: str, encrypted: bool, seq: int = 1) -> str:
|
||||||
|
return (f"ovpmon-backup_{server}_{stamp}" + (f"-{seq}" if seq > 1 else "")
|
||||||
|
+ ".ovpbak" + (".enc" if encrypted else ""))
|
||||||
|
|
||||||
|
|
||||||
|
def unique_package_name(server: str, stamp: str, encrypted: bool, existing) -> str:
|
||||||
|
"""The name for a new package: the plain one, or with -2, -3 ... when the destination already
|
||||||
|
holds a package of the same second. An existing file is never overwritten."""
|
||||||
|
taken = set(existing)
|
||||||
|
for seq in range(1, 1000):
|
||||||
|
name = package_name(server, stamp, encrypted, seq)
|
||||||
|
if name not in taken:
|
||||||
|
return name
|
||||||
|
raise BackupError("Too many packages with the same time stamp in the destination")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_package_name(name: str):
|
||||||
|
"""{'host' (server name),'created_at' (ISO UTC),'encrypted','stamp','seq'} or None when the name is not ours."""
|
||||||
|
m = PACKAGE_RE.match(name or "")
|
||||||
|
if not m:
|
||||||
|
return None
|
||||||
|
ts = datetime.strptime(m.group("ts"), "%Y%m%dT%H%M%SZ").replace(tzinfo=timezone.utc)
|
||||||
|
return {"host": m.group("host"), "created_at": ts.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||||
|
"encrypted": bool(m.group("enc")), "stamp": m.group("ts"), "seq": int(m.group("seq") or 1)}
|
||||||
|
|
||||||
|
|
||||||
|
# --- SQLite helpers ------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def schema_version(db_path: str):
|
||||||
|
"""Highest applied migration of a database (0: no migrations table), None if unreadable."""
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=30)
|
||||||
|
try:
|
||||||
|
has = conn.execute(
|
||||||
|
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='schema_migrations'").fetchone()
|
||||||
|
if not has:
|
||||||
|
return 0
|
||||||
|
return conn.execute("SELECT COALESCE(MAX(version), 0) FROM schema_migrations").fetchone()[0]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
except sqlite3.Error:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def integrity_ok(db_path: str) -> bool:
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=30)
|
||||||
|
try:
|
||||||
|
return [r[0] for r in conn.execute("PRAGMA integrity_check")] == ["ok"]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
except sqlite3.Error:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def snapshot_db(src_path: str, dst_path: str) -> None:
|
||||||
|
"""Consistent copy of a live database (online backup API); the copy is a single file
|
||||||
|
(journal mode DELETE), so no -wal/-shm files belong to it."""
|
||||||
|
if not os.path.isfile(src_path):
|
||||||
|
raise BackupError(f"Database not found: {os.path.basename(src_path)}")
|
||||||
|
src = sqlite3.connect(f"file:{src_path}?mode=ro", uri=True, timeout=60)
|
||||||
|
dst = sqlite3.connect(dst_path)
|
||||||
|
try:
|
||||||
|
src.backup(dst)
|
||||||
|
dst.execute("PRAGMA journal_mode=DELETE")
|
||||||
|
dst.commit()
|
||||||
|
except sqlite3.Error as e:
|
||||||
|
raise BackupError(f"Cannot snapshot {os.path.basename(src_path)}: {e}") from e
|
||||||
|
finally:
|
||||||
|
src.close()
|
||||||
|
dst.close()
|
||||||
|
os.chmod(dst_path, 0o600)
|
||||||
|
|
||||||
|
|
||||||
|
# --- building ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _copy_tree_regular(src: str, dst: str) -> int:
|
||||||
|
"""Copy regular files and directories only (links and special files are skipped). Returns file count."""
|
||||||
|
count = 0
|
||||||
|
os.makedirs(dst, mode=0o700, exist_ok=True)
|
||||||
|
for root, dirs, files in os.walk(src, followlinks=False):
|
||||||
|
rel = os.path.relpath(root, src)
|
||||||
|
target = dst if rel == "." else os.path.join(dst, rel)
|
||||||
|
os.makedirs(target, mode=0o700, exist_ok=True)
|
||||||
|
dirs[:] = [d for d in dirs if not os.path.islink(os.path.join(root, d))]
|
||||||
|
for name in files:
|
||||||
|
path = os.path.join(root, name)
|
||||||
|
st = os.lstat(path)
|
||||||
|
if not stat.S_ISREG(st.st_mode):
|
||||||
|
continue
|
||||||
|
out = os.path.join(target, name)
|
||||||
|
shutil.copyfile(path, out)
|
||||||
|
os.chmod(out, stat.S_IMODE(st.st_mode) & 0o777)
|
||||||
|
count += 1
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
def _sha256(path: str) -> str:
|
||||||
|
h = hashlib.sha256()
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
for block in iter(lambda: f.read(1024 * 1024), b""):
|
||||||
|
h.update(block)
|
||||||
|
return h.hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def build_package(out_path: str, work_dir: str, profiler_db: str, monitor_db: str,
|
||||||
|
pki_dir: str, client_dir: str, runtime: str, server_name: str = "") -> dict:
|
||||||
|
"""Write the (not encrypted) package tar.gz to out_path. Returns the manifest."""
|
||||||
|
stage = os.path.join(work_dir, "stage")
|
||||||
|
os.makedirs(os.path.join(stage, "db"), mode=0o700)
|
||||||
|
snapshot_db(profiler_db, os.path.join(stage, DB_PROFILER))
|
||||||
|
snapshot_db(monitor_db, os.path.join(stage, DB_MONITOR))
|
||||||
|
if os.path.isdir(pki_dir):
|
||||||
|
_copy_tree_regular(pki_dir, os.path.join(stage, "pki"))
|
||||||
|
else:
|
||||||
|
os.makedirs(os.path.join(stage, "pki"), mode=0o700)
|
||||||
|
if os.path.isdir(client_dir):
|
||||||
|
for name in sorted(os.listdir(client_dir)):
|
||||||
|
path = os.path.join(client_dir, name)
|
||||||
|
if name.endswith(".ovpn") and os.path.isfile(path) and not os.path.islink(path):
|
||||||
|
os.makedirs(os.path.join(stage, "client-config"), mode=0o700, exist_ok=True)
|
||||||
|
shutil.copyfile(path, os.path.join(stage, "client-config", name))
|
||||||
|
os.makedirs(os.path.join(stage, "client-config"), mode=0o700, exist_ok=True)
|
||||||
|
|
||||||
|
files = {}
|
||||||
|
for root, _dirs, names in os.walk(stage):
|
||||||
|
for name in names:
|
||||||
|
path = os.path.join(root, name)
|
||||||
|
arc = os.path.relpath(path, stage).replace(os.sep, "/")
|
||||||
|
files[arc] = {"sha256": _sha256(path), "size": os.path.getsize(path),
|
||||||
|
"mode": stat.S_IMODE(os.stat(path).st_mode) & 0o777}
|
||||||
|
profiles = 0
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(os.path.join(stage, DB_PROFILER))
|
||||||
|
try:
|
||||||
|
profiles = conn.execute("SELECT COUNT(*) FROM user_profiles").fetchone()[0]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
except sqlite3.Error:
|
||||||
|
pass
|
||||||
|
manifest = {
|
||||||
|
"format": FORMAT_NAME,
|
||||||
|
"format_version": FORMAT_VERSION,
|
||||||
|
"created_at": datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
|
||||||
|
"server_name": server_name or host_name(),
|
||||||
|
"hostname": socket.gethostname(),
|
||||||
|
"runtime": runtime,
|
||||||
|
"schema": {"profiler": schema_version(os.path.join(stage, DB_PROFILER)),
|
||||||
|
"monitor": schema_version(os.path.join(stage, DB_MONITOR))},
|
||||||
|
"profiles": profiles,
|
||||||
|
"files": files,
|
||||||
|
}
|
||||||
|
manifest_path = os.path.join(stage, MANIFEST)
|
||||||
|
with open(manifest_path, "w") as f:
|
||||||
|
json.dump(manifest, f, indent=1, sort_keys=True)
|
||||||
|
|
||||||
|
fd = os.open(out_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as raw, tarfile.open(fileobj=raw, mode="w:gz") as tar:
|
||||||
|
# Directories first (so empty ones survive), then files; fixed owner, no time-dependent names
|
||||||
|
entries = []
|
||||||
|
for root, dirs, names in os.walk(stage):
|
||||||
|
for name in dirs + names:
|
||||||
|
path = os.path.join(root, name)
|
||||||
|
entries.append((os.path.relpath(path, stage).replace(os.sep, "/"), path))
|
||||||
|
for arc, path in sorted(entries):
|
||||||
|
info = tar.gettarinfo(path, arcname=arc)
|
||||||
|
info.uid = info.gid = 0
|
||||||
|
info.uname = info.gname = ""
|
||||||
|
if info.isdir():
|
||||||
|
tar.addfile(info)
|
||||||
|
else:
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
tar.addfile(info, f)
|
||||||
|
shutil.rmtree(stage, ignore_errors=True)
|
||||||
|
return manifest
|
||||||
|
|
||||||
|
|
||||||
|
# --- reading and safe extraction -----------------------------------------------------------
|
||||||
|
|
||||||
|
def _check_member_name(name: str):
|
||||||
|
if not name or name.startswith("/") or "\\" in name or "\x00" in name:
|
||||||
|
raise BackupError(f"Unsafe path in package: {name!r}")
|
||||||
|
parts = name.split("/")
|
||||||
|
if any(p in ("", ".", "..") for p in parts):
|
||||||
|
raise BackupError(f"Unsafe path in package: {name!r}")
|
||||||
|
if parts[0] not in TOP_LEVEL:
|
||||||
|
raise BackupError(f"Unexpected entry in package: {name!r}")
|
||||||
|
if parts[0] == MANIFEST and len(parts) != 1:
|
||||||
|
raise BackupError(f"Unexpected entry in package: {name!r}")
|
||||||
|
if parts[0] == "db" and name not in ("db", DB_MONITOR, DB_PROFILER):
|
||||||
|
raise BackupError(f"Unexpected entry in package: {name!r}")
|
||||||
|
if parts[0] == "client-config" and len(parts) > 2:
|
||||||
|
raise BackupError(f"Unexpected entry in package: {name!r}")
|
||||||
|
if parts[0] == "client-config" and len(parts) == 2 and not parts[1].endswith(".ovpn"):
|
||||||
|
raise BackupError(f"Unexpected entry in package: {name!r}")
|
||||||
|
|
||||||
|
|
||||||
|
def safe_extract(package_path: str, dest: str) -> dict:
|
||||||
|
"""Extract an unencrypted package into the empty directory dest, checking every entry.
|
||||||
|
Only regular files and directories under the allowlisted names are accepted: absolute paths,
|
||||||
|
'..', links, devices and oversized content are rejected. Returns the verified manifest."""
|
||||||
|
os.makedirs(dest, mode=0o700, exist_ok=True)
|
||||||
|
base = os.path.realpath(dest)
|
||||||
|
total, count = 0, 0
|
||||||
|
try:
|
||||||
|
tar = tarfile.open(package_path, mode="r:gz")
|
||||||
|
except (tarfile.TarError, OSError, EOFError) as e:
|
||||||
|
raise BackupError(f"Cannot read the package: {e}") from e
|
||||||
|
try:
|
||||||
|
for member in tar:
|
||||||
|
count += 1
|
||||||
|
if count > MAX_FILES:
|
||||||
|
raise BackupError("Package has too many entries")
|
||||||
|
name = member.name.rstrip("/") if member.isdir() else member.name
|
||||||
|
_check_member_name(name)
|
||||||
|
if not (member.isreg() or member.isdir()):
|
||||||
|
raise BackupError(f"Package contains a link or special file: {name!r}")
|
||||||
|
target = os.path.realpath(os.path.join(base, name))
|
||||||
|
if target != base and not target.startswith(base + os.sep):
|
||||||
|
raise BackupError(f"Unsafe path in package: {name!r}")
|
||||||
|
if member.isdir():
|
||||||
|
os.makedirs(target, mode=0o700, exist_ok=True)
|
||||||
|
continue
|
||||||
|
if member.size < 0 or total + member.size > MAX_UNPACKED:
|
||||||
|
raise BackupError("Package is larger than the allowed unpacked size")
|
||||||
|
if name == MANIFEST and member.size > MAX_MANIFEST:
|
||||||
|
raise BackupError("Manifest is too large")
|
||||||
|
total += member.size
|
||||||
|
os.makedirs(os.path.dirname(target), mode=0o700, exist_ok=True)
|
||||||
|
src = tar.extractfile(member)
|
||||||
|
fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as out:
|
||||||
|
shutil.copyfileobj(src, out)
|
||||||
|
os.chmod(target, member.mode & 0o777 & ~0o7000)
|
||||||
|
except (tarfile.TarError, OSError, EOFError) as e:
|
||||||
|
if isinstance(e, FileExistsError):
|
||||||
|
raise BackupError("Package contains duplicate entries") from e
|
||||||
|
raise BackupError(f"Package is damaged or cannot be unpacked: {e}") from e
|
||||||
|
finally:
|
||||||
|
tar.close()
|
||||||
|
return verify_extracted(dest)
|
||||||
|
|
||||||
|
|
||||||
|
def verify_extracted(dest: str) -> dict:
|
||||||
|
"""Read manifest.json and check that the extracted files are exactly the listed ones with the
|
||||||
|
listed sizes and SHA-256 sums. Returns the manifest."""
|
||||||
|
path = os.path.join(dest, MANIFEST)
|
||||||
|
if not os.path.isfile(path):
|
||||||
|
raise BackupError("Package has no manifest.json")
|
||||||
|
try:
|
||||||
|
with open(path) as f:
|
||||||
|
manifest = json.load(f)
|
||||||
|
files = manifest["files"]
|
||||||
|
fmt, version = manifest["format"], manifest["format_version"]
|
||||||
|
manifest["schema"]["profiler"], manifest["schema"]["monitor"]
|
||||||
|
except (ValueError, KeyError, TypeError) as e:
|
||||||
|
raise BackupError("Package manifest is invalid") from e
|
||||||
|
if fmt != FORMAT_NAME or not isinstance(version, int) or version > FORMAT_VERSION or version < 1:
|
||||||
|
raise BackupError(f"Unknown package format (format_version {version!r}); "
|
||||||
|
f"this release reads format {FORMAT_VERSION}")
|
||||||
|
if not isinstance(files, dict):
|
||||||
|
raise BackupError("Package manifest is invalid")
|
||||||
|
present = set()
|
||||||
|
for root, _dirs, names in os.walk(dest):
|
||||||
|
for name in names:
|
||||||
|
rel = os.path.relpath(os.path.join(root, name), dest).replace(os.sep, "/")
|
||||||
|
if rel != MANIFEST:
|
||||||
|
present.add(rel)
|
||||||
|
if present != set(files):
|
||||||
|
extra, missing = sorted(present - set(files)), sorted(set(files) - present)
|
||||||
|
raise BackupError("Package content does not match the manifest"
|
||||||
|
+ (f" (not listed: {extra[0]})" if extra else "")
|
||||||
|
+ (f" (missing: {missing[0]})" if missing else ""))
|
||||||
|
for rel, meta in files.items():
|
||||||
|
full = os.path.join(dest, rel)
|
||||||
|
if os.path.getsize(full) != meta.get("size") or _sha256(full) != meta.get("sha256"):
|
||||||
|
raise BackupError(f"Checksum mismatch: {rel}. The package is damaged")
|
||||||
|
for required in (DB_PROFILER, DB_MONITOR):
|
||||||
|
if required not in files:
|
||||||
|
raise BackupError(f"Package has no {required}")
|
||||||
|
return manifest
|
||||||
@@ -0,0 +1,252 @@
|
|||||||
|
"""Settings, destinations and history of the backup feature.
|
||||||
|
|
||||||
|
A separate SQLite file (ovpmon_backup.db) next to the profiler database. A restore replaces
|
||||||
|
ovpn_profiler.db and openvpn_monitor.db, but never this file, so the destinations survive it and
|
||||||
|
never travel inside a package. The schema is created at service start (own version table, the
|
||||||
|
migrations of the two application databases are not involved).
|
||||||
|
|
||||||
|
Secrets (destination keys, the package passphrase) are encrypted at rest with a key derived
|
||||||
|
(HKDF-SHA256) from the JWT signing key. They are never returned by the API and never logged.
|
||||||
|
If the JWT key changes they cannot be decrypted any more and have to be entered again.
|
||||||
|
"""
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import threading
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from cryptography.fernet import Fernet, InvalidToken
|
||||||
|
from cryptography.hazmat.primitives import hashes
|
||||||
|
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
||||||
|
|
||||||
|
from . import BackupError
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
SCHEMA_VERSION = 1
|
||||||
|
DEFAULT_RETENTION = 14
|
||||||
|
HISTORY_KEEP = 100
|
||||||
|
MASK = "********"
|
||||||
|
|
||||||
|
_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def db_file() -> str:
|
||||||
|
from database import db_path
|
||||||
|
return os.path.join(os.path.dirname(os.path.abspath(db_path)), "ovpmon_backup.db")
|
||||||
|
|
||||||
|
|
||||||
|
def _now() -> str:
|
||||||
|
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _conn():
|
||||||
|
conn = sqlite3.connect(db_file(), timeout=30)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
try:
|
||||||
|
yield conn
|
||||||
|
conn.commit()
|
||||||
|
except BaseException:
|
||||||
|
conn.rollback()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def init() -> None:
|
||||||
|
"""Create the schema (idempotent). Called at service start."""
|
||||||
|
path = db_file()
|
||||||
|
new = not os.path.exists(path)
|
||||||
|
with _lock, _conn() as c:
|
||||||
|
c.execute("CREATE TABLE IF NOT EXISTS backup_schema (version INTEGER NOT NULL)")
|
||||||
|
c.execute("CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT)")
|
||||||
|
c.execute("""CREATE TABLE IF NOT EXISTS destinations (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL UNIQUE,
|
||||||
|
type TEXT NOT NULL,
|
||||||
|
enabled INTEGER NOT NULL DEFAULT 1,
|
||||||
|
retention_count INTEGER NOT NULL DEFAULT 14,
|
||||||
|
params TEXT NOT NULL DEFAULT '{}',
|
||||||
|
secrets_enc TEXT NOT NULL DEFAULT '',
|
||||||
|
last_status TEXT,
|
||||||
|
last_message TEXT,
|
||||||
|
last_at TEXT,
|
||||||
|
created_at TEXT NOT NULL)""")
|
||||||
|
c.execute("""CREATE TABLE IF NOT EXISTS history (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
kind TEXT NOT NULL,
|
||||||
|
state TEXT NOT NULL,
|
||||||
|
started_at TEXT NOT NULL,
|
||||||
|
finished_at TEXT,
|
||||||
|
message TEXT,
|
||||||
|
results TEXT NOT NULL DEFAULT '[]')""")
|
||||||
|
if not c.execute("SELECT 1 FROM backup_schema").fetchone():
|
||||||
|
c.execute("INSERT INTO backup_schema (version) VALUES (?)", (SCHEMA_VERSION,))
|
||||||
|
# A job that was running when the service stopped did not finish
|
||||||
|
c.execute("UPDATE history SET state='interrupted', finished_at=? WHERE state='running'", (_now(),))
|
||||||
|
if new:
|
||||||
|
os.chmod(path, 0o600)
|
||||||
|
|
||||||
|
|
||||||
|
# --- secrets -------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _fernet() -> Fernet:
|
||||||
|
from utils.auth import SECRET_KEY
|
||||||
|
key = HKDF(algorithm=hashes.SHA256(), length=32, salt=None,
|
||||||
|
info=b"ovpmon-backup-secrets-v1").derive(SECRET_KEY.encode("utf-8"))
|
||||||
|
return Fernet(base64.urlsafe_b64encode(key))
|
||||||
|
|
||||||
|
|
||||||
|
def encrypt_text(text: str) -> str:
|
||||||
|
return _fernet().encrypt(text.encode("utf-8")).decode("ascii")
|
||||||
|
|
||||||
|
|
||||||
|
def decrypt_text(token: str) -> str:
|
||||||
|
try:
|
||||||
|
return _fernet().decrypt(token.encode("ascii")).decode("utf-8")
|
||||||
|
except (InvalidToken, ValueError):
|
||||||
|
raise BackupError("Stored secrets cannot be decrypted (the JWT secret changed). "
|
||||||
|
"Enter them again.") from None
|
||||||
|
|
||||||
|
|
||||||
|
# --- settings ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _get_setting(key):
|
||||||
|
with _conn() as c:
|
||||||
|
row = c.execute("SELECT value FROM settings WHERE key=?", (key,)).fetchone()
|
||||||
|
return row["value"] if row else None
|
||||||
|
|
||||||
|
|
||||||
|
def _set_setting(key, value):
|
||||||
|
with _lock, _conn() as c:
|
||||||
|
if value is None:
|
||||||
|
c.execute("DELETE FROM settings WHERE key=?", (key,))
|
||||||
|
else:
|
||||||
|
c.execute("INSERT INTO settings (key, value) VALUES (?, ?) "
|
||||||
|
"ON CONFLICT(key) DO UPDATE SET value=excluded.value", (key, value))
|
||||||
|
|
||||||
|
|
||||||
|
def has_passphrase() -> bool:
|
||||||
|
return bool(_get_setting("passphrase_enc"))
|
||||||
|
|
||||||
|
|
||||||
|
def get_passphrase():
|
||||||
|
"""The package passphrase, or None when none is set. Raises BackupError if it cannot be decrypted."""
|
||||||
|
token = _get_setting("passphrase_enc")
|
||||||
|
return decrypt_text(token) if token else None
|
||||||
|
|
||||||
|
|
||||||
|
def set_passphrase(value) -> None:
|
||||||
|
_set_setting("passphrase_enc", encrypt_text(value) if value else None)
|
||||||
|
|
||||||
|
|
||||||
|
def default_retention() -> int:
|
||||||
|
try:
|
||||||
|
return int(_get_setting("default_retention") or DEFAULT_RETENTION)
|
||||||
|
except ValueError:
|
||||||
|
return DEFAULT_RETENTION
|
||||||
|
|
||||||
|
|
||||||
|
def set_default_retention(n: int) -> None:
|
||||||
|
_set_setting("default_retention", str(int(n)))
|
||||||
|
|
||||||
|
|
||||||
|
def get_server_name() -> str:
|
||||||
|
"""The server name set by the administrator ('' when none). Lives here, not in the profiler
|
||||||
|
database: a restore replaces that one, and the name belongs to this server."""
|
||||||
|
return _get_setting("server_name") or ""
|
||||||
|
|
||||||
|
|
||||||
|
def set_server_name(value) -> None:
|
||||||
|
_set_setting("server_name", value or None)
|
||||||
|
|
||||||
|
|
||||||
|
# --- destinations --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _row_to_dest(row, with_secrets=False):
|
||||||
|
d = {"id": row["id"], "name": row["name"], "type": row["type"], "enabled": bool(row["enabled"]),
|
||||||
|
"retention_count": row["retention_count"], "params": json.loads(row["params"]),
|
||||||
|
"last_status": row["last_status"], "last_message": row["last_message"], "last_at": row["last_at"]}
|
||||||
|
secrets, secrets_ok = {}, True
|
||||||
|
if row["secrets_enc"]:
|
||||||
|
try:
|
||||||
|
secrets = json.loads(decrypt_text(row["secrets_enc"]))
|
||||||
|
except BackupError:
|
||||||
|
secrets_ok = False
|
||||||
|
d["secrets_ok"] = secrets_ok
|
||||||
|
if with_secrets:
|
||||||
|
d["secrets"] = secrets
|
||||||
|
else:
|
||||||
|
# Masked: the UI only learns which secrets are set
|
||||||
|
d["secrets"] = {k: MASK for k, v in secrets.items() if v}
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def list_destinations(with_secrets=False):
|
||||||
|
with _conn() as c:
|
||||||
|
rows = c.execute("SELECT * FROM destinations ORDER BY id").fetchall()
|
||||||
|
return [_row_to_dest(r, with_secrets) for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def get_destination(dest_id: int, with_secrets=False):
|
||||||
|
with _conn() as c:
|
||||||
|
row = c.execute("SELECT * FROM destinations WHERE id=?", (dest_id,)).fetchone()
|
||||||
|
return _row_to_dest(row, with_secrets) if row else None
|
||||||
|
|
||||||
|
|
||||||
|
def save_destination(dest_id, name, dtype, enabled, retention_count, params, secrets) -> int:
|
||||||
|
"""Insert (dest_id None) or update. Raises BackupError on a duplicate name."""
|
||||||
|
enc = encrypt_text(json.dumps(secrets)) if secrets else ""
|
||||||
|
try:
|
||||||
|
with _lock, _conn() as c:
|
||||||
|
if dest_id is None:
|
||||||
|
cur = c.execute(
|
||||||
|
"INSERT INTO destinations (name, type, enabled, retention_count, params, secrets_enc, created_at) "
|
||||||
|
"VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
(name, dtype, int(enabled), retention_count, json.dumps(params), enc, _now()))
|
||||||
|
return cur.lastrowid
|
||||||
|
c.execute("UPDATE destinations SET name=?, type=?, enabled=?, retention_count=?, params=?, "
|
||||||
|
"secrets_enc=? WHERE id=?",
|
||||||
|
(name, dtype, int(enabled), retention_count, json.dumps(params), enc, dest_id))
|
||||||
|
return dest_id
|
||||||
|
except sqlite3.IntegrityError:
|
||||||
|
raise BackupError(f"A destination named '{name}' already exists") from None
|
||||||
|
|
||||||
|
|
||||||
|
def delete_destination(dest_id: int) -> bool:
|
||||||
|
with _lock, _conn() as c:
|
||||||
|
return c.execute("DELETE FROM destinations WHERE id=?", (dest_id,)).rowcount > 0
|
||||||
|
|
||||||
|
|
||||||
|
def set_last_result(dest_id: int, ok: bool, message: str) -> None:
|
||||||
|
with _lock, _conn() as c:
|
||||||
|
c.execute("UPDATE destinations SET last_status=?, last_message=?, last_at=? WHERE id=?",
|
||||||
|
("ok" if ok else "error", (message or "")[:500], _now(), dest_id))
|
||||||
|
|
||||||
|
|
||||||
|
# --- history -------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def history_start(kind: str) -> int:
|
||||||
|
with _lock, _conn() as c:
|
||||||
|
return c.execute("INSERT INTO history (kind, state, started_at) VALUES (?, 'running', ?)",
|
||||||
|
(kind, _now())).lastrowid
|
||||||
|
|
||||||
|
|
||||||
|
def history_finish(hist_id: int, state: str, message: str, results: list) -> None:
|
||||||
|
with _lock, _conn() as c:
|
||||||
|
c.execute("UPDATE history SET state=?, finished_at=?, message=?, results=? WHERE id=?",
|
||||||
|
(state, _now(), (message or "")[:1000], json.dumps(results), hist_id))
|
||||||
|
c.execute("DELETE FROM history WHERE id NOT IN (SELECT id FROM history ORDER BY id DESC LIMIT ?)",
|
||||||
|
(HISTORY_KEEP,))
|
||||||
|
|
||||||
|
|
||||||
|
def history_list(limit: int = 20) -> list:
|
||||||
|
with _conn() as c:
|
||||||
|
rows = c.execute("SELECT * FROM history ORDER BY id DESC LIMIT ?", (limit,)).fetchall()
|
||||||
|
return [{"id": r["id"], "kind": r["kind"], "state": r["state"], "started_at": r["started_at"],
|
||||||
|
"finished_at": r["finished_at"], "message": r["message"], "results": json.loads(r["results"])}
|
||||||
|
for r in rows]
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
import os
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
import logging
|
import logging
|
||||||
from .config import get_pki_settings
|
import shutil
|
||||||
|
import threading
|
||||||
|
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
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -120,37 +123,160 @@ def _get_easyrsa_env(db: Session):
|
|||||||
}
|
}
|
||||||
return env
|
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"
|
||||||
|
|
||||||
|
# A backup restore replaces the PKI, the profile files and the databases: while it runs,
|
||||||
|
# everything that changes them is refused (set by services/backup/engine.py)
|
||||||
|
_restore_running = False
|
||||||
|
|
||||||
|
def set_restore_running(value: bool):
|
||||||
|
global _restore_running
|
||||||
|
_restore_running = bool(value)
|
||||||
|
|
||||||
|
def is_restore_running() -> bool:
|
||||||
|
return _restore_running
|
||||||
|
|
||||||
|
RESTORE_RUNNING_MSG = "A backup restore is running"
|
||||||
|
|
||||||
|
class PkiNotReady(Exception):
|
||||||
|
"""An operation needs keys that are not there (PKI absent, init running or server files missing)."""
|
||||||
|
|
||||||
|
NOT_INITIALIZED_MSG = "PKI is not initialized. Initialize PKI first."
|
||||||
|
|
||||||
|
def server_files_missing(db: Session) -> list:
|
||||||
|
"""Names (relative to PKI_DIR) of the files server.conf points to that do not exist.
|
||||||
|
Checks the real files: a changed fqdn_server leaves the old certificate behind."""
|
||||||
|
fqdn = get_pki_settings(db).fqdn_server
|
||||||
|
files = ["ca.crt", f"issued/{fqdn}.crt", f"private/{fqdn}.key", "dh.pem", "ta.key"]
|
||||||
|
if get_system_settings(db).crl_verify:
|
||||||
|
files.append("crl.pem")
|
||||||
|
return [f for f in files if not os.path.isfile(os.path.join(PKI_DIR, f))]
|
||||||
|
|
||||||
|
def require_pki_ready():
|
||||||
|
"""CA operations (client certificates): initialized PKI and no init job running."""
|
||||||
|
if is_init_running() or not is_initialized():
|
||||||
|
raise PkiNotReady(NOT_INITIALIZED_MSG)
|
||||||
|
|
||||||
|
def require_server_ready(db: Session):
|
||||||
|
"""Server operations (configure, start, restart): CA plus every file server.conf references."""
|
||||||
|
require_pki_ready()
|
||||||
|
missing = server_files_missing(db)
|
||||||
|
if missing:
|
||||||
|
raise PkiNotReady(f"PKI server files are missing: {', '.join(missing)}")
|
||||||
|
|
||||||
|
def init_status(db: Session) -> dict:
|
||||||
|
with _init_lock:
|
||||||
|
job = dict(_init_job)
|
||||||
|
job["initialized"] = is_initialized()
|
||||||
|
missing = server_files_missing(db)
|
||||||
|
running = job["state"] == "running"
|
||||||
|
job["missing"] = missing
|
||||||
|
job["pki_ready"] = job["initialized"] and not running
|
||||||
|
job["server_ready"] = job["pki_ready"] and not missing
|
||||||
|
return job
|
||||||
|
|
||||||
|
def _set_step(step: str):
|
||||||
|
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)
|
env = _get_easyrsa_env(db)
|
||||||
pki_settings = get_pki_settings(db)
|
pki_settings = get_pki_settings(db)
|
||||||
|
step = on_step or (lambda name: None)
|
||||||
|
|
||||||
if os.path.exists(os.path.join(PKI_DIR, "ca.crt")):
|
if is_initialized():
|
||||||
logger.warning("PKI already initialized")
|
logger.warning("PKI already initialized")
|
||||||
return "PKI already initialized"
|
return "PKI already initialized"
|
||||||
|
|
||||||
# Init PKI
|
# Init PKI
|
||||||
|
step("init-pki")
|
||||||
_run_easyrsa(["init-pki"], env)
|
_run_easyrsa(["init-pki"], env)
|
||||||
|
|
||||||
# Build CA
|
# Build CA
|
||||||
|
step("ca")
|
||||||
_run_easyrsa(["--req-cn=" + pki_settings.fqdn_ca, "build-ca", "nopass"], env)
|
_run_easyrsa(["--req-cn=" + pki_settings.fqdn_ca, "build-ca", "nopass"], env)
|
||||||
|
|
||||||
# Build Server Cert
|
# Build Server Cert
|
||||||
|
step("server-cert")
|
||||||
_run_easyrsa(["build-server-full", pki_settings.fqdn_server, "nopass"], env)
|
_run_easyrsa(["build-server-full", pki_settings.fqdn_server, "nopass"], env)
|
||||||
|
|
||||||
# Gen DH
|
# Gen DH
|
||||||
|
step("dh")
|
||||||
_run_easyrsa(["gen-dh"], env)
|
_run_easyrsa(["gen-dh"], env)
|
||||||
|
|
||||||
# Gen TLS Auth Key (requires openvpn, not easyrsa)
|
# Gen TLS Auth Key
|
||||||
ta_key_path = os.path.join(PKI_DIR, "ta.key")
|
step("ta-key")
|
||||||
subprocess.run(["openvpn", "--genkey", "secret", ta_key_path], check=True)
|
_gen_ta_key()
|
||||||
|
|
||||||
# Gen CRL
|
# Gen CRL
|
||||||
|
step("crl")
|
||||||
_run_easyrsa(["gen-crl"], env)
|
_run_easyrsa(["gen-crl"], env)
|
||||||
_publish_crl()
|
_publish_crl()
|
||||||
|
|
||||||
return "PKI Initialized"
|
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_restore_running():
|
||||||
|
raise InitConflict(RESTORE_RUNNING_MSG)
|
||||||
|
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):
|
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
|
# 1. Clear Database Users
|
||||||
from models import UserProfile
|
from models import UserProfile
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -9,7 +9,14 @@ logger = logging.getLogger(__name__)
|
|||||||
def is_container():
|
def is_container():
|
||||||
"""
|
"""
|
||||||
Checks if the application is running inside a Docker container.
|
Checks if the application is running inside a Docker container.
|
||||||
|
OVPMON_RUNTIME=host|container overrides the detection (a service that runs on a host inside a
|
||||||
|
test container with /.dockerenv sets host).
|
||||||
"""
|
"""
|
||||||
|
forced = os.environ.get("OVPMON_RUNTIME", "").strip().lower()
|
||||||
|
if forced == "host":
|
||||||
|
return False
|
||||||
|
if forced == "container":
|
||||||
|
return True
|
||||||
if os.path.exists('/.dockerenv'):
|
if os.path.exists('/.dockerenv'):
|
||||||
return True
|
return True
|
||||||
try:
|
try:
|
||||||
@@ -23,6 +30,18 @@ def is_container():
|
|||||||
HELPER_PATH = "/usr/local/sbin/ovpmon-helper"
|
HELPER_PATH = "/usr/local/sbin/ovpmon-helper"
|
||||||
|
|
||||||
|
|
||||||
|
def openvpn_config_path():
|
||||||
|
"""OpenVPN config path for root/container mode (OVPMON_OPENVPN_CONFIG, default /etc/openvpn/server.conf).
|
||||||
|
Unprivileged mode only stages the file; the helper's own configuration decides where it is installed."""
|
||||||
|
return os.environ.get("OVPMON_OPENVPN_CONFIG", "").strip() or "/etc/openvpn/server.conf"
|
||||||
|
|
||||||
|
|
||||||
|
def openvpn_service_name():
|
||||||
|
"""Service name for the native root path (OVPMON_OPENVPN_SERVICE, default 'openvpn';
|
||||||
|
systemd hosts use 'openvpn-server@server')."""
|
||||||
|
return os.environ.get("OVPMON_OPENVPN_SERVICE", "").strip() or "openvpn"
|
||||||
|
|
||||||
|
|
||||||
def _run_helper(args):
|
def _run_helper(args):
|
||||||
"""Call the root-side helper through doas (used when this process is unprivileged).
|
"""Call the root-side helper through doas (used when this process is unprivileged).
|
||||||
Returns (returncode, parsed_json_or_None, raw_output)."""
|
Returns (returncode, parsed_json_or_None, raw_output)."""
|
||||||
@@ -68,7 +87,7 @@ def control_service(action: str):
|
|||||||
if action not in ["start", "stop", "restart"]:
|
if action not in ["start", "stop", "restart"]:
|
||||||
raise ValueError("Invalid action")
|
raise ValueError("Invalid action")
|
||||||
|
|
||||||
CONFIG_PATH = "/etc/openvpn/server.conf"
|
CONFIG_PATH = openvpn_config_path()
|
||||||
PID_FILE = "/run/openvpn.pid"
|
PID_FILE = "/run/openvpn.pid"
|
||||||
|
|
||||||
# In Container: Use direct execution to avoid OpenRC/cgroups issues
|
# In Container: Use direct execution to avoid OpenRC/cgroups issues
|
||||||
@@ -149,9 +168,9 @@ def control_service(action: str):
|
|||||||
|
|
||||||
cmd = []
|
cmd = []
|
||||||
if os_type == "alpine":
|
if os_type == "alpine":
|
||||||
cmd = ["rc-service", "openvpn", action]
|
cmd = ["rc-service", openvpn_service_name(), action]
|
||||||
else:
|
else:
|
||||||
cmd = ["systemctl", action, "openvpn"]
|
cmd = ["systemctl", action, openvpn_service_name()]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
|
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
|
||||||
|
|||||||
@@ -1,25 +1,19 @@
|
|||||||
client
|
client
|
||||||
dev tun
|
dev tun
|
||||||
windows-driver wintun
|
|
||||||
proto {{ protocol }}
|
proto {{ protocol }}
|
||||||
remote {{ remote_ip }} {{ port }}
|
remote {{ remote_ip }} {{ port }}
|
||||||
resolv-retry infinite
|
resolv-retry infinite
|
||||||
nobind
|
nobind
|
||||||
|
{% if protocol == 'udp' %}
|
||||||
|
explicit-exit-notify
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
{% if tun_mtu %}
|
{% if tun_mtu %}
|
||||||
tun-mtu {{ tun_mtu }}
|
tun-mtu {{ tun_mtu }}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
user nobody
|
|
||||||
group nobody
|
|
||||||
persist-key
|
persist-key
|
||||||
persist-tun
|
persist-tun
|
||||||
|
|
||||||
{% if protocol == 'tcp' %}
|
|
||||||
tls-client
|
|
||||||
{% else %}
|
|
||||||
#tls-client
|
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
mute-replay-warnings
|
mute-replay-warnings
|
||||||
|
|
||||||
remote-cert-tls server
|
remote-cert-tls server
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
dev tun
|
dev tun
|
||||||
proto {{ protocol }}
|
proto {{ protocol }}
|
||||||
{% if protocol == 'tcp' %}
|
{% if protocol != 'tcp' %}
|
||||||
tls-server
|
|
||||||
{% else %}
|
|
||||||
# explicit-exit-notify 1
|
|
||||||
explicit-exit-notify 1
|
explicit-exit-notify 1
|
||||||
{% endif %}
|
{% endif %}
|
||||||
port {{ port }}
|
port {{ port }}
|
||||||
@@ -28,7 +25,6 @@ server {{ vpn_network }} {{ vpn_netmask }}
|
|||||||
|
|
||||||
ifconfig-pool-persist /etc/openvpn/ipp.txt
|
ifconfig-pool-persist /etc/openvpn/ipp.txt
|
||||||
|
|
||||||
log /var/log/openvpn/openvpn.log
|
|
||||||
log-append /var/log/openvpn/openvpn.log
|
log-append /var/log/openvpn/openvpn.log
|
||||||
|
|
||||||
verb 3
|
verb 3
|
||||||
|
|||||||
@@ -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,404 @@
|
|||||||
|
import io
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import tarfile
|
||||||
|
import tempfile
|
||||||
|
import types
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
# The DB path must be set before database.py is imported (via main)
|
||||||
|
_tmp = tempfile.TemporaryDirectory()
|
||||||
|
os.environ.setdefault("OVPMON_PROFILER_DB_PATH", os.path.join(_tmp.name, "test.db"))
|
||||||
|
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from main import app
|
||||||
|
import migrations
|
||||||
|
from services import pki, process
|
||||||
|
from services.backup import BackupError, crypto, destinations, engine, package, store
|
||||||
|
from utils.auth import verify_token
|
||||||
|
|
||||||
|
app.dependency_overrides[verify_token] = lambda: {"sub": "test"}
|
||||||
|
client = TestClient(app)
|
||||||
|
|
||||||
|
PASS = "correct horse battery"
|
||||||
|
|
||||||
|
|
||||||
|
class InlineThread:
|
||||||
|
"""Runs the job in the calling thread: the tests need no polling."""
|
||||||
|
def __init__(self, target, args=(), daemon=None):
|
||||||
|
self.target, self.args = target, args
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
self.target(*self.args)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def env(tmp_path, monkeypatch):
|
||||||
|
"""A complete data layout in a temporary directory, nothing of the real system is touched."""
|
||||||
|
data = tmp_path / "data"
|
||||||
|
data.mkdir()
|
||||||
|
prof, mon = str(data / "ovpn_profiler.db"), str(data / "openvpn_monitor.db")
|
||||||
|
migrations.run(prof)
|
||||||
|
conn = sqlite3.connect(mon)
|
||||||
|
conn.executescript("CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT);"
|
||||||
|
"INSERT INTO schema_migrations VALUES (2, 'x', 'now');"
|
||||||
|
"CREATE TABLE users (name TEXT); INSERT INTO users VALUES ('admin');")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
pki_dir, client_dir = tmp_path / "easy-rsa" / "pki", tmp_path / "client-config"
|
||||||
|
(pki_dir / "private").mkdir(parents=True)
|
||||||
|
(pki_dir / "ca.crt").write_text("CA")
|
||||||
|
(pki_dir / "private" / "ca.key").write_text("SECRET")
|
||||||
|
os.chmod(pki_dir / "private" / "ca.key", 0o600)
|
||||||
|
client_dir.mkdir()
|
||||||
|
(client_dir / "alice.ovpn").write_text("client config")
|
||||||
|
monkeypatch.setenv("OVPMON_BACKUP_LOCAL_ROOT", str(tmp_path / "backups"))
|
||||||
|
monkeypatch.setattr(engine, "profiler_db_path", lambda: prof)
|
||||||
|
monkeypatch.setattr(engine, "monitor_db_path", lambda: mon)
|
||||||
|
monkeypatch.setattr(engine, "client_dir", lambda: str(client_dir))
|
||||||
|
monkeypatch.setattr(engine, "core_dir", lambda: None) # the schemas are equal: no migration needed
|
||||||
|
monkeypatch.setattr(pki, "PKI_DIR", str(pki_dir))
|
||||||
|
monkeypatch.setattr(process, "get_process_stats", lambda: {"status": "stopped"})
|
||||||
|
monkeypatch.setattr(engine, "threading", types.SimpleNamespace(Thread=InlineThread))
|
||||||
|
monkeypatch.setattr(store, "db_file", lambda: str(tmp_path / "ovpmon_backup.db"))
|
||||||
|
store.init()
|
||||||
|
return types.SimpleNamespace(root=tmp_path, prof=prof, mon=mon, pki=pki_dir, clients=client_dir)
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_round_trip_and_wrong_passphrase(env, tmp_path):
|
||||||
|
work = tmp_path / "w"
|
||||||
|
work.mkdir()
|
||||||
|
path, name, manifest = engine.create_package(str(work), PASS)
|
||||||
|
assert name.endswith(".ovpbak.enc") and package.parse_package_name(name)["encrypted"]
|
||||||
|
assert crypto.is_encrypted(path) and b"SECRET" not in open(path, "rb").read()
|
||||||
|
assert manifest["schema"]["monitor"] == 2 and "pki/private/ca.key" in manifest["files"]
|
||||||
|
|
||||||
|
with pytest.raises(crypto.WrongPassphrase):
|
||||||
|
crypto.decrypt_file(path, str(tmp_path / "bad.tar.gz"), "wrong passphrase")
|
||||||
|
crypto.decrypt_file(path, str(tmp_path / "ok.tar.gz"), PASS)
|
||||||
|
out = tmp_path / "out"
|
||||||
|
package.safe_extract(str(tmp_path / "ok.tar.gz"), str(out))
|
||||||
|
assert (out / "pki" / "ca.crt").read_text() == "CA"
|
||||||
|
assert (out / "pki" / "private" / "ca.key").read_text() == "SECRET"
|
||||||
|
assert oct(os.stat(out / "pki" / "private" / "ca.key").st_mode & 0o777) == "0o600"
|
||||||
|
assert (out / "client-config" / "alice.ovpn").read_text() == "client config"
|
||||||
|
assert sqlite3.connect(out / "db" / "openvpn_monitor.db").execute("SELECT name FROM users").fetchone() == ("admin",)
|
||||||
|
assert package.integrity_ok(str(out / "db" / "ovpn_profiler.db"))
|
||||||
|
|
||||||
|
|
||||||
|
def _tar(path, members):
|
||||||
|
with tarfile.open(path, "w:gz") as tar:
|
||||||
|
for info, data in members:
|
||||||
|
tar.addfile(info, io.BytesIO(data) if data is not None else None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_safe_extraction_and_newer_schema(env, tmp_path):
|
||||||
|
def reg(name, data=b"x"):
|
||||||
|
info = tarfile.TarInfo(name)
|
||||||
|
info.size = len(data)
|
||||||
|
return info, data
|
||||||
|
|
||||||
|
link = tarfile.TarInfo("pki/link")
|
||||||
|
link.type, link.linkname = tarfile.SYMTYPE, "/etc/passwd"
|
||||||
|
for i, members in enumerate([[reg("../evil")], [reg("/abs/evil")], [reg("pki/../../evil")],
|
||||||
|
[(link, None)], [reg("other/file")], [reg("db/extra.db")]]):
|
||||||
|
bad = str(tmp_path / f"bad{i}.tar.gz")
|
||||||
|
_tar(bad, members)
|
||||||
|
with pytest.raises(BackupError):
|
||||||
|
package.safe_extract(bad, str(tmp_path / f"out{i}"))
|
||||||
|
assert not (tmp_path / "evil").exists()
|
||||||
|
|
||||||
|
# A valid package from a newer release is refused before anything is touched
|
||||||
|
work = tmp_path / "w"
|
||||||
|
work.mkdir()
|
||||||
|
path, _name, _ = engine.create_package(str(work), None)
|
||||||
|
out = tmp_path / "ok"
|
||||||
|
manifest = package.safe_extract(path, str(out))
|
||||||
|
conn = sqlite3.connect(out / "db" / "ovpn_profiler.db")
|
||||||
|
conn.execute("INSERT INTO schema_migrations VALUES (999, 'future', 'now')")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
with pytest.raises(BackupError, match="newer release"):
|
||||||
|
engine._prepare_staged(str(out), manifest)
|
||||||
|
# An unknown format version is refused too
|
||||||
|
import json
|
||||||
|
manifest["format_version"] = 99
|
||||||
|
(out / "manifest.json").write_text(json.dumps(manifest))
|
||||||
|
with pytest.raises(BackupError, match="Unknown package format"):
|
||||||
|
package.verify_extracted(str(out))
|
||||||
|
|
||||||
|
|
||||||
|
class FailingDestination(destinations.Destination):
|
||||||
|
type = "stub"
|
||||||
|
label = "Stub"
|
||||||
|
|
||||||
|
def put(self, local_path, name):
|
||||||
|
raise destinations.DestinationError("disk on fire")
|
||||||
|
|
||||||
|
def list(self):
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def test_multi_destination_backup_rotation_and_restore(env, tmp_path, monkeypatch):
|
||||||
|
monkeypatch.setitem(destinations.DESTINATION_TYPES, "stub", FailingDestination)
|
||||||
|
good = store.save_destination(None, "local-good", "local", True, 2, {"folder": "daily"}, {})
|
||||||
|
bad = store.save_destination(None, "broken", "stub", True, 14, {}, {})
|
||||||
|
stamps = iter(f"20261007T1000{i:02d}Z" for i in range(10))
|
||||||
|
monkeypatch.setattr(package, "utc_stamp", lambda now=None: next(stamps))
|
||||||
|
|
||||||
|
for _ in range(3):
|
||||||
|
engine.start_backup(None)
|
||||||
|
job = engine.status()
|
||||||
|
assert job["state"] == "partial" # one failed, the other still got the package
|
||||||
|
by_name = {r["name"]: r for r in job["results"]}
|
||||||
|
assert by_name["local-good"]["state"] == "ok" and by_name["broken"]["state"] == "error"
|
||||||
|
assert "disk on fire" in by_name["broken"]["message"]
|
||||||
|
assert store.get_destination(bad)["last_status"] == "error"
|
||||||
|
names = sorted(p["name"] for p in engine.list_packages(good))
|
||||||
|
assert len(names) == 2 and names[0].endswith("100001Z.ovpbak") # oldest of 3 rotated away
|
||||||
|
|
||||||
|
# Restore the newest package after the live data was damaged
|
||||||
|
newest = engine.list_packages(good)[0]["name"]
|
||||||
|
env.pki.joinpath("ca.crt").write_text("DAMAGED")
|
||||||
|
(env.clients / "alice.ovpn").unlink()
|
||||||
|
(env.clients / "stray.ovpn").write_text("not in the package")
|
||||||
|
sqlite3.connect(env.mon).execute("DROP TABLE users").connection.commit()
|
||||||
|
engine.start_restore(good, newest, None)
|
||||||
|
job = engine.status()
|
||||||
|
assert job["state"] == "done", job["message"]
|
||||||
|
assert job["relogin"] is True
|
||||||
|
assert env.pki.joinpath("ca.crt").read_text() == "CA"
|
||||||
|
assert (env.clients / "alice.ovpn").read_text() == "client config" and not (env.clients / "stray.ovpn").exists()
|
||||||
|
assert sqlite3.connect(env.mon).execute("SELECT name FROM users").fetchone() == ("admin",)
|
||||||
|
assert not [p for p in os.listdir(env.pki) if p.startswith(".restore-")]
|
||||||
|
# the previous state was saved first, locally
|
||||||
|
pre = destinations.LocalDestination({"folder": "pre-restore"}, {}).list()
|
||||||
|
assert len(pre) == 1 and package.parse_package_name(pre[0]["name"])
|
||||||
|
|
||||||
|
# A package that is not in the listing is not accepted
|
||||||
|
with pytest.raises(BackupError):
|
||||||
|
engine.start_restore(good, "ovpmon-backup_x_20200101T000000Z.ovpbak", None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_api_requires_jwt_masks_secrets_and_refuses_remote_without_passphrase(env):
|
||||||
|
saved = app.dependency_overrides.pop(verify_token)
|
||||||
|
try:
|
||||||
|
for method, path in [("get", "/api/backup/settings"), ("put", "/api/backup/settings"),
|
||||||
|
("get", "/api/backup/destinations"), ("post", "/api/backup/destinations"),
|
||||||
|
("put", "/api/backup/destinations/1"), ("delete", "/api/backup/destinations/1"),
|
||||||
|
("post", "/api/backup/destinations/1/test"), ("get", "/api/backup/destinations/1/packages"),
|
||||||
|
("post", "/api/backup/run"), ("post", "/api/backup/restore"),
|
||||||
|
("get", "/api/backup/status"), ("get", "/api/backup/history")]:
|
||||||
|
assert getattr(client, method)(path).status_code == 401, (method, path)
|
||||||
|
finally:
|
||||||
|
app.dependency_overrides[verify_token] = saved
|
||||||
|
|
||||||
|
s3 = {"name": "bucket", "type": "s3", "params": {"endpoint": "s3.example.com", "bucket": "my-backups"},
|
||||||
|
"secrets": {"access_key": "AKIAEXAMPLE", "secret_key": "TOPSECRETVALUE"}}
|
||||||
|
r = client.post("/api/backup/destinations", json=s3)
|
||||||
|
assert r.status_code == 201
|
||||||
|
dest = r.json()
|
||||||
|
assert "TOPSECRETVALUE" not in r.text and "AKIAEXAMPLE" not in r.text
|
||||||
|
assert dest["secrets"] == {"access_key": store.MASK, "secret_key": store.MASK}
|
||||||
|
assert "TOPSECRETVALUE" not in client.get("/api/backup/destinations").text
|
||||||
|
assert "TOPSECRETVALUE" not in open(store.db_file(), "rb").read().decode("latin-1") # encrypted at rest
|
||||||
|
|
||||||
|
# Only implemented types; updating with the mask keeps the stored secret
|
||||||
|
assert client.post("/api/backup/destinations", json={**s3, "name": "x", "type": "smb"}).status_code == 400
|
||||||
|
s3["secrets"] = {"access_key": store.MASK, "secret_key": ""}
|
||||||
|
assert client.put(f"/api/backup/destinations/{dest['id']}", json=s3).status_code == 200
|
||||||
|
assert store.get_destination(dest["id"], with_secrets=True)["secrets"]["secret_key"] == "TOPSECRETVALUE"
|
||||||
|
|
||||||
|
# Remote destination without a passphrase: no backup
|
||||||
|
r = client.post("/api/backup/run", json={})
|
||||||
|
assert r.status_code == 400 and "passphrase" in r.json()["detail"].lower()
|
||||||
|
assert client.put("/api/backup/settings", json={"passphrase": "short"}).status_code == 400
|
||||||
|
r = client.put("/api/backup/settings", json={"passphrase": PASS})
|
||||||
|
assert r.status_code == 200 and r.json()["encryption_enabled"] is True and PASS not in r.text
|
||||||
|
assert client.put("/api/backup/settings", json={"clear_passphrase": True}).status_code == 400 # remote needs it
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_name_server_name_fallback_and_unique_names(env, tmp_path, monkeypatch):
|
||||||
|
import re
|
||||||
|
import socket
|
||||||
|
monkeypatch.setattr(socket, "gethostname", lambda: "3f9a1c0b2d44")
|
||||||
|
assert engine.effective_server_name() == ("3f9a1c0b2d44", "hostname")
|
||||||
|
conn = sqlite3.connect(env.prof)
|
||||||
|
conn.execute("INSERT INTO system_settings (id, public_ip) VALUES (1, 'vpn.example.com')")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
assert engine.effective_server_name() == ("vpn.example.com", "public_ip")
|
||||||
|
|
||||||
|
# The setting wins, is validated, and can be cleared again
|
||||||
|
assert client.put("/api/backup/settings", json={"server_name": "bad name!"}).status_code == 400
|
||||||
|
r = client.put("/api/backup/settings", json={"server_name": "vpn-main"}).json()
|
||||||
|
assert (r["server_name"], r["effective_server_name"], r["server_name_source"]) == ("vpn-main", "vpn-main", "setting")
|
||||||
|
assert client.put("/api/backup/settings", json={"server_name": ""}).json()["server_name_source"] == "public_ip"
|
||||||
|
store.set_server_name("vpn-main")
|
||||||
|
|
||||||
|
# Name format, manifest, and -2 / -3 when the same second is taken (nothing is overwritten)
|
||||||
|
monkeypatch.setattr(package, "utc_stamp", lambda now=None: "20261007T101500Z")
|
||||||
|
dest = store.save_destination(None, "local-daily", "local", True, 2, {"folder": "daily"}, {})
|
||||||
|
old = "ovpmon-backup_oldhost_20200101T000000Z.ovpbak" # first-pass name: listed, never rotated
|
||||||
|
destinations.LocalDestination({"folder": "daily"}, {}).put(str(env.prof), old)
|
||||||
|
for _ in range(3):
|
||||||
|
engine.start_backup(None)
|
||||||
|
assert engine.status()["state"] == "done"
|
||||||
|
packages = engine.list_packages(dest)
|
||||||
|
assert [p["name"] for p in packages] == [
|
||||||
|
"ovpmon-backup_vpn-main_20261007T101500Z-3.ovpbak",
|
||||||
|
"ovpmon-backup_vpn-main_20261007T101500Z-2.ovpbak", old] # newest first; -1 rotated away
|
||||||
|
assert packages[0]["server_name"] == "vpn-main" and packages[2]["server_name"] == "oldhost"
|
||||||
|
work = tmp_path / "w"
|
||||||
|
work.mkdir()
|
||||||
|
_path, name, manifest = engine.create_package(str(work), None)
|
||||||
|
assert name == "ovpmon-backup_vpn-main_20261007T101500Z.ovpbak"
|
||||||
|
assert manifest["server_name"] == "vpn-main" and manifest["hostname"] == "3f9a1c0b2d44"
|
||||||
|
assert re.match(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$", manifest["created_at"])
|
||||||
|
|
||||||
|
|
||||||
|
class FakeKey:
|
||||||
|
blob = b"server-host-key-A"
|
||||||
|
|
||||||
|
def asbytes(self):
|
||||||
|
return self.blob
|
||||||
|
|
||||||
|
def get_name(self):
|
||||||
|
return "ssh-ed25519"
|
||||||
|
|
||||||
|
|
||||||
|
class FakeSFTP:
|
||||||
|
files, dirs = {}, set()
|
||||||
|
|
||||||
|
def get_channel(self):
|
||||||
|
return types.SimpleNamespace(settimeout=lambda t: None)
|
||||||
|
|
||||||
|
def stat(self, path):
|
||||||
|
if path in self.dirs:
|
||||||
|
return types.SimpleNamespace(st_mode=0o40700)
|
||||||
|
raise FileNotFoundError(path)
|
||||||
|
|
||||||
|
def mkdir(self, path, mode=0o777):
|
||||||
|
self.dirs.add(path)
|
||||||
|
|
||||||
|
def put(self, local, remote, confirm=True):
|
||||||
|
self.files[remote] = open(local, "rb").read()
|
||||||
|
|
||||||
|
def putfo(self, fh, remote):
|
||||||
|
self.files[remote] = fh.read()
|
||||||
|
|
||||||
|
def posix_rename(self, a, b):
|
||||||
|
self.files[b] = self.files.pop(a)
|
||||||
|
|
||||||
|
def remove(self, path):
|
||||||
|
del self.files[path]
|
||||||
|
|
||||||
|
def listdir_attr(self, directory):
|
||||||
|
return [types.SimpleNamespace(filename=p.rsplit("/", 1)[-1], st_mode=0o100600, st_size=len(v), st_mtime=1.0)
|
||||||
|
for p, v in self.files.items() if p.rsplit("/", 1)[0] == directory]
|
||||||
|
|
||||||
|
def getfo(self, remote, out):
|
||||||
|
out.write(self.files[remote])
|
||||||
|
|
||||||
|
|
||||||
|
class FakeSSH:
|
||||||
|
connects = []
|
||||||
|
|
||||||
|
def set_missing_host_key_policy(self, policy):
|
||||||
|
self.policy = policy
|
||||||
|
|
||||||
|
def connect(self, host, **kw):
|
||||||
|
FakeSSH.connects.append((host, kw.get("password"), kw.get("pkey")))
|
||||||
|
self.policy.missing_host_key(self, host, FakeKey()) # raises unless the key is the pinned one
|
||||||
|
|
||||||
|
def open_sftp(self):
|
||||||
|
return FakeSFTP()
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def test_sftp_ftp_validation_and_host_key_pinning(env, monkeypatch):
|
||||||
|
import paramiko
|
||||||
|
from cryptography.hazmat.primitives import serialization
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import ed25519
|
||||||
|
monkeypatch.setattr(paramiko, "SSHClient", FakeSSH)
|
||||||
|
FakeSFTP.files, FakeSFTP.dirs = {}, set()
|
||||||
|
FakeSSH.connects.clear()
|
||||||
|
sftp, ftp = destinations.SFTPDestination, destinations.FTPDestination
|
||||||
|
base = {"host": "files.example.com", "port": 22, "username": "backup", "directory": "ovpmon/daily"}
|
||||||
|
|
||||||
|
# Parameter and secret rules
|
||||||
|
for bad in ({"host": "bad host!"}, {"port": 70000}, {"username": ""}, {"directory": "../x"}, {"directory": "/etc"}):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
sftp.validate({**base, **bad}, {"password": "pw"})
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
sftp.validate(base, {}) # neither password nor key
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
sftp.validate(base, {"password": "pw", "private_key": "x"}) # both
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
sftp.validate(base, {"private_key": "-----BEGIN OPENSSH PRIVATE KEY-----\nnot a key\n"})
|
||||||
|
key = ed25519.Ed25519PrivateKey.generate().private_bytes(
|
||||||
|
serialization.Encoding.PEM, serialization.PrivateFormat.OpenSSH, serialization.NoEncryption()).decode()
|
||||||
|
assert sftp.validate(base, {"private_key": key})[1] == {"private_key": key.strip() + "\n"}
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
sftp.validate({**base, "host_key": "SHA256:x"}, {"password": "pw"}) # a pin never comes with the form
|
||||||
|
fclean, _ = ftp.validate({"host": "ftp.example.com", "username": "u", "directory": "bk"}, {"password": "pw"})
|
||||||
|
assert (fclean["port"], fclean["tls"], fclean["verify_cert"], fclean["passive"]) == (21, True, True, True)
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
ftp.validate({"host": "ftp.example.com", "username": "u", "directory": "bk"}, {}) # no password
|
||||||
|
|
||||||
|
# Not pinned: Test shows the fingerprint, nothing else works, no connection is even opened
|
||||||
|
body = {"name": "offsite", "type": "sftp", "params": base, "secrets": {"password": "pw"}}
|
||||||
|
dest = client.post("/api/backup/destinations", json=body).json()
|
||||||
|
assert dest["secrets"] == {"password": store.MASK} and "host_key" not in dest["params"]
|
||||||
|
shown = engine.test_destination(dest["id"])
|
||||||
|
assert shown["ok"] is False and shown["needs_trust"] is True and shown["key_changed"] is False
|
||||||
|
fp = shown["fingerprint"]
|
||||||
|
assert fp == destinations._ssh_fingerprint(FakeKey())
|
||||||
|
rec = store.get_destination(dest["id"], with_secrets=True)
|
||||||
|
unpinned = destinations.build_destination("sftp", rec["params"], rec["secrets"])
|
||||||
|
n = len(FakeSSH.connects)
|
||||||
|
for call in (lambda: unpinned.put(__file__, "ovpmon-backup_x_20260101T000000Z.ovpbak"), unpinned.list,
|
||||||
|
lambda: unpinned.get("ovpmon-backup_x_20260101T000000Z.ovpbak", "/dev/null"),
|
||||||
|
lambda: unpinned.delete("ovpmon-backup_x_20260101T000000Z.ovpbak")):
|
||||||
|
with pytest.raises(destinations.DestinationError, match="not trusted"):
|
||||||
|
call()
|
||||||
|
assert len(FakeSSH.connects) == n
|
||||||
|
|
||||||
|
# Trust: only the fingerprint the administrator saw is accepted
|
||||||
|
with pytest.raises(BackupError):
|
||||||
|
engine.trust_host_key(dest["id"], "SHA256:" + "A" * 43)
|
||||||
|
pinned = engine.trust_host_key(dest["id"], fp)
|
||||||
|
assert pinned["params"]["host_key"] == fp and pinned["secrets"] == {"password": store.MASK}
|
||||||
|
assert engine.test_destination(dest["id"])["ok"] is True
|
||||||
|
rec = store.get_destination(dest["id"], with_secrets=True)
|
||||||
|
d = destinations.build_destination("sftp", rec["params"], rec["secrets"])
|
||||||
|
name = "ovpmon-backup_vpn_20261007T101500Z.ovpbak"
|
||||||
|
d.put(__file__, name)
|
||||||
|
assert f"ovpmon/daily/{name}" in FakeSFTP.files and not [f for f in FakeSFTP.files if f.endswith(".part")]
|
||||||
|
FakeSFTP.files["ovpmon/daily/notes.txt"] = b"x"
|
||||||
|
assert [o["name"] for o in d.list()] == [name] # only our package names
|
||||||
|
out = os.path.join(os.path.dirname(env.prof), "got")
|
||||||
|
d.get(name, out)
|
||||||
|
assert open(out, "rb").read() == open(__file__, "rb").read()
|
||||||
|
|
||||||
|
# Pin and the form: an edit of other fields keeps the pin, a client cannot set it, a new host drops it
|
||||||
|
edit = {**body, "params": {**base, "host_key": "SHA256:" + "B" * 43, "directory": "ovpmon/other"}, "secrets": {}}
|
||||||
|
r = client.put(f"/api/backup/destinations/{dest['id']}", json=edit).json()
|
||||||
|
assert r["params"]["host_key"] == fp and r["params"]["directory"] == "ovpmon/other"
|
||||||
|
r = client.put(f"/api/backup/destinations/{dest['id']}", json={**edit, "params": {**base, "host": "other.example.com"}}).json()
|
||||||
|
assert "host_key" not in r["params"]
|
||||||
|
client.put(f"/api/backup/destinations/{dest['id']}", json={**edit, "params": base})
|
||||||
|
engine.trust_host_key(dest["id"], fp)
|
||||||
|
|
||||||
|
# A different key from the server: connection refused, Test offers the new fingerprint (changed)
|
||||||
|
FakeKey.blob = b"server-host-key-B"
|
||||||
|
try:
|
||||||
|
with pytest.raises(destinations.DestinationError, match="host key of the server changed"):
|
||||||
|
d.list()
|
||||||
|
changed = engine.test_destination(dest["id"])
|
||||||
|
assert changed["needs_trust"] is True and changed["key_changed"] is True and changed["fingerprint"] != fp
|
||||||
|
finally:
|
||||||
|
FakeKey.blob = b"server-host-key-A"
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
"""One test for the client profile template (templates/client.ovpn.j2), tcp and udp."""
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from services.generator import env
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("protocol", ["tcp", "udp"])
|
||||||
|
def test_client_template(protocol):
|
||||||
|
text = env.get_template("client.ovpn.j2").render(
|
||||||
|
protocol=protocol, remote_ip="203.0.113.1", port=1194, ca_cert="CA",
|
||||||
|
client_cert="CERT", client_key="KEY", tls_auth="TA", tun_mtu=None)
|
||||||
|
lines = [x.strip() for x in text.splitlines()]
|
||||||
|
assert f"proto {protocol}" in lines and "client" in lines
|
||||||
|
# directives that OpenVPN 2.7 rejects or that are redundant/harmful on user devices
|
||||||
|
for gone in ("windows-driver", "tls-client", "#tls-client", "user", "group"):
|
||||||
|
assert not any(x.split(" ")[0] == gone for x in lines)
|
||||||
|
assert ("explicit-exit-notify" in lines) == (protocol == "udp")
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
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 utils.auth import verify_token
|
||||||
|
|
||||||
|
app.dependency_overrides[verify_token] = lambda: {"sub": "test"}
|
||||||
|
client = TestClient(app)
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_section_values():
|
||||||
|
r = client.get("/api/config", params={"section": "server"})
|
||||||
|
assert r.status_code == 200 and r.json()["server"] and not r.json().get("pki")
|
||||||
|
assert client.get("/api/config", params={"section": "pki"}).status_code == 200
|
||||||
|
assert client.get("/api/config").status_code == 200
|
||||||
|
assert client.get("/api/config", params={"section": "bogus"}).status_code == 422
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
"""One test for the root helper's optional configuration (/etc/ovpmon/helper.conf).
|
||||||
|
|
||||||
|
The helper has no .py extension, so it is loaded by path. Nothing here touches a real service:
|
||||||
|
subprocess.run is replaced, the config files live in a temporary directory.
|
||||||
|
"""
|
||||||
|
import importlib.machinery
|
||||||
|
import importlib.util
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import types
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
HELPER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "DOCS", "General",
|
||||||
|
"privilege-separation", "ovpmon-helper")
|
||||||
|
|
||||||
|
|
||||||
|
def load_helper():
|
||||||
|
loader = importlib.machinery.SourceFileLoader("ovpmon_helper_under_test", HELPER)
|
||||||
|
spec = importlib.util.spec_from_loader(loader.name, loader)
|
||||||
|
mod = importlib.util.module_from_spec(spec)
|
||||||
|
loader.exec_module(mod)
|
||||||
|
return mod
|
||||||
|
|
||||||
|
|
||||||
|
def write_conf(tmp_path, text, mode=0o644):
|
||||||
|
p = tmp_path / "helper.conf"
|
||||||
|
p.write_text(text)
|
||||||
|
p.chmod(mode)
|
||||||
|
return str(p)
|
||||||
|
|
||||||
|
|
||||||
|
def test_helper_config(tmp_path, monkeypatch):
|
||||||
|
if not os.path.isfile(HELPER):
|
||||||
|
pytest.skip("the helper source (DOCS/General/privilege-separation/ovpmon-helper) is not part of this tree")
|
||||||
|
h = load_helper()
|
||||||
|
|
||||||
|
# 1. Without helper.conf the old hard-coded values apply
|
||||||
|
assert h.load_config(str(tmp_path / "missing.conf")) == {}
|
||||||
|
assert h.STAGED == "/var/lib/ovpmon/staging/server.conf"
|
||||||
|
assert h.TARGET == "/etc/openvpn/server.conf"
|
||||||
|
assert h.PKI_DIR == "/opt/OpenVPN-Monitoring-Simple/APP_PROFILER/easy-rsa/pki"
|
||||||
|
assert h.CRL_SRC == h.PKI_DIR + "/crl.pem"
|
||||||
|
assert h.service_command("restart") == ["/sbin/rc-service", "openvpn", "restart"]
|
||||||
|
|
||||||
|
# 2. A valid file (here owned by the test user instead of root) is applied; PKI follows install_dir
|
||||||
|
own = os.getuid()
|
||||||
|
conf = write_conf(tmp_path, "[helper]\ninstall_dir = /srv/ovpmon\nservice_manager = systemd\n"
|
||||||
|
"config_path = /etc/openvpn/server/server.conf\n")
|
||||||
|
h.load_config(conf, owner_uid=own)
|
||||||
|
assert h.TARGET == "/etc/openvpn/server/server.conf"
|
||||||
|
assert h.PKI_DIR == "/srv/ovpmon/APP_PROFILER/easy-rsa/pki"
|
||||||
|
assert h.SERVICE_UNIT == "openvpn-server@server" # systemd default unit
|
||||||
|
|
||||||
|
# 3. Command lines: systemd -> systemctl <action> <unit>; openrc -> rc-service <unit> <action>
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake_run(cmd, **kwargs):
|
||||||
|
calls.append(cmd)
|
||||||
|
return subprocess.CompletedProcess(cmd, 0, stdout="ok", stderr="")
|
||||||
|
|
||||||
|
monkeypatch.setattr(h, "subprocess", types.SimpleNamespace(run=fake_run))
|
||||||
|
assert h.service("stop") == (0, "ok")
|
||||||
|
assert calls[-1][1:] == ["stop", "openvpn-server@server"] and calls[-1][0].endswith("systemctl")
|
||||||
|
h.load_config(write_conf(tmp_path, "[helper]\nservice_unit = openvpn\n"), owner_uid=own)
|
||||||
|
h.service("status")
|
||||||
|
assert calls[-1] == ["/sbin/rc-service", "openvpn", "status"]
|
||||||
|
|
||||||
|
# 4. Unsafe or malformed files are rejected; so is a file that is not owned by root
|
||||||
|
for bad in ("[helper]\ninstall_dir = /opt/../etc\n",
|
||||||
|
"[helper]\nservice_unit = x; reboot\n",
|
||||||
|
"[helper]\nservice_unit = -rf\n",
|
||||||
|
"[helper]\nservice_manager = runit\n",
|
||||||
|
"[helper]\nconfig_path = /tmp/server.conf\n",
|
||||||
|
"[helper]\nstaged_path = /etc/passwd\n",
|
||||||
|
"[helper]\nunknown = 1\n",
|
||||||
|
"install_dir = /opt/x\n"):
|
||||||
|
with pytest.raises(h.Reject):
|
||||||
|
h.load_config(write_conf(tmp_path, bad), owner_uid=own)
|
||||||
|
with pytest.raises(h.Reject):
|
||||||
|
h.load_config(write_conf(tmp_path, "[helper]\n", mode=0o666), owner_uid=own) # group/world writable
|
||||||
|
with pytest.raises(h.Reject):
|
||||||
|
h.load_config(write_conf(tmp_path, "[helper]\n"), owner_uid=own + 1) # wrong owner
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
import glob
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
# The DB path must be set before database.py is imported (the migration reads the models)
|
||||||
|
_tmp = tempfile.TemporaryDirectory()
|
||||||
|
os.environ["OVPMON_PROFILER_DB_PATH"] = os.path.join(_tmp.name, "test.db")
|
||||||
|
|
||||||
|
import migrations
|
||||||
|
|
||||||
|
PKI_SQL = """
|
||||||
|
CREATE TABLE pki_settings (
|
||||||
|
id INTEGER NOT NULL, fqdn_ca VARCHAR, fqdn_server VARCHAR, easyrsa_dn VARCHAR,
|
||||||
|
easyrsa_req_country VARCHAR, easyrsa_req_province VARCHAR, easyrsa_req_city VARCHAR,
|
||||||
|
easyrsa_req_org VARCHAR, easyrsa_req_email VARCHAR, easyrsa_req_ou VARCHAR,
|
||||||
|
easyrsa_key_size INTEGER, easyrsa_ca_expire INTEGER, easyrsa_cert_expire INTEGER,
|
||||||
|
easyrsa_cert_renew INTEGER, easyrsa_crl_days INTEGER, easyrsa_batch BOOLEAN,
|
||||||
|
PRIMARY KEY (id)
|
||||||
|
);
|
||||||
|
CREATE INDEX ix_pki_settings_id ON pki_settings (id);
|
||||||
|
"""
|
||||||
|
|
||||||
|
SYSTEM_COLUMNS = """
|
||||||
|
id INTEGER NOT NULL, protocol VARCHAR, port INTEGER, vpn_network VARCHAR,
|
||||||
|
vpn_netmask VARCHAR, tunnel_type VARCHAR, split_routes JSON, duplicate_cn BOOLEAN,
|
||||||
|
crl_verify BOOLEAN, client_to_client BOOLEAN, user_defined_dns BOOLEAN, dns_servers JSON,
|
||||||
|
user_defined_cdscripts BOOLEAN, connect_script VARCHAR, disconnect_script VARCHAR,
|
||||||
|
management_interface BOOLEAN, management_interface_address VARCHAR, management_port INTEGER
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Oldest schema: reconstructed from what the standalone scripts (add_columns.py,
|
||||||
|
# scripts/add_*.py) had to add later. Git history has no older models.py than fcb8f6b.
|
||||||
|
ANCIENT_SQL = PKI_SQL + f"""
|
||||||
|
CREATE TABLE system_settings ({SYSTEM_COLUMNS}, PRIMARY KEY (id));
|
||||||
|
CREATE INDEX ix_system_settings_id ON system_settings (id);
|
||||||
|
CREATE TABLE user_profiles (
|
||||||
|
id INTEGER NOT NULL, username VARCHAR, status VARCHAR, created_at DATETIME,
|
||||||
|
revoked_at DATETIME, file_path VARCHAR, PRIMARY KEY (id)
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX ix_user_profiles_username ON user_profiles (username);
|
||||||
|
CREATE INDEX ix_user_profiles_id ON user_profiles (id);
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Baseline: models.py at commit 3836049 (everything except user_profiles.note)
|
||||||
|
BASELINE_SQL = PKI_SQL + f"""
|
||||||
|
CREATE TABLE system_settings (
|
||||||
|
{SYSTEM_COLUMNS}, public_ip VARCHAR, tun_mtu INTEGER, mssfix INTEGER, PRIMARY KEY (id)
|
||||||
|
);
|
||||||
|
CREATE INDEX ix_system_settings_id ON system_settings (id);
|
||||||
|
CREATE TABLE user_profiles (
|
||||||
|
id INTEGER NOT NULL, username VARCHAR, status VARCHAR, created_at DATETIME,
|
||||||
|
revoked_at DATETIME, expiration_date DATETIME, is_revoked BOOLEAN, is_expired BOOLEAN,
|
||||||
|
file_path VARCHAR, PRIMARY KEY (id)
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX ix_user_profiles_username ON user_profiles (username);
|
||||||
|
CREATE INDEX ix_user_profiles_id ON user_profiles (id);
|
||||||
|
"""
|
||||||
|
|
||||||
|
ROWS_SQL = """
|
||||||
|
INSERT INTO pki_settings (id, fqdn_ca, easyrsa_key_size) VALUES (1, 'my-ca', 4096);
|
||||||
|
INSERT INTO system_settings (id, protocol, port, tunnel_type) VALUES (1, 'tcp', 443, 'SPLIT');
|
||||||
|
INSERT INTO user_profiles (id, username, status, created_at, file_path)
|
||||||
|
VALUES (1, 'alice', 'active', '2026-01-01 10:00:00', '/p/alice.ovpn');
|
||||||
|
INSERT INTO user_profiles (id, username, status, created_at, file_path)
|
||||||
|
VALUES (2, 'bob', 'revoked', '2026-01-02 10:00:00', '/p/bob.ovpn');
|
||||||
|
"""
|
||||||
|
|
||||||
|
SCHEMAS = {"ancient": ANCIENT_SQL, "baseline_3836049": BASELINE_SQL}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _auto_migrate(monkeypatch):
|
||||||
|
monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False)
|
||||||
|
|
||||||
|
|
||||||
|
def make_db(path, schema_sql, extra_sql=ROWS_SQL):
|
||||||
|
conn = sqlite3.connect(path)
|
||||||
|
conn.executescript(schema_sql + extra_sql)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def query(path, sql):
|
||||||
|
conn = sqlite3.connect(path)
|
||||||
|
try:
|
||||||
|
return conn.execute(sql).fetchall()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def columns(path, table):
|
||||||
|
return [r[1] for r in query(path, f"PRAGMA table_info({table})")]
|
||||||
|
|
||||||
|
|
||||||
|
def sha(path):
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
return hashlib.sha256(f.read()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("schema", SCHEMAS)
|
||||||
|
def test_old_schema_is_migrated_without_data_loss(tmp_path, schema):
|
||||||
|
db = str(tmp_path / "old.db")
|
||||||
|
make_db(db, SCHEMAS[schema])
|
||||||
|
users_before = query(db, "SELECT id, username, status, created_at, file_path FROM user_profiles")
|
||||||
|
|
||||||
|
report = migrations.run(db)
|
||||||
|
|
||||||
|
# Original rows intact
|
||||||
|
assert query(db, "SELECT id, username, status, created_at, file_path FROM user_profiles") == users_before
|
||||||
|
assert query(db, "SELECT fqdn_ca, easyrsa_key_size FROM pki_settings") == [("my-ca", 4096)]
|
||||||
|
assert query(db, "SELECT protocol, port, tunnel_type FROM system_settings") == [("tcp", 443, "SPLIT")]
|
||||||
|
# New columns exist; existing rows get the defaults
|
||||||
|
assert {"note", "is_revoked", "is_expired", "expiration_date"} <= set(columns(db, "user_profiles"))
|
||||||
|
assert {"public_ip", "tun_mtu", "mssfix"} <= set(columns(db, "system_settings"))
|
||||||
|
# Columns added now get the default; columns that already existed keep their values
|
||||||
|
flags = (0, 0) if schema == "ancient" else (None, None)
|
||||||
|
assert query(db, "SELECT is_revoked, is_expired, expiration_date, note FROM user_profiles") == [
|
||||||
|
flags + (None, None), flags + (None, None)]
|
||||||
|
assert query(db, "SELECT public_ip, tun_mtu, mssfix FROM system_settings") == [(None, None, None)]
|
||||||
|
# Stamped, and the backup is the untouched pre-migration copy
|
||||||
|
assert query(db, "SELECT version, name FROM schema_migrations") == [(1, "baseline")]
|
||||||
|
backups = glob.glob(db + ".bak-*")
|
||||||
|
assert backups == [report.backup]
|
||||||
|
assert query(backups[0], "SELECT id, username, status, created_at, file_path FROM user_profiles") == users_before
|
||||||
|
assert "note" not in columns(backups[0], "user_profiles")
|
||||||
|
assert query(backups[0], "PRAGMA integrity_check") == [("ok",)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_second_run_is_a_noop(tmp_path):
|
||||||
|
db = str(tmp_path / "old.db")
|
||||||
|
make_db(db, BASELINE_SQL)
|
||||||
|
migrations.run(db)
|
||||||
|
first = sha(db)
|
||||||
|
|
||||||
|
report = migrations.run(db)
|
||||||
|
|
||||||
|
assert report.applied == [] and report.backup is None
|
||||||
|
assert len(glob.glob(db + ".bak-*")) == 1
|
||||||
|
assert sha(db) == first
|
||||||
|
|
||||||
|
|
||||||
|
def test_too_new_database_is_not_touched(tmp_path):
|
||||||
|
db = str(tmp_path / "new.db")
|
||||||
|
make_db(db, BASELINE_SQL, ROWS_SQL + """
|
||||||
|
CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT);
|
||||||
|
INSERT INTO schema_migrations VALUES (9999, 'from the future', '2030-01-01T00:00:00Z');
|
||||||
|
""")
|
||||||
|
before = sha(db)
|
||||||
|
|
||||||
|
with pytest.raises(migrations.SchemaTooNew):
|
||||||
|
migrations.run(db)
|
||||||
|
with pytest.raises(migrations.SchemaTooNew):
|
||||||
|
migrations.startup(db)
|
||||||
|
|
||||||
|
assert sha(db) == before
|
||||||
|
assert glob.glob(db + ".bak-*") == []
|
||||||
|
assert len(query(db, "SELECT * FROM user_profiles")) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_fresh_database_gets_full_schema_without_backup(tmp_path):
|
||||||
|
db = str(tmp_path / "fresh.db")
|
||||||
|
|
||||||
|
report = migrations.run(db)
|
||||||
|
|
||||||
|
assert report.created and report.backup is None
|
||||||
|
assert glob.glob(db + ".bak-*") == []
|
||||||
|
assert {"note", "is_revoked"} <= set(columns(db, "user_profiles"))
|
||||||
|
assert {"public_ip", "mssfix"} <= set(columns(db, "system_settings"))
|
||||||
|
assert "ix_user_profiles_username" in [r[1] for r in query(db, "PRAGMA index_list(user_profiles)")]
|
||||||
|
assert query(db, "SELECT version FROM schema_migrations") == [(1,)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_auto_migrate_off_refuses_while_pending(tmp_path, monkeypatch):
|
||||||
|
db = str(tmp_path / "old.db")
|
||||||
|
make_db(db, BASELINE_SQL)
|
||||||
|
before = sha(db)
|
||||||
|
monkeypatch.setenv("OVPMON_AUTO_MIGRATE", "0")
|
||||||
|
|
||||||
|
with pytest.raises(migrations.MigrationPending, match="migrate.py"):
|
||||||
|
migrations.startup(db)
|
||||||
|
assert sha(db) == before
|
||||||
|
|
||||||
|
migrations.run(db)
|
||||||
|
migrations.startup(db) # up to date: allowed
|
||||||
|
|
||||||
|
|
||||||
|
def test_default_clause_from_model_defaults():
|
||||||
|
import models
|
||||||
|
t = models.SystemSettings.__table__.c
|
||||||
|
assert migrations._default_clause(t.split_routes) == " DEFAULT '[]'"
|
||||||
|
assert migrations._default_clause(t.duplicate_cn) == " DEFAULT 0"
|
||||||
|
assert migrations._default_clause(t.port) == " DEFAULT 1194"
|
||||||
|
assert migrations._default_clause(t.protocol) == " DEFAULT 'udp'"
|
||||||
|
assert migrations._default_clause(t.tun_mtu) == ""
|
||||||
|
assert migrations._default_clause(models.UserProfile.__table__.c.created_at) == ""
|
||||||
@@ -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
|
||||||
@@ -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"]
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import importlib
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from utils.secret_key import resolve_secret_key, SecretKeyError
|
||||||
|
|
||||||
|
GOOD = "0123456789abcdef" * 4 # 64 hex characters
|
||||||
|
|
||||||
|
|
||||||
|
def test_weak_or_missing_key_is_refused():
|
||||||
|
for bad in (None, "", " ", "ovpmon-secret-change-me", "Change-Me-Please", "k" * 31):
|
||||||
|
with pytest.raises(SecretKeyError) as exc:
|
||||||
|
resolve_secret_key(bad, None)
|
||||||
|
assert "openssl rand -hex 32" in str(exc.value)
|
||||||
|
if bad and bad.strip():
|
||||||
|
assert bad not in str(exc.value) # the key value is never part of the message
|
||||||
|
# the same checks apply to the config.ini value
|
||||||
|
with pytest.raises(SecretKeyError):
|
||||||
|
resolve_secret_key(None, "ovpmon-secret-change-me")
|
||||||
|
# legacy variable name is called out explicitly
|
||||||
|
with pytest.raises(SecretKeyError) as exc:
|
||||||
|
resolve_secret_key(None, "", legacy_env=GOOD)
|
||||||
|
assert "OVPMON_SECRET_KEY" in str(exc.value) and "OVPMON_API_SECRET_KEY" in str(exc.value)
|
||||||
|
assert GOOD not in str(exc.value)
|
||||||
|
|
||||||
|
|
||||||
|
def test_good_key_and_priority():
|
||||||
|
assert resolve_secret_key(GOOD, None) == (GOOD, "environment")
|
||||||
|
assert resolve_secret_key(None, GOOD) == (GOOD, "config.ini")
|
||||||
|
# environment wins over config.ini, even when the config.ini value is the old default
|
||||||
|
assert resolve_secret_key(GOOD, "ovpmon-secret-change-me") == (GOOD, "environment")
|
||||||
|
|
||||||
|
|
||||||
|
def test_auth_import_fails_closed(monkeypatch):
|
||||||
|
# Fresh import each time; the original module is restored in sys.modules after the test
|
||||||
|
monkeypatch.delitem(sys.modules, "utils.auth", raising=False)
|
||||||
|
monkeypatch.setenv("OVPMON_API_SECRET_KEY", "ovpmon-secret-change-me")
|
||||||
|
with pytest.raises(SystemExit) as exc:
|
||||||
|
importlib.import_module("utils.auth")
|
||||||
|
assert exc.value.code == 1
|
||||||
|
|
||||||
|
monkeypatch.delitem(sys.modules, "utils.auth", raising=False)
|
||||||
|
monkeypatch.setenv("OVPMON_API_SECRET_KEY", GOOD)
|
||||||
|
assert importlib.import_module("utils.auth").SECRET_KEY == GOOD
|
||||||
@@ -1,33 +1,27 @@
|
|||||||
|
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 fastapi.testclient import TestClient
|
||||||
from main import app
|
from main import app
|
||||||
import sys
|
from utils.auth import verify_token
|
||||||
import os
|
|
||||||
|
|
||||||
# Add project root to sys.path
|
|
||||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
|
||||||
|
|
||||||
|
app.dependency_overrides[verify_token] = lambda: {"sub": "test"}
|
||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
|
|
||||||
|
|
||||||
def test_get_stats():
|
def test_get_stats():
|
||||||
response = client.get("/server/process/stats")
|
response = client.get("/api/server/process/stats")
|
||||||
print(f"Stats response status: {response.status_code}")
|
|
||||||
print(f"Stats response body: {response.json()}")
|
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
data = response.json()
|
data = response.json()
|
||||||
assert "pid" in data
|
assert "pid" in data
|
||||||
assert "cpu_percent" in data
|
assert "cpu_percent" in data
|
||||||
assert "memory_mb" in data
|
assert "memory_mb" in data
|
||||||
|
|
||||||
def test_control_invalid():
|
|
||||||
response = client.post("/server/process/invalid_action")
|
|
||||||
print(f"Invalid action response: {response.status_code}")
|
|
||||||
assert response.status_code == 400
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
def test_control_invalid():
|
||||||
print("Running API tests...")
|
response = client.post("/api/server/process/invalid_action")
|
||||||
try:
|
assert response.status_code == 400
|
||||||
test_get_stats()
|
|
||||||
test_control_invalid()
|
|
||||||
print("Tests passed!")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"Tests failed: {e}")
|
|
||||||
+18
-16
@@ -1,29 +1,31 @@
|
|||||||
import jwt
|
import jwt
|
||||||
import configparser
|
import logging
|
||||||
import os
|
import os
|
||||||
from fastapi import Header, HTTPException, status
|
from fastapi import Header, HTTPException, status
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from .config import get_config_value
|
from .config import get_config_value
|
||||||
|
from .secret_key import resolve_secret_key, SecretKeyError
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def get_secret_key():
|
def get_secret_key():
|
||||||
# Use consistent OVPMON_API_SECRET_KEY as primary source
|
"""JWT signing key: OVPMON_API_SECRET_KEY, else [api] secret_key of config.ini. No built-in default."""
|
||||||
key = get_config_value('api', 'secret_key', fallback='ovpmon-secret-change-me')
|
try:
|
||||||
|
# get_config_value returns the environment value first, then the config.ini value
|
||||||
if key == 'ovpmon-secret-change-me':
|
key, source = resolve_secret_key(
|
||||||
print("[AUTH] WARNING: Using default fallback SECRET_KEY")
|
os.getenv('OVPMON_API_SECRET_KEY'),
|
||||||
else:
|
get_config_value('api', 'secret_key'),
|
||||||
# Check if it was from env (get_config_value prioritizes env)
|
os.getenv('OVPMON_SECRET_KEY'))
|
||||||
import os
|
except SecretKeyError as e:
|
||||||
if os.getenv('OVPMON_API_SECRET_KEY'):
|
logger.critical(f"Refusing to start: {e}")
|
||||||
print("[AUTH] Using SECRET_KEY from OVPMON_API_SECRET_KEY environment variable")
|
raise SystemExit(1)
|
||||||
elif os.getenv('OVPMON_SECRET_KEY'):
|
logger.info(f"JWT secret key loaded from {source}")
|
||||||
print("[AUTH] Using SECRET_KEY from OVPMON_SECRET_KEY environment variable")
|
|
||||||
else:
|
|
||||||
print("[AUTH] SECRET_KEY loaded (config.ini or fallback)")
|
|
||||||
|
|
||||||
return key
|
return key
|
||||||
|
|
||||||
|
|
||||||
|
# Fails the import (and so the uvicorn start, exit code 1) when the key is missing or weak
|
||||||
SECRET_KEY = get_secret_key()
|
SECRET_KEY = get_secret_key()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
from services import pki
|
||||||
|
|
||||||
|
|
||||||
|
def forbid_during_restore():
|
||||||
|
"""Dependency of the routes that change the PKI, the profiles or the settings: 409 while a
|
||||||
|
backup restore replaces them."""
|
||||||
|
if pki.is_restore_running():
|
||||||
|
raise HTTPException(status_code=409, detail=pki.RESTORE_RUNNING_MSG)
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"""JWT signing key rule (fail closed). Identical copy lives in APP_CORE/secret_key.py."""
|
||||||
|
|
||||||
|
ENV_NAME = "OVPMON_API_SECRET_KEY"
|
||||||
|
LEGACY_ENV_NAME = "OVPMON_SECRET_KEY"
|
||||||
|
DEFAULT_KEY = "ovpmon-secret-change-me"
|
||||||
|
MIN_LENGTH = 32
|
||||||
|
|
||||||
|
HOW_TO_FIX = f"Generate one with: openssl rand -hex 32, and set it in {ENV_NAME} (or [api] secret_key in config.ini)."
|
||||||
|
|
||||||
|
|
||||||
|
class SecretKeyError(Exception):
|
||||||
|
"""The signing key is missing or weak. The message never contains the key value."""
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_secret_key(env, ini_value, legacy_env=None):
|
||||||
|
"""Return (key, source) where source is "environment" or "config.ini".
|
||||||
|
|
||||||
|
env: value of OVPMON_API_SECRET_KEY (or None); ini_value: [api] secret_key (or None);
|
||||||
|
legacy_env: value of OVPMON_SECRET_KEY (not used by the application, only for the hint).
|
||||||
|
Priority: environment > config.ini. Raises SecretKeyError; does not log or exit.
|
||||||
|
"""
|
||||||
|
if env is not None:
|
||||||
|
key, source = env, f"environment variable {ENV_NAME}"
|
||||||
|
result_source = "environment"
|
||||||
|
else:
|
||||||
|
key, source = ini_value, "[api] secret_key in config.ini"
|
||||||
|
result_source = "config.ini"
|
||||||
|
|
||||||
|
if key is None or not key.strip():
|
||||||
|
msg = f"JWT secret key is not set (checked {ENV_NAME} and [api] secret_key in config.ini)."
|
||||||
|
if legacy_env is not None and legacy_env.strip():
|
||||||
|
msg += (f" {LEGACY_ENV_NAME} is set but is not used by the application: "
|
||||||
|
f"rename it to {ENV_NAME}.")
|
||||||
|
raise SecretKeyError(f"{msg} {HOW_TO_FIX}")
|
||||||
|
|
||||||
|
lowered = key.strip().lower()
|
||||||
|
if lowered == DEFAULT_KEY or "change-me" in lowered or "changeme" in lowered:
|
||||||
|
raise SecretKeyError(f"JWT secret key from {source} is a placeholder/default value. {HOW_TO_FIX}")
|
||||||
|
if len(key) < MIN_LENGTH:
|
||||||
|
raise SecretKeyError(f"JWT secret key from {source} is too short "
|
||||||
|
f"({len(key)} characters, at least {MIN_LENGTH} required). {HOW_TO_FIX}")
|
||||||
|
return key, result_source
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
.vscode
|
||||||
|
.git
|
||||||
|
*.bak
|
||||||
|
*.log
|
||||||
+12
-4
@@ -2,14 +2,22 @@
|
|||||||
FROM node:20-alpine AS build-stage
|
FROM node:20-alpine AS build-stage
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
RUN npm install
|
RUN npm ci
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
# Stage 2: Serve
|
# Stage 2: Serve
|
||||||
FROM nginx:alpine
|
# nginx runs as the unprivileged user "nginx" (uid 101) and listens on 8080 (OVP_UI_PORT); docker-compose publishes
|
||||||
|
# it as the host port (OVPMON_HTTP_PORT, default 80). The image entrypoint renders the template into
|
||||||
|
# /etc/nginx/conf.d. Behind another proxy or Kubernetes: target port 8080.
|
||||||
|
FROM nginxinc/nginx-unprivileged:alpine
|
||||||
COPY --from=build-stage /app/dist /usr/share/nginx/html
|
COPY --from=build-stage /app/dist /usr/share/nginx/html
|
||||||
COPY default.conf.template /etc/nginx/templates/default.conf.template
|
COPY default.conf.template /etc/nginx/templates/default.conf.template
|
||||||
EXPOSE 80
|
# Validates OVP_CSP_CONNECT_EXTRA before the template is rendered (20-envsubst-on-templates.sh)
|
||||||
|
COPY check-csp-connect-extra.sh /docker-entrypoint.d/15-check-csp-connect-extra.sh
|
||||||
|
# envsubst replaces only variables that are defined, so the defaults must exist.
|
||||||
|
# OVP_CSP_CONNECT_EXTRA: extra connect-src origins of the CSP, separated by spaces (empty: same origin only)
|
||||||
|
ENV OVP_UI_PORT=8080 \
|
||||||
|
OVP_CSP_CONNECT_EXTRA=""
|
||||||
|
EXPOSE 8080
|
||||||
CMD ["nginx", "-g", "daemon off;"]
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
|
|
||||||
+21
-9
@@ -1,25 +1,37 @@
|
|||||||
# OpenVPN Dashboard UI (`APP_UI`)
|
# OpenVPN Controller UI (`APP_UI`)
|
||||||
|
|
||||||
A Single Page Application (SPA) built with **Vue 3** and **Vite**. It serves as the unified dashboard for monitoring and management.
|
A Single Page Application (SPA) built with **Vue 3** and **Vite**. It serves as the unified dashboard for monitoring and management.
|
||||||
|
|
||||||
## Project Structure
|
## Project Structure
|
||||||
|
|
||||||
- `src/views/`: Page components (Dashboard, Login, Profiles, etc.).
|
- `src/views/`: Pages (Analytics, Clients, Certificates, PKI and VPN configuration, Server Process, Backup and Restore, Account, Login).
|
||||||
- `src/components/`: Reusable widgets (Charts, Sidebar).
|
- `src/components/`: Reusable widgets (`BaseModal`, `ConfirmModal`, `StatusBadge`, toasts, dialogs).
|
||||||
- `src/stores/`: Pinia state management (Auth, Client Data).
|
- `src/composables/`: Shared logic: `useApi` (axios clients: monitoring API, profiler API, `/api/auth`), `useTrafficChart` (charts), `useTheme`, `useToast`, `useFormatters`, `usePkiStatus`.
|
||||||
|
- `src/utils/`: Helpers without Vue (CIDR parsing).
|
||||||
|
- `default.conf.template`: nginx configuration of the container image (security headers, one CSP, gzip, cache, API proxy).
|
||||||
|
- `Dockerfile`: build and `nginxinc/nginx-unprivileged:alpine` image (user `nginx`, port 8080); `check-csp-connect-extra.sh`: validation of `OVP_CSP_CONNECT_EXTRA`, runs at container start.
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
Runtime configuration is loaded from `/config.json` (in `public/`) to allow environment-independent builds.
|
Runtime configuration is loaded from `/config.json` (in `public/`) to allow environment-independent builds. With the container nginx the CSP allows requests to the page origin only (`connect-src 'self'`): keep the API paths proxied (`/api/v1`, `/profiles-api`). To call an API on another origin, set `OVPMON_CSP_CONNECT_EXTRA` (origins separated by spaces; see [Containers reference](../DOCS/Deployment/Containers/Reference.md)). The `app-ui` container listens on 8080 (`OVP_UI_PORT`) as the unprivileged user `nginx`; compose publishes it as `OVPMON_HTTP_PORT` (default 80).
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install
|
npm ci # exact versions from package-lock.json (npm install after changing package.json)
|
||||||
npm run dev
|
npm run dev # http://localhost:5173
|
||||||
# Access at http://localhost:5173
|
npm run build
|
||||||
|
npm test # Vitest: formatters, CIDR parsing, 401 handling
|
||||||
|
npm run lint # ESLint (minimal Vue rules)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Node 20.19 or newer is required (Vite 7).
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
- The session token is kept in `localStorage` (accepted risk, see `DOCS/General/Security_Architecture.md`).
|
||||||
|
- Confirmations use `ConfirmModal`, notices use toasts (`useToast`); the native `confirm()` and SweetAlert2 are not used.
|
||||||
|
- After changing the UI sources, refresh the committed build for system-service installs: `deploy/native/build-ui.sh --publish` (`deploy/native/check-ui.sh` shows whether it is stale).
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
See `DOCS/UI/Architecture.md` for detailed architecture notes.
|
See `DOCS/UI/Architecture.md` for detailed architecture notes.
|
||||||
|
|
||||||
Executable
+51
@@ -0,0 +1,51 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Validates OVP_CSP_CONNECT_EXTRA: extra origins for the connect-src directive of the Content-Security-Policy
|
||||||
|
# (compose: OVPMON_CSP_CONNECT_EXTRA). The value ends up in a response header, so only origins are accepted:
|
||||||
|
# empty, or https://host[:port] and http://host[:port] separated by spaces (host: letters, digits, dots, hyphens;
|
||||||
|
# no path, quotes, ; or commas). Anything else could inject another CSP directive.
|
||||||
|
#
|
||||||
|
# Runs as /docker-entrypoint.d/15-check-csp-connect-extra.sh in the app-ui image (before the template is
|
||||||
|
# rendered by 20-envsubst-on-templates.sh) and from the all-in-one entrypoint. Exit code 1 stops the container.
|
||||||
|
# The same rule is in deploy/docker/lib.sh and deploy/native/lib.sh (csp_extra_problem): keep them in step.
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
csp_extra_problem() {
|
||||||
|
local _t _rest _host _port
|
||||||
|
[ -n "$1" ] || return 0
|
||||||
|
case "$1" in
|
||||||
|
*[!A-Za-z0-9.:/\ -]*)
|
||||||
|
printf 'contains characters that are not allowed (only letters, digits, . - : / and spaces; no quotes, ; or commas)'; return 1 ;;
|
||||||
|
" "*|*" ")
|
||||||
|
printf 'starts or ends with a space'; return 1 ;;
|
||||||
|
esac
|
||||||
|
set -f
|
||||||
|
for _t in $1; do
|
||||||
|
case "$_t" in
|
||||||
|
https://*) _rest=${_t#https://} ;;
|
||||||
|
http://*) _rest=${_t#http://} ;;
|
||||||
|
*) set +f; printf "'%s' is not an origin (use https://host[:port] or http://host[:port])" "$_t"; return 1 ;;
|
||||||
|
esac
|
||||||
|
_host=${_rest%%:*}
|
||||||
|
_port=""
|
||||||
|
case "$_rest" in *:*) _port=${_rest#*:} ;; esac
|
||||||
|
case "$_host" in
|
||||||
|
""|*[!A-Za-z0-9.-]*) set +f; printf "'%s' has an invalid host (letters, digits, dots and hyphens; no path)" "$_t"; return 1 ;;
|
||||||
|
esac
|
||||||
|
if [ -n "$_port" ]; then
|
||||||
|
case "$_port" in
|
||||||
|
*[!0-9]*) set +f; printf "'%s' has an invalid port (digits only, no path)" "$_t"; return 1 ;;
|
||||||
|
esac
|
||||||
|
if [ "${#_port}" -gt 5 ] || [ "$_port" -lt 1 ] || [ "$_port" -gt 65535 ]; then
|
||||||
|
set +f; printf "'%s' has a port out of range" "$_t"; return 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
case "$_rest" in *:) set +f; printf "'%s' has an empty port" "$_t"; return 1 ;; esac
|
||||||
|
done
|
||||||
|
set +f
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
if ! _reason=$(csp_extra_problem "${OVP_CSP_CONNECT_EXTRA:-}"); then
|
||||||
|
echo "check-csp-connect-extra: OVPMON_CSP_CONNECT_EXTRA is invalid: $_reason. Use origins https://host[:port] or http://host[:port] separated by spaces, or leave it empty" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
@@ -1,21 +1,58 @@
|
|||||||
server {
|
server {
|
||||||
listen 80;
|
listen ${OVP_UI_PORT};
|
||||||
server_name localhost;
|
server_name localhost;
|
||||||
|
server_tokens off;
|
||||||
|
|
||||||
root /usr/share/nginx/html;
|
root /usr/share/nginx/html;
|
||||||
index index.html;
|
index index.html;
|
||||||
|
|
||||||
|
# Security headers. add_header in a location replaces the ones inherited from the server block,
|
||||||
|
# so the /assets/ location below repeats them. CSP: the bundle is served from this origin only;
|
||||||
|
# style-src 'unsafe-inline' is needed by Bootstrap and Chart.js (inline style attributes).
|
||||||
|
# connect-src is 'self' plus OVP_CSP_CONNECT_EXTRA (origins separated by spaces, empty by default): set it
|
||||||
|
# only when config.json points the UI to an API on another origin (the defaults /api/v1 and /profiles-api are
|
||||||
|
# proxied below, same origin). The value is validated by the deploy scripts and by the all-in-one entrypoint.
|
||||||
|
# One policy ($csp) for both places.
|
||||||
|
set $csp "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self' ${OVP_CSP_CONNECT_EXTRA}; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'";
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header X-Frame-Options "DENY" always;
|
||||||
|
add_header Referrer-Policy "no-referrer" always;
|
||||||
|
add_header Content-Security-Policy $csp always;
|
||||||
|
|
||||||
|
gzip on;
|
||||||
|
gzip_vary on;
|
||||||
|
gzip_min_length 1024;
|
||||||
|
gzip_types text/plain text/css text/javascript application/javascript application/json image/svg+xml;
|
||||||
|
|
||||||
location / {
|
location / {
|
||||||
try_files $uri $uri/ /index.html;
|
try_files $uri $uri/ /index.html;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Hashed build files never change under the same name
|
||||||
|
location /assets/ {
|
||||||
|
try_files $uri =404;
|
||||||
|
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header X-Frame-Options "DENY" always;
|
||||||
|
add_header Referrer-Policy "no-referrer" always;
|
||||||
|
add_header Content-Security-Policy $csp always;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The entry page and the runtime configuration must be revalidated after an update
|
||||||
|
# (expires -1 sends "Cache-Control: no-cache" and keeps the server-level headers)
|
||||||
|
location = /index.html {
|
||||||
|
expires -1;
|
||||||
|
}
|
||||||
|
location = /config.json {
|
||||||
|
expires -1;
|
||||||
|
}
|
||||||
|
|
||||||
# Модуль 1: Мониторинг (Flask, порт 5001)
|
# Модуль 1: Мониторинг (Flask, порт 5001)
|
||||||
location /api/ {
|
location /api/ {
|
||||||
proxy_pass http://${OVP_API_HOST}:${OVP_API_PORT};
|
proxy_pass http://${OVP_API_HOST}:${OVP_API_PORT};
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_pass_header Authorization;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# Модуль 2: Управление профилями (FastAPI, порт 8000)
|
# Модуль 2: Управление профилями (FastAPI, порт 8000)
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import js from '@eslint/js';
|
||||||
|
import pluginVue from 'eslint-plugin-vue';
|
||||||
|
import globals from 'globals';
|
||||||
|
|
||||||
|
// Minimal rules: recommended JS + essential Vue (real errors only, no style rules)
|
||||||
|
export default [
|
||||||
|
{ ignores: ['dist/**', 'node_modules/**'] },
|
||||||
|
js.configs.recommended,
|
||||||
|
...pluginVue.configs['flat/essential'],
|
||||||
|
{
|
||||||
|
files: ['**/*.{js,vue}'],
|
||||||
|
languageOptions: {
|
||||||
|
globals: { ...globals.browser }
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
'vue/multi-word-component-names': 'off', // views are named after their route
|
||||||
|
'no-unused-vars': ['warn', { args: 'none', caughtErrors: 'none' }]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
files: ['**/*.test.js', 'eslint.config.js', 'vite.config.js'],
|
||||||
|
languageOptions: {
|
||||||
|
globals: { ...globals.node }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
];
|
||||||
+1
-1
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
<link rel="icon" type="image/svg+xml" href="/logo.svg" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>OpenVPN Controller</title>
|
<title>OpenVPN Controller</title>
|
||||||
</head>
|
</head>
|
||||||
|
|||||||
Generated
+1594
-16
File diff suppressed because it is too large.
Load diff
+9
-4
@@ -6,7 +6,9 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview",
|
||||||
|
"test": "vitest run",
|
||||||
|
"lint": "eslint src"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fortawesome/fontawesome-free": "^7.1.0",
|
"@fortawesome/fontawesome-free": "^7.1.0",
|
||||||
@@ -14,13 +16,16 @@
|
|||||||
"bootstrap": "^5.3.8",
|
"bootstrap": "^5.3.8",
|
||||||
"chart.js": "^4.5.1",
|
"chart.js": "^4.5.1",
|
||||||
"qrcode.vue": "^3.6.0",
|
"qrcode.vue": "^3.6.0",
|
||||||
"sass": "^1.97.2",
|
|
||||||
"sweetalert2": "^11.26.17",
|
|
||||||
"vue": "^3.5.24",
|
"vue": "^3.5.24",
|
||||||
"vue-router": "^4.6.4"
|
"vue-router": "^4.6.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^10.0.1",
|
||||||
"@vitejs/plugin-vue": "^6.0.1",
|
"@vitejs/plugin-vue": "^6.0.1",
|
||||||
"vite": "^7.2.4"
|
"eslint": "^10.12.0",
|
||||||
|
"eslint-plugin-vue": "^10.11.1",
|
||||||
|
"globals": "^17.13.0",
|
||||||
|
"vite": "^7.2.4",
|
||||||
|
"vitest": "^3.2.4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1 +0,0 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
|
||||||
|
Before Width: | Height: | Size: 1.5 KiB |
+40
-24
@@ -13,7 +13,7 @@
|
|||||||
<aside v-if="isAuthenticated" class="sidebar" :class="{ 'compact': isCompact }">
|
<aside v-if="isAuthenticated" class="sidebar" :class="{ 'compact': isCompact }">
|
||||||
<div class="sidebar-header">
|
<div class="sidebar-header">
|
||||||
<img src="./assets/logo.svg" alt="OpenVPN" class="sidebar-brand-icon">
|
<img src="./assets/logo.svg" alt="OpenVPN" class="sidebar-brand-icon">
|
||||||
<span class="brand-text">VPN Controller</span>
|
<span class="brand-text">OpenVPN Controller</span>
|
||||||
|
|
||||||
<button class="btn btn-link text-muted d-md-none ms-auto" @click="isSidebarOpen = false">
|
<button class="btn btn-link text-muted d-md-none ms-auto" @click="isSidebarOpen = false">
|
||||||
<i class="fas fa-times"></i>
|
<i class="fas fa-times"></i>
|
||||||
@@ -24,7 +24,6 @@
|
|||||||
|
|
||||||
<!-- SECTION: MONITORING -->
|
<!-- SECTION: MONITORING -->
|
||||||
<div class="nav-section-header">MONITORING</div>
|
<div class="nav-section-header">MONITORING</div>
|
||||||
<p></p>
|
|
||||||
<router-link to="/" class="nav-link" active-class="active" title="Analytics">
|
<router-link to="/" class="nav-link" active-class="active" title="Analytics">
|
||||||
<i class="fas fa-chart-line"></i> <span>Analytics</span>
|
<i class="fas fa-chart-line"></i> <span>Analytics</span>
|
||||||
</router-link>
|
</router-link>
|
||||||
@@ -34,27 +33,31 @@
|
|||||||
|
|
||||||
<!-- SECTION: CONFIGURATION -->
|
<!-- SECTION: CONFIGURATION -->
|
||||||
<div class="nav-section-header mt-3">CONFIGURATION</div>
|
<div class="nav-section-header mt-3">CONFIGURATION</div>
|
||||||
<p></p>
|
|
||||||
<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>
|
||||||
<p></p>
|
|
||||||
<router-link to="/certificates" class="nav-link" active-class="active" title="Certificates">
|
<router-link to="/certificates" class="nav-link" active-class="active" title="Certificates">
|
||||||
<i class="fas fa-certificate"></i> <span>Certificates</span>
|
<i class="fas fa-certificate"></i> <span>Certificates</span>
|
||||||
</router-link>
|
</router-link>
|
||||||
<router-link to="/server" class="nav-link" active-class="active" title="Server Process">
|
<router-link to="/server" class="nav-link" active-class="active" title="Server Process">
|
||||||
<i class="fas fa-terminal"></i> <span>Server Process</span>
|
<i class="fas fa-terminal"></i> <span>Server Process</span>
|
||||||
</router-link>
|
</router-link>
|
||||||
|
<router-link to="/backup" class="nav-link" active-class="active" title="Backup and Restore">
|
||||||
|
<i class="fas fa-box-archive"></i> <span>Backup and Restore</span>
|
||||||
|
</router-link>
|
||||||
|
|
||||||
<!-- SECTION: ACCOUNT -->
|
<!-- SECTION: ACCOUNT -->
|
||||||
<div class="nav-section-header mt-3">ACCOUNT</div>
|
<div class="nav-section-header mt-3">ACCOUNT</div>
|
||||||
<p></p>
|
|
||||||
<router-link to="/account" class="nav-link" active-class="active" title="Account Settings">
|
<router-link to="/account" class="nav-link" active-class="active" title="Account Settings">
|
||||||
<i class="fas fa-user-cog"></i> <span>Account Settings</span>
|
<i class="fas fa-user-cog"></i> <span>Account Settings</span>
|
||||||
</router-link>
|
</router-link>
|
||||||
@@ -89,10 +92,10 @@
|
|||||||
<i class="fas fa-globe me-1 text-muted"></i>{{ timezoneAbbr }}
|
<i class="fas fa-globe me-1 text-muted"></i>{{ timezoneAbbr }}
|
||||||
</span>
|
</span>
|
||||||
<button class="btn-header" @click="toggleTheme" title="Toggle Theme">
|
<button class="btn-header" @click="toggleTheme" title="Toggle Theme">
|
||||||
<i class="fas" :class="isDark ? 'fa-sun' : 'fa-moon'" id="themeIcon"></i>
|
<i class="fas" :class="isDark ? 'fa-sun' : 'fa-moon'"></i>
|
||||||
</button>
|
</button>
|
||||||
<button class="btn-header me-2" @click="refreshPage" title="Refresh">
|
<button class="btn-header me-2" @click="refreshPage" title="Refresh">
|
||||||
<i class="fas fa-sync-alt" id="refreshIcon"></i>
|
<i class="fas fa-sync-alt"></i>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<div class="header-divider d-none d-md-block"></div>
|
<div class="header-divider d-none d-md-block"></div>
|
||||||
@@ -118,6 +121,9 @@
|
|||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Shared toasts: outside the v-if/v-else pair so they also work on the Login page -->
|
||||||
|
<ToastContainer />
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
@@ -125,18 +131,28 @@ import { ref, onMounted, watch, computed } from 'vue';
|
|||||||
import { useAppConfig } from './composables/useAppConfig';
|
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 { usePkiStatus } from './composables/usePkiStatus';
|
||||||
|
import { useToast } from './composables/useToast';
|
||||||
|
import { useTheme } from './composables/useTheme';
|
||||||
|
|
||||||
const { loadConfig, isLoaded } = useAppConfig();
|
const { loadConfig, isLoaded } = useAppConfig();
|
||||||
const { apiClient } = useApi();
|
const { apiClient } = useApi();
|
||||||
const timezoneAbbr = ref(new Date().toLocaleTimeString('en-us',{timeZoneName:'short'}).split(' ')[2] || 'UTC');
|
const timezoneAbbr = ref(new Date().toLocaleTimeString('en-us',{timeZoneName:'short'}).split(' ')[2] || 'UTC');
|
||||||
const isDark = ref(false);
|
const { isDark, toggleTheme } = useTheme();
|
||||||
const refreshKey = ref(0);
|
const refreshKey = ref(0);
|
||||||
const isSidebarOpen = ref(false);
|
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');
|
// Signed in: a stored token on a non-public page (the token is not reactive: it is re-read on every navigation)
|
||||||
|
const isAuthenticated = computed(() => {
|
||||||
|
void route.fullPath;
|
||||||
|
return !route.meta.public && !!localStorage.getItem('ovpmon_token');
|
||||||
|
});
|
||||||
const username = ref(localStorage.getItem('ovpmon_user') || '');
|
const username = ref(localStorage.getItem('ovpmon_user') || '');
|
||||||
|
|
||||||
// Keep the header name in sync with the server (login, rename, stale session)
|
// Keep the header name in sync with the server (login, rename, stale session)
|
||||||
@@ -156,19 +172,18 @@ 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');
|
||||||
router.push('/login');
|
router.push('/login');
|
||||||
};
|
};
|
||||||
|
|
||||||
const toggleTheme = () => {
|
|
||||||
isDark.value = !isDark.value;
|
|
||||||
const theme = isDark.value ? 'dark' : 'light';
|
|
||||||
document.documentElement.setAttribute('data-theme', theme);
|
|
||||||
localStorage.setItem('theme', theme);
|
|
||||||
};
|
|
||||||
|
|
||||||
const toggleSidebar = () => {
|
const toggleSidebar = () => {
|
||||||
isCompact.value = !isCompact.value;
|
isCompact.value = !isCompact.value;
|
||||||
localStorage.setItem('sidebarCompact', isCompact.value);
|
localStorage.setItem('sidebarCompact', isCompact.value);
|
||||||
@@ -181,18 +196,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 (isAuthenticated.value) {
|
||||||
|
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 (isAuthenticated.value) {
|
||||||
|
syncUsername();
|
||||||
// Init Theme
|
refreshPkiStatus();
|
||||||
const savedTheme = localStorage.getItem('theme') || 'light';
|
}
|
||||||
isDark.value = savedTheme === 'dark';
|
|
||||||
document.documentElement.setAttribute('data-theme', savedTheme);
|
|
||||||
|
|
||||||
// Init Sidebar
|
// Init Sidebar
|
||||||
const savedCompact = localStorage.getItem('sidebarCompact');
|
const savedCompact = localStorage.getItem('sidebarCompact');
|
||||||
|
|||||||
+245
-25
@@ -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;
|
||||||
@@ -262,6 +272,11 @@ body {
|
|||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Space between a section header and its first link (also kept when the header is hidden in compact mode) */
|
||||||
|
.nav-section-header + .nav-link {
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
/* Compact Mode Styles */
|
/* Compact Mode Styles */
|
||||||
.sidebar.compact {
|
.sidebar.compact {
|
||||||
width: 64px;
|
width: 64px;
|
||||||
@@ -1616,42 +1631,169 @@ input[type="number"].config-input {
|
|||||||
appearance: textfield;
|
appearance: textfield;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Messages / Toast */
|
/* Toast notifications (ToastContainer.vue) */
|
||||||
.toast-message {
|
:root {
|
||||||
padding: 14px 22px;
|
--toast-success: #1a7f37;
|
||||||
border-radius: 6px;
|
--toast-warning: #9a6700;
|
||||||
font-size: 14px;
|
--toast-error: #cf222e;
|
||||||
font-weight: 500;
|
--toast-info: #0969da;
|
||||||
margin-bottom: 20px;
|
--toast-shadow: 0 8px 24px rgba(31, 35, 40, 0.14), 0 1px 3px rgba(31, 35, 40, 0.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-theme="dark"] {
|
||||||
|
--toast-success: #3fb950;
|
||||||
|
--toast-warning: #d29922;
|
||||||
|
--toast-error: #f85149;
|
||||||
|
--toast-info: #58a6ff;
|
||||||
|
--toast-shadow: 0 8px 24px rgba(1, 4, 9, 0.6), 0 0 0 1px rgba(240, 246, 252, 0.04);
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-stack {
|
||||||
|
position: fixed;
|
||||||
|
right: 20px;
|
||||||
|
bottom: 20px;
|
||||||
|
z-index: 2000; /* above Bootstrap modals (1055) and backdrop (1050) */
|
||||||
|
width: 380px;
|
||||||
|
max-width: calc(100vw - 32px);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-stack-list {
|
||||||
|
position: relative;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
flex-direction: column;
|
||||||
gap: 10px;
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-toast {
|
||||||
|
--toast-color: var(--toast-info);
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 12px;
|
||||||
|
width: 100%;
|
||||||
|
padding: 12px 10px 14px 14px;
|
||||||
|
overflow: hidden;
|
||||||
|
background: var(--bg-card);
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
border-left: 4px solid var(--toast-color);
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: var(--toast-shadow);
|
||||||
|
color: var(--text-main);
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.45;
|
||||||
|
pointer-events: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-toast-success { --toast-color: var(--toast-success); }
|
||||||
|
.app-toast-warning { --toast-color: var(--toast-warning); }
|
||||||
|
.app-toast-error { --toast-color: var(--toast-error); }
|
||||||
|
.app-toast-info { --toast-color: var(--toast-info); }
|
||||||
|
|
||||||
|
.app-toast-icon {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
margin-top: 2px;
|
||||||
|
font-size: 16px;
|
||||||
|
color: var(--toast-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-toast-text {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-width: 0;
|
||||||
|
color: var(--text-heading);
|
||||||
|
font-weight: 500;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-toast-close {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
width: 24px;
|
||||||
|
height: 24px;
|
||||||
|
padding: 0;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
background: transparent;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 4px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background-color 0.15s ease, color 0.15s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-toast-close:hover,
|
||||||
|
.app-toast-close:focus-visible {
|
||||||
|
background: var(--bg-element-hover);
|
||||||
|
color: var(--text-heading);
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-toast-progress {
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
height: 3px;
|
||||||
|
background: var(--toast-color);
|
||||||
|
opacity: 0.55;
|
||||||
|
transform-origin: left center;
|
||||||
|
animation: toast-progress linear forwards;
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-toast:hover .app-toast-progress {
|
||||||
|
animation-play-state: paused;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes toast-progress {
|
||||||
|
from { transform: scaleX(1); }
|
||||||
|
to { transform: scaleX(0); }
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-enter-active,
|
||||||
|
.toast-leave-active {
|
||||||
|
transition: transform 0.28s ease, opacity 0.28s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-leave-active {
|
||||||
|
position: absolute; /* keeps its place while siblings slide into the gap */
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-move {
|
||||||
|
transition: transform 0.28s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-enter-from {
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
transform: translateY(-10px);
|
transform: translateX(40px);
|
||||||
transition: all 0.3s ease;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.toast-message.show {
|
.toast-leave-to {
|
||||||
opacity: 1;
|
opacity: 0;
|
||||||
transform: translateY(0);
|
transform: translateX(20px);
|
||||||
}
|
}
|
||||||
|
|
||||||
.toast-success {
|
@media (max-width: 576px) {
|
||||||
background-color: #d1fae5;
|
.toast-stack {
|
||||||
color: #065f46;
|
right: 16px;
|
||||||
border-left: 4px solid #10b981;
|
left: 16px;
|
||||||
|
bottom: 16px;
|
||||||
|
width: auto;
|
||||||
|
max-width: none;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.toast-warning {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
background-color: #fef3c7;
|
.toast-enter-active,
|
||||||
color: #92400e;
|
.toast-leave-active,
|
||||||
border-left: 4px solid #f59e0b;
|
.toast-move {
|
||||||
|
transition: opacity 0.15s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
.toast-error {
|
.toast-enter-from,
|
||||||
background-color: #fee2e2;
|
.toast-leave-to {
|
||||||
color: #991b1b;
|
transform: none;
|
||||||
border-left: 4px solid #ef4444;
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Animations */
|
/* Animations */
|
||||||
@@ -1802,6 +1944,48 @@ input[type="number"].config-input {
|
|||||||
transform: scale(1.02);
|
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 */
|
/* Shared Utilities */
|
||||||
.cursor-pointer {
|
.cursor-pointer {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
@@ -1821,3 +2005,39 @@ input[type="number"].config-input {
|
|||||||
grid-column: span 1;
|
grid-column: span 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* --- BACKUP AND RESTORE PAGE --- */
|
||||||
|
.backup-page {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 24px;
|
||||||
|
padding: 40px 0;
|
||||||
|
background-color: var(--bg-body);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Same card as the configuration pages, wider for the tables */
|
||||||
|
.config-card.backup-card {
|
||||||
|
width: 960px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.backup-steps {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0 0 12px;
|
||||||
|
padding: 0;
|
||||||
|
color: var(--text-main);
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.backup-steps li {
|
||||||
|
padding: 3px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.backup-steps li i {
|
||||||
|
width: 22px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.backup-result {
|
||||||
|
padding: 6px 0;
|
||||||
|
border-top: 1px solid var(--border-subtle);
|
||||||
|
}
|
||||||
@@ -22,7 +22,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref, onMounted, onUnmounted } from 'vue';
|
import { ref, computed, onMounted, onUnmounted } from 'vue';
|
||||||
import { Modal } from 'bootstrap';
|
import { Modal } from 'bootstrap';
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
@@ -40,11 +40,11 @@ const props = defineProps({
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const emit = defineEmits(['close', 'opened', 'closed']);
|
const emit = defineEmits(['opened', 'closed']);
|
||||||
|
|
||||||
const modalRef = ref(null);
|
const modalRef = ref(null);
|
||||||
let bsModal = null;
|
let bsModal = null;
|
||||||
const sizeClass = props.size || '';
|
const sizeClass = computed(() => props.size || '');
|
||||||
|
|
||||||
const show = () => {
|
const show = () => {
|
||||||
bsModal?.show();
|
bsModal?.show();
|
||||||
@@ -63,7 +63,6 @@ onMounted(() => {
|
|||||||
|
|
||||||
modalRef.value.addEventListener('hidden.bs.modal', () => {
|
modalRef.value.addEventListener('hidden.bs.modal', () => {
|
||||||
emit('closed');
|
emit('closed');
|
||||||
emit('close');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<template>
|
<template>
|
||||||
<BaseModal id="confirmModal" :title="title" ref="modal">
|
<BaseModal :id="modalId" :title="title" ref="modal">
|
||||||
<template #body>
|
<template #body>
|
||||||
<p class="text-main">{{ message }}</p>
|
<p class="text-main" style="white-space: pre-line;">{{ message }}</p>
|
||||||
</template>
|
</template>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<button v-if="showCancel" type="button" class="btn-action btn-action-secondary" @click="close">Cancel</button>
|
<button v-if="showCancel" type="button" class="btn-action btn-action-secondary" @click="close">Cancel</button>
|
||||||
@@ -13,9 +13,11 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref } from 'vue';
|
import { ref, useId } from 'vue';
|
||||||
import BaseModal from './BaseModal.vue';
|
import BaseModal from './BaseModal.vue';
|
||||||
|
|
||||||
|
// Unique element id: several ConfirmModal instances may live on one page
|
||||||
|
const modalId = `confirm-${useId()}`;
|
||||||
const emit = defineEmits(['confirm']);
|
const emit = defineEmits(['confirm']);
|
||||||
const modal = ref(null);
|
const modal = ref(null);
|
||||||
|
|
||||||
|
|||||||
@@ -54,15 +54,12 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
|
import { ref, onMounted, onUnmounted } from 'vue';
|
||||||
import Chart from 'chart.js/auto';
|
|
||||||
import { useApi } from '../composables/useApi';
|
import { useApi } from '../composables/useApi';
|
||||||
import { useFormatters } from '../composables/useFormatters';
|
import { useTrafficChart } from '../composables/useTrafficChart';
|
||||||
import { Modal } from 'bootstrap';
|
import { Modal } from 'bootstrap';
|
||||||
|
|
||||||
const props = defineProps(['modelValue']); // If we wanted v-model control, but using manual open method for now
|
|
||||||
const { fetchClientHistory } = useApi();
|
const { fetchClientHistory } = useApi();
|
||||||
const { parseServerDate } = useFormatters();
|
|
||||||
|
|
||||||
const modalRef = ref(null);
|
const modalRef = ref(null);
|
||||||
const chartCanvas = ref(null);
|
const chartCanvas = ref(null);
|
||||||
@@ -71,10 +68,10 @@ const range = ref('24h');
|
|||||||
const isSpeedMode = ref(false);
|
const isSpeedMode = ref(false);
|
||||||
const loading = ref(false);
|
const loading = ref(false);
|
||||||
let bsModal = null;
|
let bsModal = null;
|
||||||
let chartInstance = null;
|
|
||||||
let cachedData = null;
|
let cachedData = null;
|
||||||
|
let requestId = 0; // the latest request wins: a slow answer for an old range or client is dropped
|
||||||
|
|
||||||
const MAX_CHART_POINTS = 48;
|
const chart = useTrafficChart(chartCanvas, { maxPoints: 48 });
|
||||||
|
|
||||||
const open = (name) => {
|
const open = (name) => {
|
||||||
clientName.value = name;
|
clientName.value = name;
|
||||||
@@ -90,159 +87,52 @@ const close = () => {
|
|||||||
|
|
||||||
const loadHistory = async () => {
|
const loadHistory = async () => {
|
||||||
if (!clientName.value) return;
|
if (!clientName.value) return;
|
||||||
|
const id = ++requestId;
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
try {
|
try {
|
||||||
const res = await fetchClientHistory(clientName.value, range.value);
|
const res = await fetchClientHistory(clientName.value, range.value);
|
||||||
|
if (id !== requestId) return;
|
||||||
if (res.success && res.data.history) {
|
if (res.success && res.data.history) {
|
||||||
cachedData = res.data.history;
|
// Map the raw fields to the point format of useTrafficChart
|
||||||
|
cachedData = res.data.history.map(p => ({
|
||||||
|
timestamp: p.timestamp,
|
||||||
|
bytes_received: p.bytes_received,
|
||||||
|
bytes_sent: p.bytes_sent,
|
||||||
|
rx_rate_mbps: p.bytes_received_rate_mbps,
|
||||||
|
tx_rate_mbps: p.bytes_sent_rate_mbps
|
||||||
|
}));
|
||||||
renderChart();
|
renderChart();
|
||||||
} else {
|
} else {
|
||||||
cachedData = [];
|
cachedData = [];
|
||||||
if (chartInstance) chartInstance.destroy();
|
chart.destroy();
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
if (id === requestId) console.error(e);
|
||||||
} finally {
|
} finally {
|
||||||
loading.value = false;
|
if (id === requestId) loading.value = false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const renderChart = () => {
|
const renderChart = () => {
|
||||||
if (!chartCanvas.value || !cachedData) return;
|
if (!cachedData) return;
|
||||||
if (chartInstance) chartInstance.destroy();
|
chart.render(cachedData, { range: range.value, speedMode: isSpeedMode.value });
|
||||||
|
|
||||||
const ctx = chartCanvas.value.getContext('2d');
|
|
||||||
const downsampled = downsampleData(cachedData, MAX_CHART_POINTS);
|
|
||||||
|
|
||||||
const labels = [];
|
|
||||||
const dataRx = [];
|
|
||||||
const dataTx = [];
|
|
||||||
|
|
||||||
downsampled.forEach(point => {
|
|
||||||
const d = parseServerDate(point.timestamp);
|
|
||||||
let label = '';
|
|
||||||
|
|
||||||
if(range.value.includes('h') || range.value === '1d') {
|
|
||||||
label = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
|
||||||
} else {
|
|
||||||
label = d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' +
|
|
||||||
d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
|
||||||
}
|
|
||||||
labels.push(label);
|
|
||||||
|
|
||||||
if (!isSpeedMode.value) {
|
|
||||||
dataRx.push(point.bytes_received / (1024 * 1024)); // MB
|
|
||||||
dataTx.push(point.bytes_sent / (1024 * 1024)); // MB
|
|
||||||
} else {
|
|
||||||
dataRx.push(point.bytes_received_rate_mbps);
|
|
||||||
dataTx.push(point.bytes_sent_rate_mbps);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
|
|
||||||
const gridColor = isDark ? 'rgba(240, 246, 252, 0.1)' : 'rgba(0,0,0,0.05)';
|
|
||||||
const textColor = isDark ? '#8b949e' : '#6c757d';
|
|
||||||
|
|
||||||
chartInstance = new Chart(ctx, {
|
|
||||||
type: 'line',
|
|
||||||
data: {
|
|
||||||
labels,
|
|
||||||
datasets: [
|
|
||||||
{
|
|
||||||
label: !isSpeedMode.value ? 'Received (MB)' : 'RX Mbps',
|
|
||||||
data: dataRx,
|
|
||||||
borderColor: '#1652B8', // OpenVPN Blue
|
|
||||||
backgroundColor: 'rgba(22, 82, 184, 0.15)',
|
|
||||||
borderWidth: 2,
|
|
||||||
fill: true,
|
|
||||||
tension: 0.3,
|
|
||||||
pointRadius: 3,
|
|
||||||
pointHoverRadius: 4
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: !isSpeedMode.value ? 'Sent (MB)' : 'TX Mbps',
|
|
||||||
data: dataTx,
|
|
||||||
borderColor: '#EC7C31', // OpenVPN Orange
|
|
||||||
backgroundColor: 'rgba(236, 124, 49, 0.15)',
|
|
||||||
borderWidth: 2,
|
|
||||||
fill: true,
|
|
||||||
tension: 0.3,
|
|
||||||
pointRadius: 3,
|
|
||||||
pointHoverRadius: 4
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
options: {
|
|
||||||
responsive: true,
|
|
||||||
maintainAspectRatio: false,
|
|
||||||
interaction: {
|
|
||||||
mode: 'index',
|
|
||||||
intersect: false,
|
|
||||||
},
|
|
||||||
plugins: {
|
|
||||||
legend: { labels: { color: textColor } }
|
|
||||||
},
|
|
||||||
scales: {
|
|
||||||
x: {
|
|
||||||
ticks: { color: textColor, maxTicksLimit: 8 },
|
|
||||||
grid: { color: gridColor }
|
|
||||||
},
|
|
||||||
y: {
|
|
||||||
beginAtZero: true,
|
|
||||||
ticks: { color: textColor },
|
|
||||||
grid: { color: gridColor }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const downsampleData = (data, maxPoints) => {
|
|
||||||
if (!data || data.length === 0) return [];
|
|
||||||
if (data.length <= maxPoints) return data;
|
|
||||||
|
|
||||||
const blockSize = Math.ceil(data.length / maxPoints);
|
|
||||||
const result = [];
|
|
||||||
|
|
||||||
for (let i = 0; i < data.length; i += blockSize) {
|
|
||||||
const chunk = data.slice(i, i + blockSize);
|
|
||||||
if (chunk.length === 0) continue;
|
|
||||||
|
|
||||||
let sumRx = 0, sumTx = 0;
|
|
||||||
let maxRxRate = 0, maxTxRate = 0;
|
|
||||||
|
|
||||||
chunk.forEach(pt => {
|
|
||||||
sumRx += (pt.bytes_received || 0);
|
|
||||||
sumTx += (pt.bytes_sent || 0);
|
|
||||||
maxRxRate = Math.max(maxRxRate, pt.bytes_received_rate_mbps || 0);
|
|
||||||
maxTxRate = Math.max(maxTxRate, pt.bytes_sent_rate_mbps || 0);
|
|
||||||
});
|
|
||||||
|
|
||||||
result.push({
|
|
||||||
timestamp: chunk[0].timestamp,
|
|
||||||
bytes_received: sumRx,
|
|
||||||
bytes_sent: sumTx,
|
|
||||||
bytes_received_rate_mbps: maxRxRate,
|
|
||||||
bytes_sent_rate_mbps: maxTxRate
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
bsModal = new Modal(modalRef.value);
|
bsModal = new Modal(modalRef.value);
|
||||||
|
|
||||||
// Clean up chart on close
|
// Clean up the chart on close and drop answers that are still on the way
|
||||||
modalRef.value.addEventListener('hidden.bs.modal', () => {
|
modalRef.value.addEventListener('hidden.bs.modal', () => {
|
||||||
if (chartInstance) {
|
requestId++;
|
||||||
chartInstance.destroy();
|
loading.value = false;
|
||||||
chartInstance = null;
|
cachedData = null;
|
||||||
}
|
chart.destroy();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
if (chartInstance) chartInstance.destroy();
|
requestId++;
|
||||||
|
bsModal?.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
defineExpose({ open, close });
|
defineExpose({ open, close });
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
<template>
|
<template>
|
||||||
<BaseModal id="newClientModal" title="Create New Client" ref="modal">
|
<BaseModal id="newClientModal" title="Create New Client" ref="modal" @opened="inputRef?.focus()">
|
||||||
<template #body>
|
<template #body>
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="clientName" class="form-label small text-muted text-uppercase fw-bold">Client Name</label>
|
<label for="clientName" class="form-label small text-muted text-uppercase fw-bold">Client Name</label>
|
||||||
<div class="input-group">
|
<div class="input-group">
|
||||||
<span class="input-group-text"><i class="fas fa-user"></i></span>
|
<span class="input-group-text"><i class="fas fa-user"></i></span>
|
||||||
<input type="text" class="form-control" id="clientName" v-model="clientName" placeholder="e.g. laptop-user" @keyup.enter="confirm" ref="inputRef">
|
<input type="text" class="form-control" :class="{ 'is-invalid': clientName && !isValid }" id="clientName"
|
||||||
|
v-model="clientName" placeholder="e.g. laptop-user" maxlength="64" autocomplete="off" @keyup.enter="confirm" ref="inputRef">
|
||||||
|
</div>
|
||||||
|
<div v-if="clientName && !isValid" class="text-danger small mt-2">
|
||||||
|
Letters, digits, dashes and underscores only; the first character must be a letter or a digit.
|
||||||
</div>
|
</div>
|
||||||
<div class="form-text mt-2 text-muted small">
|
<div class="form-text mt-2 text-muted small">
|
||||||
<i class="fas fa-info-circle me-1"></i> Use only alphanumeric characters, dashes, or underscores.
|
<i class="fas fa-info-circle me-1"></i> Use only alphanumeric characters, dashes, or underscores.
|
||||||
@@ -14,7 +18,7 @@
|
|||||||
</template>
|
</template>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<button type="button" class="btn-action btn-action-secondary" @click="close">Cancel</button>
|
<button type="button" class="btn-action btn-action-secondary" @click="close">Cancel</button>
|
||||||
<button type="button" class="btn-action btn-action-save" @click="confirm" :disabled="!clientName">
|
<button type="button" class="btn-action btn-action-save" @click="confirm" :disabled="!isValid">
|
||||||
Create Client
|
Create Client
|
||||||
</button>
|
</button>
|
||||||
</template>
|
</template>
|
||||||
@@ -22,7 +26,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref } from 'vue';
|
import { ref, computed } from 'vue';
|
||||||
import BaseModal from './BaseModal.vue';
|
import BaseModal from './BaseModal.vue';
|
||||||
|
|
||||||
const emit = defineEmits(['create']);
|
const emit = defineEmits(['create']);
|
||||||
@@ -30,10 +34,13 @@ const modal = ref(null);
|
|||||||
const clientName = ref('');
|
const clientName = ref('');
|
||||||
const inputRef = ref(null);
|
const inputRef = ref(null);
|
||||||
|
|
||||||
|
// Same rule as the profiler API (without dots): 1-64 characters, no leading dash or underscore
|
||||||
|
const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
||||||
|
const isValid = computed(() => NAME_RE.test(clientName.value));
|
||||||
|
|
||||||
const open = () => {
|
const open = () => {
|
||||||
clientName.value = '';
|
clientName.value = '';
|
||||||
modal.value.show();
|
modal.value.show(); // the input is focused on the opened event
|
||||||
setTimeout(() => inputRef.value?.focus(), 500);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const close = () => {
|
const close = () => {
|
||||||
@@ -41,7 +48,7 @@ const close = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const confirm = () => {
|
const confirm = () => {
|
||||||
if (clientName.value) {
|
if (isValid.value) {
|
||||||
emit('create', clientName.value);
|
emit('create', clientName.value);
|
||||||
close();
|
close();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
<template>
|
||||||
|
<BaseModal id="profileDetailsModal" title="Profile Details" ref="modal">
|
||||||
|
<template #header>
|
||||||
|
<div class="d-flex align-items-center gap-2 flex-wrap">
|
||||||
|
<h5 class="modal-title fw-bold mb-0" style="color: var(--text-heading);">{{ profile?.username }}</h5>
|
||||||
|
<StatusBadge v-if="profile" :profile="profile" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template #body>
|
||||||
|
<div v-if="profile">
|
||||||
|
<dl class="profile-meta">
|
||||||
|
<dt>Created</dt>
|
||||||
|
<dd>{{ formatDate(profile.created_at) }}</dd>
|
||||||
|
<dt>Expires</dt>
|
||||||
|
<dd>{{ formatDate(profile.expiration_date) }}<span v-if="daysLabel" class="text-muted"> ({{ daysLabel }})</span></dd>
|
||||||
|
<template v-if="profile.revoked_at">
|
||||||
|
<dt>Revoked</dt>
|
||||||
|
<dd>{{ formatDate(profile.revoked_at) }}</dd>
|
||||||
|
</template>
|
||||||
|
<dt>File</dt>
|
||||||
|
<dd class="certificate-file text-muted small text-break mt-0">{{ profile.file_path || 'N/A' }}</dd>
|
||||||
|
</dl>
|
||||||
|
|
||||||
|
<label for="profileNote" class="form-label small text-muted text-uppercase fw-bold">Note</label>
|
||||||
|
<textarea class="form-control" id="profileNote" rows="3" maxlength="1000" v-model="note" placeholder="Add a note about this profile..."></textarea>
|
||||||
|
<div class="form-text text-end">{{ note.length }} / 1000</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template #footer>
|
||||||
|
<button type="button" class="btn-action btn-action-secondary" @click="close">Close</button>
|
||||||
|
<button type="button" class="btn-action btn-action-save" @click="save" :disabled="!dirty">Save</button>
|
||||||
|
</template>
|
||||||
|
</BaseModal>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, computed } from 'vue';
|
||||||
|
import BaseModal from './BaseModal.vue';
|
||||||
|
import StatusBadge from './StatusBadge.vue';
|
||||||
|
|
||||||
|
const emit = defineEmits(['save']);
|
||||||
|
const modal = ref(null);
|
||||||
|
const profile = ref(null);
|
||||||
|
const note = ref('');
|
||||||
|
|
||||||
|
const dirty = computed(() => note.value !== (profile.value?.note || ''));
|
||||||
|
|
||||||
|
const daysLabel = computed(() => {
|
||||||
|
const days = profile.value?.days_remaining;
|
||||||
|
if (days == null) return '';
|
||||||
|
return days > 0 ? `${days} d` : 'expired';
|
||||||
|
});
|
||||||
|
|
||||||
|
// YYYY-MM-DD HH:mm (local time)
|
||||||
|
const formatDate = (dateStr) => {
|
||||||
|
if (!dateStr) return 'N/A';
|
||||||
|
const d = new Date(dateStr);
|
||||||
|
if (isNaN(d)) return dateStr;
|
||||||
|
const pad = (n) => String(n).padStart(2, '0');
|
||||||
|
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const open = (p) => {
|
||||||
|
profile.value = p;
|
||||||
|
note.value = p.note || '';
|
||||||
|
modal.value.show();
|
||||||
|
};
|
||||||
|
|
||||||
|
const close = () => {
|
||||||
|
modal.value.hide();
|
||||||
|
};
|
||||||
|
|
||||||
|
const save = () => {
|
||||||
|
emit('save', { id: profile.value.id, note: note.value });
|
||||||
|
close();
|
||||||
|
};
|
||||||
|
|
||||||
|
defineExpose({ open, close });
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<template>
|
||||||
|
<span class="status-badge" :class="badge.cls">
|
||||||
|
<i class="fas me-1" :class="badge.icon"></i>{{ badge.label }}
|
||||||
|
</span>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { computed } from 'vue';
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
// Profile as returned by GET /profiles
|
||||||
|
profile: {
|
||||||
|
type: Object,
|
||||||
|
required: true
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const badge = computed(() => {
|
||||||
|
const p = props.profile;
|
||||||
|
if (p.is_revoked) return { label: 'Revoked', cls: 'status-expired', icon: 'fa-ban' };
|
||||||
|
if (p.is_expired) return { label: 'Expired', cls: 'status-expired', icon: 'fa-times-circle' };
|
||||||
|
if (p.days_remaining != null && p.days_remaining <= 30) {
|
||||||
|
return { label: 'Expiring Soon', cls: 'status-warning', icon: 'fa-exclamation-triangle' };
|
||||||
|
}
|
||||||
|
return { label: 'Active', cls: 'status-valid', icon: 'fa-check-circle' };
|
||||||
|
});
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<template>
|
||||||
|
<div class="toast-stack">
|
||||||
|
<TransitionGroup name="toast" tag="div" class="toast-stack-list">
|
||||||
|
<div v-for="t in toasts" :key="t.id" class="app-toast" :class="'app-toast-' + t.type"
|
||||||
|
:role="t.type === 'error' ? 'alert' : 'status'"
|
||||||
|
:aria-live="t.type === 'error' ? 'assertive' : 'polite'" aria-atomic="true"
|
||||||
|
@mouseenter="pause(t.id)" @mouseleave="resume(t.id)">
|
||||||
|
<i class="fas app-toast-icon" :class="ICONS[t.type]" aria-hidden="true"></i>
|
||||||
|
<div class="app-toast-text">{{ t.text }}</div>
|
||||||
|
<button type="button" class="app-toast-close" aria-label="Close notification" @click="dismiss(t.id)">
|
||||||
|
<i class="fas fa-times" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
<div v-if="t.timeout > 0" class="app-toast-progress" :style="{ animationDuration: t.timeout + 'ms' }"></div>
|
||||||
|
</div>
|
||||||
|
</TransitionGroup>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { onBeforeUnmount } from 'vue';
|
||||||
|
import { useToast } from '../composables/useToast';
|
||||||
|
|
||||||
|
const { toasts, dismiss, pause, resume, clear } = useToast();
|
||||||
|
|
||||||
|
const ICONS = {
|
||||||
|
success: 'fa-check-circle',
|
||||||
|
warning: 'fa-exclamation-triangle',
|
||||||
|
error: 'fa-exclamation-circle',
|
||||||
|
info: 'fa-info-circle'
|
||||||
|
};
|
||||||
|
|
||||||
|
onBeforeUnmount(clear);
|
||||||
|
</script>
|
||||||
@@ -4,13 +4,35 @@ import { useAppConfig } from './useAppConfig';
|
|||||||
// Singleton instances
|
// Singleton instances
|
||||||
const apiClient = axios.create();
|
const apiClient = axios.create();
|
||||||
const profilesApiClient = axios.create();
|
const profilesApiClient = axios.create();
|
||||||
|
// Auth endpoints (/api/auth): login, 2FA, password and username changes
|
||||||
|
const authApiClient = axios.create();
|
||||||
|
|
||||||
// Helper to get base URLs
|
// Helper to get base URLs
|
||||||
const getBaseUrl = (config) => config?.api_base_url || 'http://localhost:5001/api/v1';
|
const getBaseUrl = (config) => config?.api_base_url || 'http://localhost:5001/api/v1';
|
||||||
const getProfilesBaseUrl = (config) => config?.profiles_api_base_url || 'http://localhost:8000';
|
const getProfilesBaseUrl = (config) => config?.profiles_api_base_url || 'http://localhost:8000';
|
||||||
|
// The auth routes sit next to the API root: /api/v1 -> /api/auth
|
||||||
|
const getAuthBaseUrl = (config) => {
|
||||||
|
const base = getBaseUrl(config).replace(/\/+$/, '');
|
||||||
|
return /\/v1$/.test(base) ? base.replace(/\/v1$/, '/auth') : base + '/../auth';
|
||||||
|
};
|
||||||
|
|
||||||
// Add interceptors to handle Auth and Dynamic Base URLs
|
// 401 on a regular API request: the session is gone, clear it and go to the login page
|
||||||
const setupInterceptors = (instance, getBase) => {
|
export const handleUnauthorized = (error) => {
|
||||||
|
if (error.response && error.response.status === 401) {
|
||||||
|
localStorage.removeItem('ovpmon_token');
|
||||||
|
localStorage.removeItem('ovpmon_user');
|
||||||
|
// Redirecting using window.location for absolute refresh
|
||||||
|
if (window.location.pathname !== '/login') {
|
||||||
|
window.location.href = '/login';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Promise.reject(error);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add interceptors to handle Auth and Dynamic Base URLs.
|
||||||
|
// endSessionOn401 is false for authApiClient: /auth/* answers 401 for a wrong current password or
|
||||||
|
// 2FA code (login, change-password, change-username). That is a form error, not an expired session.
|
||||||
|
const setupInterceptors = (instance, getBase, { endSessionOn401 = true } = {}) => {
|
||||||
instance.interceptors.request.use((reqConfig) => {
|
instance.interceptors.request.use((reqConfig) => {
|
||||||
const { config } = useAppConfig();
|
const { config } = useAppConfig();
|
||||||
reqConfig.baseURL = getBase(config.value);
|
reqConfig.baseURL = getBase(config.value);
|
||||||
@@ -22,24 +44,14 @@ const setupInterceptors = (instance, getBase) => {
|
|||||||
return reqConfig;
|
return reqConfig;
|
||||||
});
|
});
|
||||||
|
|
||||||
instance.interceptors.response.use(
|
if (endSessionOn401) {
|
||||||
response => response,
|
instance.interceptors.response.use(response => response, handleUnauthorized);
|
||||||
error => {
|
|
||||||
if (error.response && error.response.status === 401) {
|
|
||||||
localStorage.removeItem('ovpmon_token');
|
|
||||||
localStorage.removeItem('ovpmon_user');
|
|
||||||
// Redirecting using window.location for absolute refresh
|
|
||||||
if (window.location.pathname !== '/login') {
|
|
||||||
window.location.href = '/login';
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return Promise.reject(error);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
setupInterceptors(apiClient, getBaseUrl);
|
setupInterceptors(apiClient, getBaseUrl);
|
||||||
setupInterceptors(profilesApiClient, getProfilesBaseUrl);
|
setupInterceptors(profilesApiClient, getProfilesBaseUrl);
|
||||||
|
setupInterceptors(authApiClient, getAuthBaseUrl, { endSessionOn401: false });
|
||||||
|
|
||||||
export function useApi() {
|
export function useApi() {
|
||||||
const fetchStats = async () => {
|
const fetchStats = async () => {
|
||||||
@@ -59,13 +71,14 @@ export function useApi() {
|
|||||||
|
|
||||||
const fetchCertificates = async () => {
|
const fetchCertificates = async () => {
|
||||||
const res = await profilesApiClient.get('/profiles');
|
const res = await profilesApiClient.get('/profiles');
|
||||||
return res.data;
|
// GET /profiles returns a plain array (not the {success, data} envelope of the monitoring API)
|
||||||
|
return Array.isArray(res.data) ? res.data : [];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
apiClient,
|
apiClient,
|
||||||
profilesApiClient,
|
profilesApiClient,
|
||||||
|
authApiClient,
|
||||||
fetchStats,
|
fetchStats,
|
||||||
fetchClientHistory,
|
fetchClientHistory,
|
||||||
fetchAnalytics,
|
fetchAnalytics,
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||||
|
import { AxiosError } from 'axios';
|
||||||
|
|
||||||
|
const store = {};
|
||||||
|
let location;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
for (const k of Object.keys(store)) delete store[k];
|
||||||
|
store.ovpmon_token = 'tok';
|
||||||
|
store.ovpmon_user = 'admin';
|
||||||
|
location = { pathname: '/account', href: '/account' };
|
||||||
|
vi.stubGlobal('localStorage', {
|
||||||
|
getItem: (k) => (k in store ? store[k] : null),
|
||||||
|
setItem: (k, v) => { store[k] = String(v); },
|
||||||
|
removeItem: (k) => { delete store[k]; }
|
||||||
|
});
|
||||||
|
vi.stubGlobal('window', { location });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Make the client answer with the given status without any network
|
||||||
|
const failWith = async (client, status, url) => {
|
||||||
|
client.defaults.adapter = (config) => Promise.reject(
|
||||||
|
new AxiosError('failed', 'ERR_BAD_REQUEST', config, null, { status, data: {}, config })
|
||||||
|
);
|
||||||
|
await client.post(url).catch(() => {});
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('401 handling', () => {
|
||||||
|
it('keeps the session on 401 from /auth/* (wrong password or 2FA code)', async () => {
|
||||||
|
const { useApi } = await import('./useApi');
|
||||||
|
await failWith(useApi().authApiClient, 401, '/change-password');
|
||||||
|
expect(store.ovpmon_token).toBe('tok');
|
||||||
|
expect(location.href).toBe('/account');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ends the session on 401 from other requests', async () => {
|
||||||
|
const { useApi } = await import('./useApi');
|
||||||
|
await failWith(useApi().apiClient, 401, '/stats');
|
||||||
|
expect(store.ovpmon_token).toBeUndefined();
|
||||||
|
expect(location.href).toBe('/login');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds the auth base URL next to the API root', async () => {
|
||||||
|
const { useApi } = await import('./useApi');
|
||||||
|
let seen;
|
||||||
|
const client = useApi().authApiClient;
|
||||||
|
client.defaults.adapter = (config) => { seen = config; return Promise.resolve({ status: 200, data: {}, config }); };
|
||||||
|
await client.post('/login');
|
||||||
|
expect(seen.baseURL).toBe('http://localhost:5001/api/auth');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores other error codes', async () => {
|
||||||
|
const { useApi } = await import('./useApi');
|
||||||
|
await failWith(useApi().profilesApiClient, 500, '/profiles');
|
||||||
|
expect(store.ovpmon_token).toBe('tok');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,15 +1,17 @@
|
|||||||
export function useFormatters() {
|
export function useFormatters() {
|
||||||
function formatBytes(bytes, decimals = 2) {
|
function formatBytes(bytes, decimals = 2) {
|
||||||
if (bytes === 0) return '0 B';
|
const value = Number(bytes);
|
||||||
|
// null, undefined, NaN and negative values are shown as zero
|
||||||
|
if (!Number.isFinite(value) || value <= 0) return '0 B';
|
||||||
const k = 1024;
|
const k = 1024;
|
||||||
const dm = decimals < 0 ? 0 : decimals;
|
const dm = decimals < 0 ? 0 : decimals;
|
||||||
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
|
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
const i = Math.min(Math.max(Math.floor(Math.log(value) / Math.log(k)), 0), sizes.length - 1);
|
||||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
|
return parseFloat((value / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatRate(rate) {
|
function formatRate(rate) {
|
||||||
return parseFloat(rate).toFixed(3) + ' Mbps';
|
return (parseFloat(rate) || 0).toFixed(3) + ' Mbps';
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseServerDate(dateStr) {
|
function parseServerDate(dateStr) {
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { useFormatters } from './useFormatters';
|
||||||
|
|
||||||
|
const { formatBytes, formatRate } = useFormatters();
|
||||||
|
|
||||||
|
describe('formatBytes', () => {
|
||||||
|
it('formats regular values', () => {
|
||||||
|
expect(formatBytes(1536)).toBe('1.5 KB');
|
||||||
|
expect(formatBytes(5 * 1024 * 1024)).toBe('5 MB');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows zero for empty, non-numeric and negative values', () => {
|
||||||
|
for (const v of [0, null, undefined, NaN, 'abc', -5, Infinity]) {
|
||||||
|
expect(formatBytes(v)).toBe('0 B');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stays inside the unit table', () => {
|
||||||
|
expect(formatBytes(0.5)).toBe('0.5 B');
|
||||||
|
expect(formatBytes(Math.pow(1024, 6))).toMatch(/ TB$/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('formatRate', () => {
|
||||||
|
it('does not produce NaN', () => {
|
||||||
|
expect(formatRate(1.23456)).toBe('1.235 Mbps');
|
||||||
|
expect(formatRate(null)).toBe('0.000 Mbps');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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 };
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { ref, onMounted, onUnmounted } from 'vue';
|
||||||
|
|
||||||
|
const STORAGE_KEY = 'theme';
|
||||||
|
|
||||||
|
const isDark = ref(false);
|
||||||
|
|
||||||
|
const apply = (theme) => {
|
||||||
|
isDark.value = theme === 'dark';
|
||||||
|
document.documentElement.setAttribute('data-theme', theme);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Saved choice first, then the system setting (prefers-color-scheme) on the first visit.
|
||||||
|
// Called from main.js before the app is mounted, so the page never flashes in the wrong theme.
|
||||||
|
export const initTheme = () => {
|
||||||
|
let theme = null;
|
||||||
|
try { theme = localStorage.getItem(STORAGE_KEY); } catch (e) { /* storage blocked */ }
|
||||||
|
if (theme !== 'dark' && theme !== 'light') {
|
||||||
|
theme = window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||||
|
}
|
||||||
|
apply(theme);
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleTheme = () => {
|
||||||
|
const theme = isDark.value ? 'light' : 'dark';
|
||||||
|
apply(theme);
|
||||||
|
try { localStorage.setItem(STORAGE_KEY, theme); } catch (e) { /* storage blocked */ }
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useTheme() {
|
||||||
|
return { isDark, toggleTheme };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call `callback` whenever data-theme of <html> changes; the observer is released with the component
|
||||||
|
export function useThemeObserver(callback) {
|
||||||
|
let observer = null;
|
||||||
|
onMounted(() => {
|
||||||
|
observer = new MutationObserver((mutations) => {
|
||||||
|
if (mutations.some(m => m.attributeName === 'data-theme')) callback();
|
||||||
|
});
|
||||||
|
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
|
||||||
|
});
|
||||||
|
onUnmounted(() => observer?.disconnect());
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { reactive } from 'vue';
|
||||||
|
|
||||||
|
const MAX_VISIBLE = 4;
|
||||||
|
const DEFAULT_TIMEOUT = 5000;
|
||||||
|
const ERROR_TIMEOUT = 8000;
|
||||||
|
|
||||||
|
// Module-level state: every caller (views, ToastContainer) shares the same list
|
||||||
|
const toasts = reactive([]);
|
||||||
|
const timers = new Map(); // id -> { handle, startedAt, remaining }
|
||||||
|
let nextId = 1;
|
||||||
|
|
||||||
|
const clearTimer = (id) => {
|
||||||
|
const t = timers.get(id);
|
||||||
|
if (t) clearTimeout(t.handle);
|
||||||
|
timers.delete(id);
|
||||||
|
};
|
||||||
|
|
||||||
|
const dismiss = (id) => {
|
||||||
|
clearTimer(id);
|
||||||
|
const idx = toasts.findIndex((t) => t.id === id);
|
||||||
|
if (idx !== -1) toasts.splice(idx, 1);
|
||||||
|
};
|
||||||
|
|
||||||
|
const startTimer = (id, ms) => {
|
||||||
|
clearTimer(id);
|
||||||
|
timers.set(id, { handle: setTimeout(() => dismiss(id), ms), startedAt: Date.now(), remaining: ms });
|
||||||
|
};
|
||||||
|
|
||||||
|
// Stop the countdown (mouse over the toast); the progress bar is paused by CSS
|
||||||
|
const pause = (id) => {
|
||||||
|
const t = timers.get(id);
|
||||||
|
if (!t) return;
|
||||||
|
clearTimeout(t.handle);
|
||||||
|
t.remaining = Math.max(0, t.remaining - (Date.now() - t.startedAt));
|
||||||
|
t.handle = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const resume = (id) => {
|
||||||
|
const t = timers.get(id);
|
||||||
|
if (!t || t.handle !== null) return;
|
||||||
|
startTimer(id, t.remaining);
|
||||||
|
};
|
||||||
|
|
||||||
|
const show = (text, type = 'success', timeout) => {
|
||||||
|
const kind = ['success', 'warning', 'error', 'info'].includes(type) ? type : 'info';
|
||||||
|
const duration = timeout ?? (kind === 'error' ? ERROR_TIMEOUT : DEFAULT_TIMEOUT);
|
||||||
|
const id = nextId++;
|
||||||
|
|
||||||
|
toasts.push({ id, text: String(text ?? ''), type: kind, timeout: duration });
|
||||||
|
while (toasts.length > MAX_VISIBLE) dismiss(toasts[0].id);
|
||||||
|
if (duration > 0) startTimer(id, duration);
|
||||||
|
return id;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Drop everything and release all timers (container unmount)
|
||||||
|
const clear = () => {
|
||||||
|
timers.forEach((t) => clearTimeout(t.handle));
|
||||||
|
timers.clear();
|
||||||
|
toasts.splice(0, toasts.length);
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useToast() {
|
||||||
|
return { toasts, show, dismiss, pause, resume, clear };
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
import { onUnmounted } from 'vue';
|
||||||
|
import Chart from 'chart.js/auto';
|
||||||
|
import { useFormatters } from './useFormatters';
|
||||||
|
|
||||||
|
export const COLOR_RX = '#1652B8'; // OpenVPN Blue
|
||||||
|
export const COLOR_TX = '#EC7C31'; // Brand Orange
|
||||||
|
|
||||||
|
const MB = 1024 * 1024;
|
||||||
|
|
||||||
|
// Chart colors depend on the page theme (data-theme of <html>)
|
||||||
|
export const getThemeColors = () => {
|
||||||
|
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
|
||||||
|
return {
|
||||||
|
isDark,
|
||||||
|
gridColor: isDark ? 'rgba(240, 246, 252, 0.1)' : 'rgba(0,0,0,0.05)',
|
||||||
|
textColor: isDark ? '#8b949e' : '#6c757d'
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Points: { timestamp, bytes_received, bytes_sent, rx_rate_mbps, tx_rate_mbps }.
|
||||||
|
// Blocks of points are merged: traffic is summed, speed takes the block maximum.
|
||||||
|
export const downsamplePoints = (points, maxPoints) => {
|
||||||
|
if (!points || points.length === 0) return [];
|
||||||
|
if (points.length <= maxPoints) return points;
|
||||||
|
|
||||||
|
const blockSize = Math.ceil(points.length / maxPoints);
|
||||||
|
const result = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < points.length; i += blockSize) {
|
||||||
|
const chunk = points.slice(i, i + blockSize);
|
||||||
|
if (chunk.length === 0) continue;
|
||||||
|
|
||||||
|
let sumRx = 0, sumTx = 0;
|
||||||
|
let maxRxRate = 0, maxTxRate = 0;
|
||||||
|
|
||||||
|
chunk.forEach(pt => {
|
||||||
|
sumRx += (pt.bytes_received || 0);
|
||||||
|
sumTx += (pt.bytes_sent || 0);
|
||||||
|
maxRxRate = Math.max(maxRxRate, pt.rx_rate_mbps || 0);
|
||||||
|
maxTxRate = Math.max(maxTxRate, pt.tx_rate_mbps || 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
result.push({
|
||||||
|
timestamp: chunk[0].timestamp,
|
||||||
|
bytes_received: sumRx,
|
||||||
|
bytes_sent: sumTx,
|
||||||
|
rx_rate_mbps: maxRxRate,
|
||||||
|
tx_rate_mbps: maxTxRate
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Ranges of 1h/3h/24h come from raw samples (peak speed); longer ones (7d, 30d) from aggregates
|
||||||
|
// that keep only bytes, so their speed is the average of a bucket and is labelled "(avg)".
|
||||||
|
export const isAveragedRange = (range) => {
|
||||||
|
const m = /^(\d+)([hd])$/.exec(range || '');
|
||||||
|
if (!m) return false;
|
||||||
|
return Number(m[1]) * (m[2] === 'd' ? 24 : 1) > 24;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Line chart of received/sent traffic bound to a canvas ref.
|
||||||
|
// const chart = useTrafficChart(canvasRef, { maxPoints: 96 });
|
||||||
|
// chart.render(points, { range: '24h', speedMode: false });
|
||||||
|
// The chart is destroyed together with the component.
|
||||||
|
export function useTrafficChart(canvasRef, { maxPoints }) {
|
||||||
|
const { parseServerDate } = useFormatters();
|
||||||
|
let instance = null;
|
||||||
|
|
||||||
|
const destroy = () => {
|
||||||
|
if (instance) {
|
||||||
|
instance.destroy();
|
||||||
|
instance = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatLabel = (timestamp, range) => {
|
||||||
|
const d = parseServerDate(timestamp);
|
||||||
|
const time = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||||
|
if (range.includes('h') || range === '1d') return time;
|
||||||
|
return d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' + time;
|
||||||
|
};
|
||||||
|
|
||||||
|
const render = (points, { range, speedMode }) => {
|
||||||
|
if (!canvasRef.value) return;
|
||||||
|
destroy();
|
||||||
|
|
||||||
|
const labels = [];
|
||||||
|
const dataRx = [];
|
||||||
|
const dataTx = [];
|
||||||
|
|
||||||
|
downsamplePoints(points, maxPoints).forEach(point => {
|
||||||
|
labels.push(formatLabel(point.timestamp, range));
|
||||||
|
if (!speedMode) {
|
||||||
|
dataRx.push(point.bytes_received / MB);
|
||||||
|
dataTx.push(point.bytes_sent / MB);
|
||||||
|
} else {
|
||||||
|
dataRx.push(point.rx_rate_mbps || 0);
|
||||||
|
dataTx.push(point.tx_rate_mbps || 0);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const { gridColor, textColor } = getThemeColors();
|
||||||
|
const speedSuffix = isAveragedRange(range) ? ' (avg)' : '';
|
||||||
|
const dataset = (label, data, color, fill) => ({
|
||||||
|
label,
|
||||||
|
data,
|
||||||
|
borderColor: color,
|
||||||
|
backgroundColor: fill,
|
||||||
|
borderWidth: 2,
|
||||||
|
fill: true,
|
||||||
|
tension: 0.3,
|
||||||
|
pointRadius: 3,
|
||||||
|
pointHoverRadius: 4
|
||||||
|
});
|
||||||
|
|
||||||
|
instance = new Chart(canvasRef.value.getContext('2d'), {
|
||||||
|
type: 'line',
|
||||||
|
data: {
|
||||||
|
labels,
|
||||||
|
datasets: [
|
||||||
|
dataset(speedMode ? `RX Mbps${speedSuffix}` : 'Received (MB)', dataRx, COLOR_RX, 'rgba(22, 82, 184, 0.15)'),
|
||||||
|
dataset(speedMode ? `TX Mbps${speedSuffix}` : 'Sent (MB)', dataTx, COLOR_TX, 'rgba(236, 124, 49, 0.15)')
|
||||||
|
]
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
interaction: { mode: 'index', intersect: false },
|
||||||
|
plugins: { legend: { labels: { color: textColor } } },
|
||||||
|
scales: {
|
||||||
|
x: { ticks: { color: textColor, maxTicksLimit: 8 }, grid: { color: gridColor } },
|
||||||
|
y: { beginAtZero: true, ticks: { color: textColor }, grid: { color: gridColor } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
onUnmounted(destroy);
|
||||||
|
|
||||||
|
return { render, destroy };
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
};
|
||||||
+3
-16
@@ -8,23 +8,10 @@ import 'bootstrap/dist/js/bootstrap.bundle.min.js';
|
|||||||
import '@fortawesome/fontawesome-free/css/all.min.css';
|
import '@fortawesome/fontawesome-free/css/all.min.css';
|
||||||
|
|
||||||
import './assets/main.css';
|
import './assets/main.css';
|
||||||
import axios from 'axios';
|
import { initTheme } from './composables/useTheme';
|
||||||
|
|
||||||
// Global Axios Defaults (No Base URL - handled by useApi.js)
|
// Theme is applied before mounting: no flash of the wrong theme
|
||||||
// We keep global error handling for 401s as a fallback
|
initTheme();
|
||||||
axios.interceptors.response.use(
|
|
||||||
response => response,
|
|
||||||
error => {
|
|
||||||
if (error.response && error.response.status === 401) {
|
|
||||||
localStorage.removeItem('ovpmon_token');
|
|
||||||
localStorage.removeItem('ovpmon_user');
|
|
||||||
if (window.location.pathname !== '/login') {
|
|
||||||
window.location.href = '/login';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Promise.reject(error);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
const app = createApp(App);
|
const app = createApp(App);
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { createRouter, createWebHistory } from 'vue-router';
|
import { createRouter, createWebHistory } from 'vue-router';
|
||||||
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 = [
|
||||||
{
|
{
|
||||||
@@ -11,7 +12,7 @@ const routes = [
|
|||||||
{
|
{
|
||||||
path: '/clients',
|
path: '/clients',
|
||||||
name: 'Clients',
|
name: 'Clients',
|
||||||
component: Clients
|
component: () => import('../views/Clients.vue')
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: '/certificates',
|
path: '/certificates',
|
||||||
@@ -27,13 +28,19 @@ 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',
|
||||||
name: 'ServerManagement',
|
name: 'ServerManagement',
|
||||||
component: () => import('../views/ServerManagement.vue')
|
component: () => import('../views/ServerManagement.vue')
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: '/backup',
|
||||||
|
name: 'BackupRestore',
|
||||||
|
component: () => import('../views/BackupRestore.vue')
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: '/account',
|
path: '/account',
|
||||||
name: 'Account',
|
name: 'Account',
|
||||||
@@ -44,6 +51,11 @@ const routes = [
|
|||||||
name: 'Login',
|
name: 'Login',
|
||||||
component: Login,
|
component: Login,
|
||||||
meta: { public: true }
|
meta: { public: true }
|
||||||
|
},
|
||||||
|
// Unknown address: back to the start page (the guard sends guests to the login page)
|
||||||
|
{
|
||||||
|
path: '/:pathMatch(.*)*',
|
||||||
|
redirect: '/'
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -52,13 +64,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();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
// IPv4 helpers for the VPN subnet field: "a.b.c.d/nn" <-> network address + dotted netmask.
|
||||||
|
|
||||||
|
const IPV4 = /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;
|
||||||
|
|
||||||
|
// 24 -> '255.255.255.0'; null for a value outside 0..32
|
||||||
|
export function cidrToMask(bits) {
|
||||||
|
const n = Number(bits);
|
||||||
|
if (bits === '' || bits === null || !Number.isInteger(n) || n < 0 || n > 32) return null;
|
||||||
|
const mask = n === 0 ? 0 : (0xFFFFFFFF << (32 - n)) >>> 0;
|
||||||
|
return [24, 16, 8, 0].map(shift => (mask >>> shift) & 255).join('.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// '255.255.255.0' -> 24; null for a malformed or non-contiguous mask
|
||||||
|
export function maskToCidr(mask) {
|
||||||
|
if (typeof mask !== 'string' || !IPV4.test(mask)) return null;
|
||||||
|
const value = mask.split('.').reduce((acc, p) => ((acc << 8) | Number(p)) >>> 0, 0);
|
||||||
|
let bits = 0;
|
||||||
|
while (bits < 32 && (value & (0x80000000 >>> bits))) bits++;
|
||||||
|
// The rest must be zeros, otherwise the mask is not contiguous
|
||||||
|
const expected = bits === 0 ? 0 : (0xFFFFFFFF << (32 - bits)) >>> 0;
|
||||||
|
return value === expected ? bits : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// '172.20.1.0/24' -> { network: '172.20.1.0', netmask: '255.255.255.0' }
|
||||||
|
// '172.20.1.0' -> { network: '172.20.1.0', netmask: null } (no suffix: the caller keeps the current mask)
|
||||||
|
// anything else -> null
|
||||||
|
export function parseCidr(value) {
|
||||||
|
const text = String(value ?? '').trim();
|
||||||
|
const [network, suffix, ...rest] = text.split('/');
|
||||||
|
if (rest.length || !IPV4.test(network)) return null;
|
||||||
|
if (suffix === undefined) return { network, netmask: null };
|
||||||
|
const netmask = cidrToMask(suffix);
|
||||||
|
return netmask ? { network, netmask } : null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { cidrToMask, maskToCidr, parseCidr } from './cidr';
|
||||||
|
|
||||||
|
describe('cidrToMask / maskToCidr', () => {
|
||||||
|
it('converts a suffix to a netmask and back', () => {
|
||||||
|
for (const [bits, mask] of [[8, '255.0.0.0'], [22, '255.255.252.0'], [24, '255.255.255.0'], [30, '255.255.255.252']]) {
|
||||||
|
expect(cidrToMask(bits)).toBe(mask);
|
||||||
|
expect(maskToCidr(mask)).toBe(bits);
|
||||||
|
}
|
||||||
|
expect(cidrToMask(0)).toBe('0.0.0.0');
|
||||||
|
expect(cidrToMask(32)).toBe('255.255.255.255');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects out-of-range suffixes and non-contiguous masks', () => {
|
||||||
|
for (const v of [-1, 33, 'x', '', null]) expect(cidrToMask(v)).toBeNull();
|
||||||
|
expect(maskToCidr('255.0.255.0')).toBeNull();
|
||||||
|
expect(maskToCidr('255.255.255')).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('parseCidr', () => {
|
||||||
|
it('splits the address and the mask', () => {
|
||||||
|
expect(parseCidr('172.20.1.0/24')).toEqual({ network: '172.20.1.0', netmask: '255.255.255.0' });
|
||||||
|
expect(parseCidr(' 10.8.0.0/22 ')).toEqual({ network: '10.8.0.0', netmask: '255.255.252.0' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the mask empty when there is no suffix', () => {
|
||||||
|
expect(parseCidr('10.8.0.0')).toEqual({ network: '10.8.0.0', netmask: null });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects malformed input', () => {
|
||||||
|
for (const v of ['', 'abc', '10.8.0.0/', '10.8.0.0/33', '10.8.0/24', '300.1.1.1/24', '10.8.0.0/24/1']) {
|
||||||
|
expect(parseCidr(v)).toBeNull();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
// Multi-session helpers for the Clients page
|
||||||
|
|
||||||
|
// Badge "xN" is shown only when a client has more than one session
|
||||||
|
export const sessionsBadge = (c) => (c.sessions_count > 1 ? `×${c.sessions_count}` : null);
|
||||||
|
|
||||||
|
// Toggle a client in the set of expanded rows (returns a new array)
|
||||||
|
export const toggleExpanded = (expanded, name) =>
|
||||||
|
expanded.includes(name) ? expanded.filter(n => n !== name) : [...expanded, name];
|
||||||
|
|
||||||
|
// Sessions to render under a client row: only when expanded and there is more than one
|
||||||
|
export const visibleSessions = (c, expanded) =>
|
||||||
|
(c.sessions_count > 1 && expanded.includes(c.common_name)) ? (c.sessions || []) : [];
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { sessionsBadge, toggleExpanded, visibleSessions } from './sessions';
|
||||||
|
|
||||||
|
describe('multi-session display', () => {
|
||||||
|
const multi = { common_name: 'alice', sessions_count: 2, sessions: [{ real_address: 'a' }, { real_address: 'b' }] };
|
||||||
|
const single = { common_name: 'bob', sessions_count: 1, sessions: [{ real_address: 'c' }] };
|
||||||
|
|
||||||
|
it('shows the badge only for more than one session', () => {
|
||||||
|
expect(sessionsBadge(multi)).toBe('×2');
|
||||||
|
expect(sessionsBadge(single)).toBeNull();
|
||||||
|
expect(sessionsBadge({ common_name: 'old' })).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('expands and collapses the session list on click', () => {
|
||||||
|
expect(visibleSessions(multi, [])).toEqual([]);
|
||||||
|
const open = toggleExpanded([], 'alice');
|
||||||
|
expect(visibleSessions(multi, open)).toHaveLength(2);
|
||||||
|
expect(visibleSessions(multi, toggleExpanded(open, 'alice'))).toEqual([]);
|
||||||
|
expect(visibleSessions(single, ['bob'])).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -50,7 +50,7 @@
|
|||||||
<h4 class="m-0 text-heading">Secure Your Account</h4>
|
<h4 class="m-0 text-heading">Secure Your Account</h4>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-interior-description">
|
<div class="card-interior-description">
|
||||||
<p class="text-muted m-0">Protect your OpenVPN Monitor dashboard with second-layer security using Google Authenticator or any TOTP app.</p>
|
<p class="text-muted m-0">Protect your OpenVPN Controller dashboard with second-layer security using Google Authenticator or any TOTP app.</p>
|
||||||
</div>
|
</div>
|
||||||
<button class="btn btn-action btn-action-primary py-2 fw-bold btn-account-action" @click="initSetup" :disabled="loading">
|
<button class="btn btn-action btn-action-primary py-2 fw-bold btn-account-action" @click="initSetup" :disabled="loading">
|
||||||
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
||||||
@@ -87,6 +87,9 @@
|
|||||||
v-model="otp"
|
v-model="otp"
|
||||||
placeholder="000000"
|
placeholder="000000"
|
||||||
maxlength="6"
|
maxlength="6"
|
||||||
|
inputmode="numeric"
|
||||||
|
autocomplete="one-time-code"
|
||||||
|
aria-label="6-digit authentication code"
|
||||||
>
|
>
|
||||||
<button class="btn btn-action btn-action-primary px-4 fw-bold" @click="verifyAndEnable" :disabled="loading">
|
<button class="btn btn-action btn-action-primary px-4 fw-bold" @click="verifyAndEnable" :disabled="loading">
|
||||||
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
||||||
@@ -117,10 +120,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Alerts/Notifications Modal -->
|
<!-- Confirmation before 2FA is disabled; results are shown as toasts -->
|
||||||
<ConfirmModal ref="confirmModal" />
|
|
||||||
|
|
||||||
<!-- Action Confirmations Modal -->
|
|
||||||
<ConfirmModal ref="disable2FAModal" @confirm="handleDisable2FA" />
|
<ConfirmModal ref="disable2FAModal" @confirm="handleDisable2FA" />
|
||||||
|
|
||||||
<!-- Password Change Modal -->
|
<!-- Password Change Modal -->
|
||||||
@@ -134,6 +134,7 @@
|
|||||||
class="form-control"
|
class="form-control"
|
||||||
v-model="passwordForm.current_password"
|
v-model="passwordForm.current_password"
|
||||||
placeholder="Enter current password"
|
placeholder="Enter current password"
|
||||||
|
autocomplete="current-password"
|
||||||
required
|
required
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
@@ -144,6 +145,7 @@
|
|||||||
class="form-control"
|
class="form-control"
|
||||||
v-model="passwordForm.new_password"
|
v-model="passwordForm.new_password"
|
||||||
placeholder="Min. 8 characters"
|
placeholder="Min. 8 characters"
|
||||||
|
autocomplete="new-password"
|
||||||
required
|
required
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
@@ -154,6 +156,7 @@
|
|||||||
class="form-control"
|
class="form-control"
|
||||||
v-model="passwordForm.confirm_password"
|
v-model="passwordForm.confirm_password"
|
||||||
placeholder="Confirm new password"
|
placeholder="Confirm new password"
|
||||||
|
autocomplete="new-password"
|
||||||
required
|
required
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
@@ -191,6 +194,7 @@
|
|||||||
class="form-control"
|
class="form-control"
|
||||||
v-model="usernameForm.current_password"
|
v-model="usernameForm.current_password"
|
||||||
placeholder="Enter current password"
|
placeholder="Enter current password"
|
||||||
|
autocomplete="current-password"
|
||||||
required
|
required
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
@@ -223,16 +227,16 @@
|
|||||||
import { ref, onMounted, reactive } from 'vue';
|
import { ref, onMounted, reactive } from 'vue';
|
||||||
import { useApi } from '../composables/useApi';
|
import { useApi } from '../composables/useApi';
|
||||||
import QrcodeVue from 'qrcode.vue';
|
import QrcodeVue from 'qrcode.vue';
|
||||||
import Swal from 'sweetalert2';
|
|
||||||
import BaseModal from '../components/BaseModal.vue';
|
import BaseModal from '../components/BaseModal.vue';
|
||||||
import ConfirmModal from '../components/ConfirmModal.vue';
|
import ConfirmModal from '../components/ConfirmModal.vue';
|
||||||
|
import { useToast } from '../composables/useToast';
|
||||||
|
|
||||||
const { apiClient } = useApi();
|
const { apiClient, authApiClient } = useApi();
|
||||||
|
const toast = useToast();
|
||||||
|
|
||||||
// UI Refs
|
// UI Refs
|
||||||
const pwModal = ref(null);
|
const pwModal = ref(null);
|
||||||
const userModal = ref(null);
|
const userModal = ref(null);
|
||||||
const confirmModal = ref(null);
|
|
||||||
const disable2FAModal = ref(null);
|
const disable2FAModal = ref(null);
|
||||||
|
|
||||||
// Password Logic
|
// Password Logic
|
||||||
@@ -252,36 +256,21 @@ const showPwModal = () => {
|
|||||||
|
|
||||||
const handleChangePassword = async () => {
|
const handleChangePassword = async () => {
|
||||||
if (passwordForm.new_password !== passwordForm.confirm_password) {
|
if (passwordForm.new_password !== passwordForm.confirm_password) {
|
||||||
Swal.fire({
|
toast.show('New passwords do not match', 'error');
|
||||||
title: 'Error!',
|
|
||||||
text: 'New passwords do not match',
|
|
||||||
icon: 'error',
|
|
||||||
confirmButtonColor: '#EC7C31'
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
pwLoading.value = true;
|
pwLoading.value = true;
|
||||||
try {
|
try {
|
||||||
await apiClient.post('../auth/change-password', {
|
await authApiClient.post('/change-password', {
|
||||||
current_password: passwordForm.current_password,
|
current_password: passwordForm.current_password,
|
||||||
new_password: passwordForm.new_password
|
new_password: passwordForm.new_password
|
||||||
});
|
});
|
||||||
|
|
||||||
pwModal.value.hide();
|
pwModal.value.hide();
|
||||||
Swal.fire({
|
toast.show('Password updated successfully.', 'success');
|
||||||
title: 'Success!',
|
|
||||||
text: 'Password updated successfully.',
|
|
||||||
icon: 'success',
|
|
||||||
confirmButtonColor: '#1652B8'
|
|
||||||
});
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
Swal.fire({
|
toast.show(err.response?.data?.error || 'Failed to update password', 'error');
|
||||||
title: 'Failed',
|
|
||||||
text: err.response?.data?.error || 'Failed to update password',
|
|
||||||
icon: 'error',
|
|
||||||
confirmButtonColor: '#cf222e'
|
|
||||||
});
|
|
||||||
} finally {
|
} finally {
|
||||||
pwLoading.value = false;
|
pwLoading.value = false;
|
||||||
}
|
}
|
||||||
@@ -300,18 +289,13 @@ const showUserModal = () => {
|
|||||||
|
|
||||||
const handleChangeUsername = async () => {
|
const handleChangeUsername = async () => {
|
||||||
if (!/^[A-Za-z][A-Za-z0-9_.-]{2,31}$/.test(usernameForm.new_username)) {
|
if (!/^[A-Za-z][A-Za-z0-9_.-]{2,31}$/.test(usernameForm.new_username)) {
|
||||||
Swal.fire({
|
toast.show('Username must be 3-32 chars, start with a letter, and contain only letters, digits, . _ -', 'error');
|
||||||
title: 'Error!',
|
|
||||||
text: 'Username must be 3-32 chars, start with a letter, and contain only letters, digits, . _ -',
|
|
||||||
icon: 'error',
|
|
||||||
confirmButtonColor: '#EC7C31'
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
userLoading.value = true;
|
userLoading.value = true;
|
||||||
try {
|
try {
|
||||||
const res = await apiClient.post('../auth/change-username', {
|
const res = await authApiClient.post('/change-username', {
|
||||||
new_username: usernameForm.new_username,
|
new_username: usernameForm.new_username,
|
||||||
current_password: usernameForm.current_password,
|
current_password: usernameForm.current_password,
|
||||||
otp: usernameForm.otp || undefined
|
otp: usernameForm.otp || undefined
|
||||||
@@ -320,19 +304,9 @@ const handleChangeUsername = async () => {
|
|||||||
try { localStorage.setItem('ovpmon_user', res.data.username); } catch (e) { /* ignore */ }
|
try { localStorage.setItem('ovpmon_user', res.data.username); } catch (e) { /* ignore */ }
|
||||||
window.dispatchEvent(new Event('ovpmon-user-changed'));
|
window.dispatchEvent(new Event('ovpmon-user-changed'));
|
||||||
userModal.value.hide();
|
userModal.value.hide();
|
||||||
Swal.fire({
|
toast.show('Username updated. Use the new username the next time you sign in.', 'success');
|
||||||
title: 'Success!',
|
|
||||||
text: 'Username updated. Use the new username the next time you sign in.',
|
|
||||||
icon: 'success',
|
|
||||||
confirmButtonColor: '#1652B8'
|
|
||||||
});
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
Swal.fire({
|
toast.show(err.response?.data?.error || 'Failed to update username', 'error');
|
||||||
title: 'Failed',
|
|
||||||
text: err.response?.data?.error || 'Failed to update username',
|
|
||||||
icon: 'error',
|
|
||||||
confirmButtonColor: '#cf222e'
|
|
||||||
});
|
|
||||||
} finally {
|
} finally {
|
||||||
userLoading.value = false;
|
userLoading.value = false;
|
||||||
}
|
}
|
||||||
@@ -344,7 +318,6 @@ const step2 = ref(false);
|
|||||||
const loading = ref(false);
|
const loading = ref(false);
|
||||||
const otp = ref('');
|
const otp = ref('');
|
||||||
const setupData = ref({ secret: '', uri: '' });
|
const setupData = ref({ secret: '', uri: '' });
|
||||||
const isDark = ref(document.documentElement.getAttribute('data-theme') === 'dark');
|
|
||||||
|
|
||||||
const fetchUserStatus = async () => {
|
const fetchUserStatus = async () => {
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
@@ -358,27 +331,16 @@ const fetchUserStatus = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(fetchUserStatus);
|
||||||
fetchUserStatus();
|
|
||||||
|
|
||||||
const observer = new MutationObserver((mutations) => {
|
|
||||||
mutations.forEach((mutation) => {
|
|
||||||
if (mutation.attributeName === 'data-theme') {
|
|
||||||
isDark.value = document.documentElement.getAttribute('data-theme') === 'dark';
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
observer.observe(document.documentElement, { attributes: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
const initSetup = async () => {
|
const initSetup = async () => {
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
try {
|
try {
|
||||||
const res = await apiClient.post('../auth/setup-2fa');
|
const res = await authApiClient.post('/setup-2fa');
|
||||||
setupData.value = res.data;
|
setupData.value = res.data;
|
||||||
step2.value = true;
|
step2.value = true;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
Swal.fire('Error', 'Failed to initialize 2FA setup.', 'error');
|
toast.show(err.response?.data?.error || 'Failed to initialize 2FA setup.', 'error');
|
||||||
} finally {
|
} finally {
|
||||||
loading.value = false;
|
loading.value = false;
|
||||||
}
|
}
|
||||||
@@ -388,26 +350,14 @@ const verifyAndEnable = async () => {
|
|||||||
if (!otp.value || otp.value.length !== 6) return;
|
if (!otp.value || otp.value.length !== 6) return;
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
try {
|
try {
|
||||||
await apiClient.post('../auth/enable-2fa', {
|
await authApiClient.post('/enable-2fa', {
|
||||||
secret: setupData.value.secret,
|
secret: setupData.value.secret,
|
||||||
otp: otp.value
|
otp: otp.value
|
||||||
});
|
});
|
||||||
isEnabled.value = true;
|
isEnabled.value = true;
|
||||||
confirmModal.value.open({
|
toast.show('Two-factor authentication has been enabled. Your dashboard is now more secure.', 'success');
|
||||||
title: 'Success!',
|
|
||||||
message: 'Two-factor authentication has been enabled successfully. Your dashboard is now more secure.',
|
|
||||||
confirmText: 'Great!',
|
|
||||||
confirmBtnClass: 'btn-action-save',
|
|
||||||
showCancel: false
|
|
||||||
});
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
confirmModal.value.open({
|
toast.show(err.response?.data?.error || 'The code you entered is invalid. Please check your authenticator app and try again.', 'error');
|
||||||
title: 'Verification Failed',
|
|
||||||
message: err.response?.data?.error || 'The code you entered is invalid. Please check your authenticator app and try again.',
|
|
||||||
confirmText: 'Try Again',
|
|
||||||
confirmBtnClass: 'btn-action-danger',
|
|
||||||
showCancel: false
|
|
||||||
});
|
|
||||||
} finally {
|
} finally {
|
||||||
loading.value = false;
|
loading.value = false;
|
||||||
}
|
}
|
||||||
@@ -424,25 +374,13 @@ const disableConfirm = () => {
|
|||||||
|
|
||||||
const handleDisable2FA = async () => {
|
const handleDisable2FA = async () => {
|
||||||
try {
|
try {
|
||||||
await apiClient.post('../auth/disable-2fa');
|
await authApiClient.post('/disable-2fa');
|
||||||
|
|
||||||
isEnabled.value = false;
|
isEnabled.value = false;
|
||||||
step2.value = false;
|
step2.value = false;
|
||||||
confirmModal.value.open({
|
toast.show('Two-factor authentication has been disabled. Your account is now using standard password protection.', 'warning');
|
||||||
title: '2FA Disabled',
|
|
||||||
message: 'Two-factor authentication has been disabled. Your account is now using standard password protection.',
|
|
||||||
confirmText: 'OK',
|
|
||||||
confirmBtnClass: 'btn-action-primary',
|
|
||||||
showCancel: false
|
|
||||||
});
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
confirmModal.value.open({
|
toast.show(err.response?.data?.error || 'Failed to disable two-factor authentication. Please try again.', 'error');
|
||||||
title: 'Error',
|
|
||||||
message: err.response?.data?.error || 'Failed to disable two-factor authentication. Please try again.',
|
|
||||||
confirmText: 'OK',
|
|
||||||
confirmBtnClass: 'btn-action-danger',
|
|
||||||
showCancel: false
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
+29
-146
@@ -151,16 +151,18 @@ import Chart from 'chart.js/auto';
|
|||||||
import { useApi } from '../composables/useApi';
|
import { useApi } from '../composables/useApi';
|
||||||
import { useFormatters } from '../composables/useFormatters';
|
import { useFormatters } from '../composables/useFormatters';
|
||||||
import { useAppConfig } from '../composables/useAppConfig';
|
import { useAppConfig } from '../composables/useAppConfig';
|
||||||
|
import { useThemeObserver } from '../composables/useTheme';
|
||||||
|
import { useTrafficChart, getThemeColors, COLOR_RX, COLOR_TX } from '../composables/useTrafficChart';
|
||||||
|
|
||||||
const { fetchAnalytics, fetchCertificates } = useApi();
|
const { fetchAnalytics, fetchCertificates } = useApi();
|
||||||
const { formatBytes, parseServerDate } = useFormatters();
|
const { formatBytes } = useFormatters();
|
||||||
const { config } = useAppConfig();
|
const { config } = useAppConfig();
|
||||||
|
|
||||||
// Refs
|
// Refs
|
||||||
const mainChartRef = ref(null);
|
const mainChartRef = ref(null);
|
||||||
const pieChartRef = ref(null);
|
const pieChartRef = ref(null);
|
||||||
let mainChartInstance = null;
|
|
||||||
let pieChartInstance = null;
|
let pieChartInstance = null;
|
||||||
|
const mainChart = useTrafficChart(mainChartRef, { maxPoints: 96 });
|
||||||
|
|
||||||
// State
|
// State
|
||||||
const loading = reactive({ analytics: true, certs: true });
|
const loading = reactive({ analytics: true, certs: true });
|
||||||
@@ -179,17 +181,14 @@ const kpi = reactive({
|
|||||||
|
|
||||||
const topClients = ref([]);
|
const topClients = ref([]);
|
||||||
const expiringCertsList = ref([]);
|
const expiringCertsList = ref([]);
|
||||||
let cachedHistory = null;
|
let cachedHistory = [];
|
||||||
|
|
||||||
// Helpers
|
|
||||||
const MAX_CHART_POINTS = 96;
|
|
||||||
|
|
||||||
const loadAnalytics = async () => {
|
const loadAnalytics = async () => {
|
||||||
loading.analytics = true;
|
loading.analytics = true;
|
||||||
try {
|
try {
|
||||||
const res = await fetchAnalytics(range.value);
|
const res = await fetchAnalytics(range.value);
|
||||||
if (res.success) {
|
if (res.success) {
|
||||||
proccessData(res.data);
|
processData(res.data);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
@@ -201,17 +200,16 @@ const loadAnalytics = async () => {
|
|||||||
const loadCerts = async () => {
|
const loadCerts = async () => {
|
||||||
loading.certs = true;
|
loading.certs = true;
|
||||||
try {
|
try {
|
||||||
const res = await fetchCertificates();
|
// fetchCertificates returns the plain array of profiles
|
||||||
if(res.success && Array.isArray(res.data)) {
|
const profiles = await fetchCertificates();
|
||||||
const list = res.data.filter(cert => {
|
const list = profiles.filter(cert => {
|
||||||
// Only active, non-revoked, and expiring soon (within 45 days)
|
// Only active, non-revoked, and expiring soon (within 45 days)
|
||||||
return !cert.is_revoked && !cert.is_expired &&
|
return !cert.is_revoked && !cert.is_expired &&
|
||||||
cert.days_remaining !== null && cert.days_remaining <= 45;
|
cert.days_remaining != null && cert.days_remaining <= 45;
|
||||||
});
|
});
|
||||||
|
|
||||||
kpi.expiringCerts = list.length;
|
kpi.expiringCerts = list.length;
|
||||||
expiringCertsList.value = list.sort((a,b) => (a.days_remaining || 0) - (b.days_remaining || 0));
|
expiringCertsList.value = list.sort((a, b) => a.days_remaining - b.days_remaining);
|
||||||
}
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -219,7 +217,7 @@ const loadCerts = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const proccessData = (data) => {
|
const processData = (data) => {
|
||||||
kpi.concurrentUsers = data.max_concurrent_24h || 0;
|
kpi.concurrentUsers = data.max_concurrent_24h || 0;
|
||||||
|
|
||||||
// Traffic Distribution
|
// Traffic Distribution
|
||||||
@@ -238,87 +236,21 @@ const proccessData = (data) => {
|
|||||||
percent: kpi.totalTraffic > 0 ? ((Number(c.total_traffic) / kpi.totalTraffic) * 100).toFixed(1) : 0
|
percent: kpi.totalTraffic > 0 ? ((Number(c.total_traffic) / kpi.totalTraffic) * 100).toFixed(1) : 0
|
||||||
}));
|
}));
|
||||||
|
|
||||||
cachedHistory = data.global_history_24h || [];
|
// Map the raw fields to the point format of useTrafficChart
|
||||||
|
cachedHistory = (data.global_history_24h || []).map(p => ({
|
||||||
|
timestamp: p.timestamp,
|
||||||
|
bytes_received: p.total_rx,
|
||||||
|
bytes_sent: p.total_tx,
|
||||||
|
rx_rate_mbps: p.total_rx_rate,
|
||||||
|
tx_rate_mbps: p.total_tx_rate
|
||||||
|
}));
|
||||||
|
|
||||||
renderMainChart();
|
renderMainChart();
|
||||||
renderPieChart();
|
renderPieChart();
|
||||||
};
|
};
|
||||||
|
|
||||||
const renderMainChart = () => {
|
const renderMainChart = () => {
|
||||||
if (!mainChartRef.value) return;
|
mainChart.render(cachedHistory, { range: range.value, speedMode: isSpeedMode.value });
|
||||||
if (mainChartInstance) mainChartInstance.destroy();
|
|
||||||
|
|
||||||
const downsampled = downsampleData(cachedHistory, MAX_CHART_POINTS);
|
|
||||||
const labels = [];
|
|
||||||
const dataRx = [];
|
|
||||||
const dataTx = [];
|
|
||||||
|
|
||||||
downsampled.forEach(point => {
|
|
||||||
const d = parseServerDate(point.timestamp);
|
|
||||||
let label = '';
|
|
||||||
if(range.value.includes('h') || range.value === '1d') {
|
|
||||||
label = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
|
||||||
} else {
|
|
||||||
label = d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' +
|
|
||||||
d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
|
||||||
}
|
|
||||||
labels.push(label);
|
|
||||||
|
|
||||||
if (!isSpeedMode.value) {
|
|
||||||
dataRx.push(point.bytes_received / (1024 * 1024)); // MB
|
|
||||||
dataTx.push(point.bytes_sent / (1024 * 1024)); // MB
|
|
||||||
} else {
|
|
||||||
dataRx.push(point.rx_rate_mbps || 0);
|
|
||||||
dataTx.push(point.tx_rate_mbps || 0);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
|
|
||||||
const gridColor = isDark ? 'rgba(240, 246, 252, 0.1)' : 'rgba(0,0,0,0.05)';
|
|
||||||
const textColor = isDark ? '#8b949e' : '#6c757d';
|
|
||||||
|
|
||||||
const ctx = mainChartRef.value.getContext('2d');
|
|
||||||
mainChartInstance = new Chart(ctx, {
|
|
||||||
type: 'line',
|
|
||||||
data: {
|
|
||||||
labels,
|
|
||||||
datasets: [
|
|
||||||
|
|
||||||
{
|
|
||||||
label: !isSpeedMode.value ? 'Received (MB)' : 'RX Mbps',
|
|
||||||
data: dataRx,
|
|
||||||
borderColor: '#1652B8', // OpenVPN Blue
|
|
||||||
backgroundColor: 'rgba(22, 82, 184, 0.15)',
|
|
||||||
borderWidth: 2,
|
|
||||||
fill: true,
|
|
||||||
tension: 0.3,
|
|
||||||
pointRadius: 3,
|
|
||||||
pointHoverRadius: 4
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: !isSpeedMode.value ? 'Sent (MB)' : 'TX Mbps',
|
|
||||||
data: dataTx,
|
|
||||||
borderColor: '#EC7C31', // Brand Orange
|
|
||||||
backgroundColor: 'rgba(236, 124, 49, 0.15)',
|
|
||||||
borderWidth: 2,
|
|
||||||
fill: true,
|
|
||||||
tension: 0.3,
|
|
||||||
pointRadius: 3,
|
|
||||||
pointHoverRadius: 4
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
options: {
|
|
||||||
responsive: true,
|
|
||||||
maintainAspectRatio: false,
|
|
||||||
interaction: { mode: 'index', intersect: false },
|
|
||||||
plugins: { legend: { labels: { color: textColor } } },
|
|
||||||
scales: {
|
|
||||||
x: { ticks: { color: textColor, maxTicksLimit: 8 }, grid: { color: gridColor } },
|
|
||||||
y: { beginAtZero: true, ticks: { color: textColor }, grid: { color: gridColor } }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const renderPieChart = () => {
|
const renderPieChart = () => {
|
||||||
@@ -326,8 +258,7 @@ const renderPieChart = () => {
|
|||||||
if (pieChartInstance) pieChartInstance.destroy();
|
if (pieChartInstance) pieChartInstance.destroy();
|
||||||
|
|
||||||
const ctx = pieChartRef.value.getContext('2d');
|
const ctx = pieChartRef.value.getContext('2d');
|
||||||
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
|
const bgColor = getThemeColors().isDark ? '#161b22' : '#ffffff';
|
||||||
const bgColor = isDark ? '#161b22' : '#ffffff';
|
|
||||||
|
|
||||||
pieChartInstance = new Chart(ctx, {
|
pieChartInstance = new Chart(ctx, {
|
||||||
type: 'doughnut',
|
type: 'doughnut',
|
||||||
@@ -335,7 +266,7 @@ const renderPieChart = () => {
|
|||||||
labels: ['Received', 'Sent'],
|
labels: ['Received', 'Sent'],
|
||||||
datasets: [{
|
datasets: [{
|
||||||
data: [kpi.totalReceived, kpi.totalSent],
|
data: [kpi.totalReceived, kpi.totalSent],
|
||||||
backgroundColor: ['#1652B8', '#EC7C31'],
|
backgroundColor: [COLOR_RX, COLOR_TX],
|
||||||
borderColor: bgColor,
|
borderColor: bgColor,
|
||||||
borderWidth: 2,
|
borderWidth: 2,
|
||||||
hoverOffset: 4
|
hoverOffset: 4
|
||||||
@@ -350,66 +281,19 @@ const renderPieChart = () => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const downsampleData = (data, maxPoints) => {
|
|
||||||
if (!data || data.length === 0) return [];
|
|
||||||
if (data.length <= maxPoints) {
|
|
||||||
// Map raw fields to internal standardized names
|
|
||||||
return data.map(p => ({
|
|
||||||
timestamp: p.timestamp,
|
|
||||||
bytes_received: p.total_rx,
|
|
||||||
bytes_sent: p.total_tx,
|
|
||||||
rx_rate_mbps: p.total_rx_rate,
|
|
||||||
tx_rate_mbps: p.total_tx_rate
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
const blockSize = Math.ceil(data.length / maxPoints);
|
|
||||||
const result = [];
|
|
||||||
|
|
||||||
for (let i = 0; i < data.length; i += blockSize) {
|
|
||||||
const chunk = data.slice(i, i + blockSize);
|
|
||||||
if (chunk.length === 0) continue;
|
|
||||||
|
|
||||||
let sumRx = 0, sumTx = 0;
|
|
||||||
let maxRxR = 0, maxTxR = 0;
|
|
||||||
|
|
||||||
chunk.forEach(pt => {
|
|
||||||
sumRx += (pt.total_rx || 0);
|
|
||||||
sumTx += (pt.total_tx || 0);
|
|
||||||
maxRxR = Math.max(maxRxR, pt.total_rx_rate || 0);
|
|
||||||
maxTxR = Math.max(maxTxR, pt.total_tx_rate || 0);
|
|
||||||
});
|
|
||||||
|
|
||||||
result.push({
|
|
||||||
timestamp: chunk[0].timestamp,
|
|
||||||
bytes_received: sumRx,
|
|
||||||
bytes_sent: sumTx,
|
|
||||||
rx_rate_mbps: maxRxR,
|
|
||||||
tx_rate_mbps: maxTxR
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Lifecycle
|
// Lifecycle
|
||||||
let intervalId;
|
let intervalId;
|
||||||
|
|
||||||
|
// Redraw the charts when the theme is toggled
|
||||||
|
useThemeObserver(() => {
|
||||||
|
renderMainChart();
|
||||||
|
renderPieChart();
|
||||||
|
});
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
loadAnalytics();
|
loadAnalytics();
|
||||||
loadCerts();
|
loadCerts();
|
||||||
|
|
||||||
// Support Theme Toggle re-render like in Clients
|
|
||||||
// We observe the attribute on html
|
|
||||||
const observer = new MutationObserver((mutations) => {
|
|
||||||
mutations.forEach((mutation) => {
|
|
||||||
if (mutation.type === 'attributes' && mutation.attributeName === 'data-theme') {
|
|
||||||
renderMainChart();
|
|
||||||
renderPieChart();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
observer.observe(document.documentElement, { attributes: true });
|
|
||||||
|
|
||||||
const refreshTime = config.value?.refresh_interval || 30000;
|
const refreshTime = config.value?.refresh_interval || 30000;
|
||||||
intervalId = setInterval(() => {
|
intervalId = setInterval(() => {
|
||||||
loadAnalytics();
|
loadAnalytics();
|
||||||
@@ -419,7 +303,6 @@ onMounted(() => {
|
|||||||
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
if (intervalId) clearInterval(intervalId);
|
if (intervalId) clearInterval(intervalId);
|
||||||
if (mainChartInstance) mainChartInstance.destroy();
|
|
||||||
if (pieChartInstance) pieChartInstance.destroy();
|
if (pieChartInstance) pieChartInstance.destroy();
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
@@ -0,0 +1,803 @@
|
|||||||
|
<template>
|
||||||
|
<div class="backup-page">
|
||||||
|
|
||||||
|
<!-- DESTINATIONS -->
|
||||||
|
<div class="config-card backup-card">
|
||||||
|
<div class="config-header">
|
||||||
|
<h1>Backup Destinations</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
|
||||||
|
<span class="text-muted small">Where backup packages are stored. A backup goes to every selected destination.</span>
|
||||||
|
<button type="button" class="btn-action btn-action-save btn-sm" @click="openAdd" :disabled="!settings.types.length">
|
||||||
|
<i class="fas fa-plus"></i> Add destination
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-hover mb-0">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Name</th>
|
||||||
|
<th>Type</th>
|
||||||
|
<th>Status</th>
|
||||||
|
<th>Last result</th>
|
||||||
|
<th>Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-if="loading">
|
||||||
|
<td colspan="5" class="text-center py-4">
|
||||||
|
<div class="spinner-border spinner-border-sm text-primary" role="status">
|
||||||
|
<span class="visually-hidden">Loading...</span>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr v-else-if="destinations.length === 0">
|
||||||
|
<td colspan="5" class="empty-state text-center py-4">
|
||||||
|
<i class="fas fa-box-archive fa-2x mb-3 text-muted"></i>
|
||||||
|
<p class="text-muted mb-0">No destinations yet. Add one to start making backups.</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr v-for="d in destinations" :key="d.id">
|
||||||
|
<td class="align-top">
|
||||||
|
<div class="fw-semibold" style="color: var(--text-heading);">{{ d.name }}</div>
|
||||||
|
<div class="text-muted small">{{ destinationSummary(d) }}</div>
|
||||||
|
<div v-if="typeInfo(d.type)?.pins_host_key" class="small mt-1">
|
||||||
|
<span v-if="d.params.host_key" class="status-badge status-valid" :title="d.params.host_key">
|
||||||
|
<i class="fas fa-fingerprint me-1"></i>Host key trusted
|
||||||
|
</span>
|
||||||
|
<span v-else class="status-badge status-warning">
|
||||||
|
<i class="fas fa-triangle-exclamation me-1"></i>Host key not trusted: press Test and confirm it
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="plainFtp(d)" class="small mt-1">
|
||||||
|
<span class="status-badge status-warning"><i class="fas fa-triangle-exclamation me-1"></i>No TLS: clear text</span>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td class="align-top"><span class="status-badge status-client">{{ typeLabel(d.type) }}</span></td>
|
||||||
|
<td class="align-top">
|
||||||
|
<span :class="['status-badge', d.enabled ? 'status-valid' : 'status-secondary']">
|
||||||
|
{{ d.enabled ? 'Enabled' : 'Disabled' }}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td class="align-top">
|
||||||
|
<span v-if="d.last_status" :class="['status-badge', d.last_status === 'ok' ? 'status-valid' : 'status-expired']"
|
||||||
|
:title="d.last_message">
|
||||||
|
{{ d.last_status === 'ok' ? 'OK' : 'Failed' }}
|
||||||
|
</span>
|
||||||
|
<span v-else class="text-muted small">never used</span>
|
||||||
|
<div v-if="d.last_at" class="text-muted small">{{ formatTime(d.last_at) }}</div>
|
||||||
|
</td>
|
||||||
|
<td class="align-top">
|
||||||
|
<button class="btn btn-sm btn-link text-primary p-0 me-2" title="Test connection"
|
||||||
|
@click="testDestination(d)" :disabled="testingId === d.id">
|
||||||
|
<i v-if="testingId === d.id" class="fas fa-spinner fa-spin"></i>
|
||||||
|
<i v-else class="fas fa-plug"></i>
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-sm btn-link text-warning p-0 me-2" title="Edit" @click="openEdit(d)" :disabled="isRunning">
|
||||||
|
<i class="fas fa-pen"></i>
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-sm btn-link text-danger p-0" title="Delete" @click="askDelete(d)" :disabled="isRunning">
|
||||||
|
<i class="fas fa-trash"></i>
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- BACKUP -->
|
||||||
|
<div class="config-card backup-card">
|
||||||
|
<div class="config-header">
|
||||||
|
<h1>Backup</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-2">
|
||||||
|
<div>
|
||||||
|
<span v-if="settings.encryption_enabled" class="status-badge status-valid">
|
||||||
|
<i class="fas fa-lock me-1"></i>Packages are encrypted
|
||||||
|
</span>
|
||||||
|
<span v-else class="status-badge status-warning">
|
||||||
|
<i class="fas fa-triangle-exclamation me-1"></i>Packages are NOT encrypted
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="btn-action btn-action-secondary btn-sm" @click="openPassphrase" :disabled="isRunning">
|
||||||
|
<i class="fas fa-key"></i> {{ settings.encryption_enabled ? 'Change passphrase' : 'Set passphrase' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p class="text-muted small mb-3">
|
||||||
|
A package contains the CA private key, the certificates and the password hashes of the administrators.
|
||||||
|
<template v-if="!settings.encryption_enabled">Remote destinations need an encryption passphrase; a local folder can be used without it.</template>
|
||||||
|
<template v-else>Keep the passphrase: a package cannot be restored without it, and it is not stored in the package.</template>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="config-divider"></div>
|
||||||
|
|
||||||
|
<label class="config-label">Server name</label>
|
||||||
|
<div class="config-input-group">
|
||||||
|
<input type="text" class="config-input" v-model="serverNameInput" maxlength="63" autocomplete="off"
|
||||||
|
placeholder="e.g. vpn-main" :disabled="isRunning" @keyup.enter="saveServerName">
|
||||||
|
<button type="button" class="btn-action btn-action-secondary btn-sm" @click="saveServerName"
|
||||||
|
:disabled="isRunning || saving || serverNameInput.trim() === settings.server_name">
|
||||||
|
<i class="fas fa-floppy-disk"></i> Save
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p class="text-muted small mt-2 mb-0">
|
||||||
|
Package names will start with <strong class="text-main">{{ settings.effective_server_name }}</strong>
|
||||||
|
<span v-if="settings.server_name_source === 'public_ip'">(the server address from the VPN settings: no name is set)</span>
|
||||||
|
<span v-else-if="settings.server_name_source === 'hostname'">(the host name, in a container a random identifier: set a name)</span>.
|
||||||
|
Letters, digits, '.' and '-'. Only packages with the same name in the same folder count for "copies to keep".
|
||||||
|
The name is not part of a package: set it again on a new server.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="config-divider"></div>
|
||||||
|
|
||||||
|
<label class="config-label">Destinations for this backup</label>
|
||||||
|
<div v-if="enabledDestinations.length === 0" class="text-muted small mb-3">
|
||||||
|
No enabled destinations. Add or enable one above.
|
||||||
|
</div>
|
||||||
|
<div v-else class="mb-3">
|
||||||
|
<div v-for="d in enabledDestinations" :key="d.id" class="form-check mb-1">
|
||||||
|
<input class="form-check-input" type="checkbox" :id="'bk-dest-' + d.id" :value="d.id"
|
||||||
|
v-model="selectedIds" :disabled="needsPassphrase(d)">
|
||||||
|
<label class="form-check-label text-main" :for="'bk-dest-' + d.id">
|
||||||
|
{{ d.name }} <span class="text-muted small">({{ typeLabel(d.type) }})</span>
|
||||||
|
<span v-if="needsPassphrase(d)" class="text-muted small"> - set a passphrase first</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="btn-action-group justify-content-center mt-3">
|
||||||
|
<button type="button" class="btn-action btn-action-primary" @click="runBackup"
|
||||||
|
:disabled="isRunning || selectedIds.length === 0">
|
||||||
|
<i v-if="isRunning && job.kind === 'backup'" class="fas fa-spinner fa-spin"></i>
|
||||||
|
<i v-else class="fas fa-box-archive"></i>
|
||||||
|
Backup now
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Progress and result of the last backup -->
|
||||||
|
<div v-if="job.kind === 'backup' && job.state !== 'idle'" class="nested-box fade-in mt-4">
|
||||||
|
<label class="nested-label d-flex justify-content-between">
|
||||||
|
<span>{{ job.state === 'running' ? 'Backup in progress' : 'Last backup' }}</span>
|
||||||
|
<span v-if="job.state !== 'running'" :class="['status-badge', jobBadge(job.state)]">{{ jobLabel(job.state) }}</span>
|
||||||
|
</label>
|
||||||
|
<ul class="backup-steps">
|
||||||
|
<li v-for="s in job.stages" :key="s.name">
|
||||||
|
<i :class="stageIcon(s.state)"></i> {{ stageLabel(s.name) }}
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<div v-for="r in job.results" :key="r.destination_id" class="backup-result">
|
||||||
|
<span :class="['status-badge', resultBadge(r.state)]">
|
||||||
|
<i v-if="r.state === 'running'" class="fas fa-spinner fa-spin me-1"></i>{{ resultLabel(r.state) }}
|
||||||
|
</span>
|
||||||
|
<span class="fw-semibold ms-2" style="color: var(--text-heading);">{{ r.name }}</span>
|
||||||
|
<div v-if="r.message" class="text-muted small ms-1 mt-1">{{ r.message }}</div>
|
||||||
|
</div>
|
||||||
|
<div v-if="job.state !== 'running' && job.message" class="text-muted small mt-2">{{ job.message }}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- History -->
|
||||||
|
<div v-if="history.length" class="mt-4">
|
||||||
|
<label class="config-label">History</label>
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-hover mb-0">
|
||||||
|
<thead>
|
||||||
|
<tr><th>Time</th><th>Action</th><th>Result</th><th>Details</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="h in history" :key="h.id">
|
||||||
|
<td>{{ formatTime(h.started_at) }}</td>
|
||||||
|
<td class="text-capitalize">{{ h.kind }}</td>
|
||||||
|
<td><span :class="['status-badge', jobBadge(h.state)]">{{ jobLabel(h.state) }}</span></td>
|
||||||
|
<td class="small text-muted">{{ h.message }}</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- RESTORE -->
|
||||||
|
<div class="config-card backup-card">
|
||||||
|
<div class="config-header">
|
||||||
|
<h1>Restore</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="text-muted small mb-3">
|
||||||
|
Restores the databases, the PKI and the client profiles from a package, also one made on another server.
|
||||||
|
The current state is saved to a local safety copy first.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="config-row">
|
||||||
|
<div class="config-col">
|
||||||
|
<label class="config-label">Source</label>
|
||||||
|
<div class="select-container">
|
||||||
|
<select class="config-select" v-model="restore.sourceId" :disabled="isRunning">
|
||||||
|
<option :value="null" disabled>Select a destination</option>
|
||||||
|
<option v-for="d in destinations" :key="d.id" :value="d.id">{{ d.name }} ({{ typeLabel(d.type) }})</option>
|
||||||
|
</select>
|
||||||
|
<div class="select-arrow"><i class="fas fa-chevron-down"></i></div>
|
||||||
|
</div>
|
||||||
|
<div v-if="restore.checking" class="text-muted small mt-2">
|
||||||
|
<i class="fas fa-spinner fa-spin me-1"></i>Checking the source...
|
||||||
|
</div>
|
||||||
|
<div v-else-if="restore.sourceError" class="mt-2">
|
||||||
|
<span class="status-badge status-expired"><i class="fas fa-times-circle me-1"></i>Source check failed</span>
|
||||||
|
<div class="text-muted small mt-1">{{ restore.sourceError }}</div>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="restore.sourceId !== null" class="mt-2">
|
||||||
|
<span class="status-badge status-valid"><i class="fas fa-check-circle me-1"></i>Source reachable</span>
|
||||||
|
<span class="text-muted small ms-2">{{ restore.packages.length }} package(s) found</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="config-row">
|
||||||
|
<div class="config-col">
|
||||||
|
<label class="config-label">Package (newest first)</label>
|
||||||
|
<div class="select-container">
|
||||||
|
<select class="config-select" v-model="restore.packageName"
|
||||||
|
:disabled="isRunning || restore.checking || restore.packages.length === 0">
|
||||||
|
<option :value="''" disabled>{{ restore.packages.length ? 'Select a package' : 'No packages' }}</option>
|
||||||
|
<option v-for="p in restore.packages" :key="p.name" :value="p.name">{{ packageLabel(p) }}</option>
|
||||||
|
</select>
|
||||||
|
<div class="select-arrow"><i class="fas fa-chevron-down"></i></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="selectedPackage && selectedPackage.encrypted" class="config-row">
|
||||||
|
<div class="config-col">
|
||||||
|
<label class="config-label">Package passphrase</label>
|
||||||
|
<input type="password" class="config-input" v-model="restore.passphrase" autocomplete="off"
|
||||||
|
placeholder="Passphrase used when the package was made">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="btn-action-group justify-content-center">
|
||||||
|
<button type="button" class="btn-action btn-action-danger" @click="askRestore" :disabled="!canRestore">
|
||||||
|
<i v-if="isRunning && job.kind === 'restore'" class="fas fa-spinner fa-spin"></i>
|
||||||
|
<i v-else class="fas fa-rotate-left"></i>
|
||||||
|
Restore
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Progress and result of the restore -->
|
||||||
|
<div v-if="job.kind === 'restore' && job.state !== 'idle'" class="nested-box fade-in mt-4">
|
||||||
|
<label class="nested-label d-flex justify-content-between">
|
||||||
|
<span>{{ job.state === 'running' ? 'Restore in progress. Do not close the server.' : 'Last restore' }}</span>
|
||||||
|
<span v-if="job.state !== 'running'" :class="['status-badge', jobBadge(job.state)]">{{ jobLabel(job.state) }}</span>
|
||||||
|
</label>
|
||||||
|
<ul class="backup-steps">
|
||||||
|
<li v-for="s in job.stages" :key="s.name">
|
||||||
|
<i :class="stageIcon(s.state)"></i> {{ stageLabel(s.name) }}
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<div v-if="job.state !== 'running' && job.message" class="small mt-2" :class="job.state === 'done' ? 'text-main' : 'text-danger'">
|
||||||
|
{{ job.message }}
|
||||||
|
</div>
|
||||||
|
<div v-for="(w, i) in job.warnings" :key="i" class="small mt-1">
|
||||||
|
<span class="status-badge status-warning"><i class="fas fa-triangle-exclamation me-1"></i>{{ w }}</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="restoreFinishedHere && job.relogin" class="mt-3">
|
||||||
|
<p class="text-main small mb-2">
|
||||||
|
The accounts now come from the package. Log in again with the account of the restored server.
|
||||||
|
Check the server address in the VPN settings if the package comes from another server.
|
||||||
|
</p>
|
||||||
|
<button type="button" class="btn-action btn-action-primary btn-sm" @click="logInAgain">
|
||||||
|
<i class="fas fa-sign-in-alt"></i> Log in again
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Add / edit destination -->
|
||||||
|
<BaseModal id="destinationModal" :title="destForm.id ? 'Edit Destination' : 'Add Destination'" ref="destModal">
|
||||||
|
<template #body>
|
||||||
|
<form @submit.prevent="saveDestination" id="destForm" autocomplete="off">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">Name</label>
|
||||||
|
<input type="text" class="form-control" v-model="destForm.name" maxlength="64" required placeholder="e.g. offsite-bucket">
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">Type</label>
|
||||||
|
<div class="select-container">
|
||||||
|
<select class="config-select" v-model="destForm.type" @change="onTypeChange">
|
||||||
|
<option v-for="t in settings.types" :key="t.id" :value="t.id">{{ t.label }}</option>
|
||||||
|
</select>
|
||||||
|
<div class="select-arrow"><i class="fas fa-chevron-down"></i></div>
|
||||||
|
</div>
|
||||||
|
<div v-if="currentType && currentType.remote && !settings.encryption_enabled" class="form-text mt-2 small text-warning">
|
||||||
|
<i class="fas fa-triangle-exclamation me-1"></i>Backups to this type need an encryption passphrase.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-for="f in currentFields" :key="f.name" class="mb-3">
|
||||||
|
<template v-if="f.kind === 'bool'">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase d-block">{{ f.label }}</label>
|
||||||
|
<div class="toggle-wrapper">
|
||||||
|
<label class="toggle-switch">
|
||||||
|
<input type="checkbox" v-model="destForm.params[f.name]">
|
||||||
|
<span class="toggle-slider"></span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template v-else-if="f.kind === 'secret'">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">{{ f.label }}</label>
|
||||||
|
<input type="password" class="form-control" v-model="destForm.secrets[f.name]"
|
||||||
|
autocomplete="new-password"
|
||||||
|
:placeholder="secretIsSet(f.name) ? '(unchanged)' : ''">
|
||||||
|
<div v-if="f.hint" class="form-text mt-1 text-muted small">{{ f.hint }}</div>
|
||||||
|
</template>
|
||||||
|
<template v-else-if="f.kind === 'secret_multiline'">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">{{ f.label }}</label>
|
||||||
|
<textarea class="form-control" rows="5" v-model="destForm.secrets[f.name]" spellcheck="false"
|
||||||
|
autocomplete="off" style="font-family: monospace; font-size: 12px;"
|
||||||
|
:placeholder="secretIsSet(f.name) ? '(unchanged: paste a new key to replace it)' : '-----BEGIN OPENSSH PRIVATE KEY-----'"></textarea>
|
||||||
|
</template>
|
||||||
|
<template v-else-if="f.kind === 'number'">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">{{ f.label }}</label>
|
||||||
|
<input type="number" class="form-control" v-model.number="destForm.params[f.name]" min="1" max="65535">
|
||||||
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">{{ f.label }}</label>
|
||||||
|
<input type="text" class="form-control" v-model="destForm.params[f.name]" :placeholder="f.default || ''">
|
||||||
|
<div v-if="f.hint" class="form-text mt-1 text-muted small">{{ f.hint }}</div>
|
||||||
|
</template>
|
||||||
|
<div v-if="f.warning && destForm.params[f.name] === f.warn_if" class="form-text mt-2 small text-warning">
|
||||||
|
<i class="fas fa-triangle-exclamation me-1"></i>{{ f.warning }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="currentType && currentType.pins_host_key" class="mb-3">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">Server host key (SHA-256)</label>
|
||||||
|
<div v-if="destForm.params.host_key" class="small text-main" style="word-break: break-all;">
|
||||||
|
{{ destForm.params.host_key }}
|
||||||
|
</div>
|
||||||
|
<div v-else class="form-text small text-warning">
|
||||||
|
<i class="fas fa-triangle-exclamation me-1"></i>Not trusted yet. Save the destination, press Test and confirm the fingerprint. Nothing is copied before that.
|
||||||
|
</div>
|
||||||
|
<div class="form-text mt-1 text-muted small">Changing the host or the port clears the trusted key.</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">Copies to keep</label>
|
||||||
|
<input type="number" class="form-control" v-model.number="destForm.retention_count" min="1" max="1000">
|
||||||
|
<div class="form-text mt-1 text-muted small">The oldest packages of this server beyond this number are deleted after a successful backup.</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mb-1 d-flex align-items-center">
|
||||||
|
<div class="toggle-wrapper me-2">
|
||||||
|
<label class="toggle-switch">
|
||||||
|
<input type="checkbox" v-model="destForm.enabled" id="destEnabled">
|
||||||
|
<span class="toggle-slider"></span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<label class="user-select-none text-muted" for="destEnabled" style="cursor: pointer;">Enabled</label>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</template>
|
||||||
|
<template #footer>
|
||||||
|
<button type="button" class="btn-action btn-action-secondary" @click="destModal.hide()">Cancel</button>
|
||||||
|
<button type="submit" form="destForm" class="btn-action btn-action-save" :disabled="saving">
|
||||||
|
<span v-if="saving" class="spinner-border spinner-border-sm me-2"></span>
|
||||||
|
{{ destForm.id ? 'Save' : 'Add' }}
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
</BaseModal>
|
||||||
|
|
||||||
|
<!-- Passphrase -->
|
||||||
|
<BaseModal id="passphraseModal" title="Encryption Passphrase" ref="passModal">
|
||||||
|
<template #body>
|
||||||
|
<form @submit.prevent="savePassphrase" id="passForm" autocomplete="off">
|
||||||
|
<p class="text-main small">
|
||||||
|
Packages made after this change are encrypted with the new passphrase. Older packages keep the
|
||||||
|
passphrase they were made with: keep it as long as you need them.
|
||||||
|
</p>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">New passphrase</label>
|
||||||
|
<input type="password" class="form-control" v-model="passForm.value" autocomplete="new-password"
|
||||||
|
placeholder="Min. 8 characters" required>
|
||||||
|
</div>
|
||||||
|
<div class="mb-2">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">Confirm passphrase</label>
|
||||||
|
<input type="password" class="form-control" v-model="passForm.confirm" autocomplete="new-password" required>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</template>
|
||||||
|
<template #footer>
|
||||||
|
<button v-if="settings.encryption_enabled" type="button" class="btn-action btn-action-danger me-auto" @click="removePassphrase" :disabled="saving">
|
||||||
|
Remove passphrase
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn-action btn-action-secondary" @click="passModal.hide()">Cancel</button>
|
||||||
|
<button type="submit" form="passForm" class="btn-action btn-action-save" :disabled="saving">
|
||||||
|
<span v-if="saving" class="spinner-border spinner-border-sm me-2"></span>
|
||||||
|
Save
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
</BaseModal>
|
||||||
|
|
||||||
|
<ConfirmModal ref="deleteModal" @confirm="confirmDelete" />
|
||||||
|
<ConfirmModal ref="restoreModal" @confirm="confirmRestore" />
|
||||||
|
<ConfirmModal ref="trustModal" @confirm="confirmTrust" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, reactive, computed, watch, onMounted, onUnmounted } from 'vue';
|
||||||
|
import { useApi } from '../composables/useApi';
|
||||||
|
import { useToast } from '../composables/useToast';
|
||||||
|
import { useFormatters } from '../composables/useFormatters';
|
||||||
|
import BaseModal from '../components/BaseModal.vue';
|
||||||
|
import ConfirmModal from '../components/ConfirmModal.vue';
|
||||||
|
|
||||||
|
const { profilesApiClient } = useApi();
|
||||||
|
const toast = useToast();
|
||||||
|
const { formatBytes } = useFormatters();
|
||||||
|
|
||||||
|
const loading = ref(true);
|
||||||
|
const saving = ref(false);
|
||||||
|
const testingId = ref(null);
|
||||||
|
const settings = reactive({ encryption_enabled: false, default_retention: 14, local_root: '', types: [],
|
||||||
|
server_name: '', effective_server_name: '', server_name_source: 'hostname' });
|
||||||
|
const serverNameInput = ref('');
|
||||||
|
const destinations = ref([]);
|
||||||
|
const history = ref([]);
|
||||||
|
const selectedIds = ref([]);
|
||||||
|
const job = reactive({ kind: null, state: 'idle', stages: [], results: [], warnings: [], message: null, relogin: false });
|
||||||
|
const restoreFinishedHere = ref(false);
|
||||||
|
|
||||||
|
const destModal = ref(null);
|
||||||
|
const passModal = ref(null);
|
||||||
|
const deleteModal = ref(null);
|
||||||
|
const restoreModal = ref(null);
|
||||||
|
const trustModal = ref(null);
|
||||||
|
|
||||||
|
const destForm = reactive({ id: null, name: '', type: 'local', enabled: true, retention_count: 14, params: {}, secrets: {} });
|
||||||
|
const existingSecrets = ref({});
|
||||||
|
const passForm = reactive({ value: '', confirm: '' });
|
||||||
|
const restore = reactive({ sourceId: null, checking: false, sourceError: '', packages: [], packageName: '', passphrase: '' });
|
||||||
|
|
||||||
|
let pollTimer = null;
|
||||||
|
|
||||||
|
const errText = (e) => e.response?.data?.detail || e.message;
|
||||||
|
const isRunning = computed(() => job.state === 'running');
|
||||||
|
const enabledDestinations = computed(() => destinations.value.filter((d) => d.enabled));
|
||||||
|
const typeInfo = (id) => settings.types.find((t) => t.id === id);
|
||||||
|
const typeLabel = (id) => typeInfo(id)?.label || id;
|
||||||
|
const currentType = computed(() => typeInfo(destForm.type));
|
||||||
|
const currentFields = computed(() => currentType.value?.fields || []);
|
||||||
|
const needsPassphrase = (d) => !!typeInfo(d.type)?.remote && !settings.encryption_enabled;
|
||||||
|
const selectedPackage = computed(() => restore.packages.find((p) => p.name === restore.packageName) || null);
|
||||||
|
const canRestore = computed(() => !isRunning.value && !!selectedPackage.value
|
||||||
|
&& (!selectedPackage.value.encrypted || restore.passphrase.length > 0));
|
||||||
|
|
||||||
|
// --- formatting ---
|
||||||
|
const formatTime = (iso) => {
|
||||||
|
if (!iso) return '';
|
||||||
|
const d = new Date(iso);
|
||||||
|
return isNaN(d) ? iso : d.toLocaleString();
|
||||||
|
};
|
||||||
|
// Package time: UTC (as in the file name) and the browser's local time
|
||||||
|
const utcTime = (iso) => (iso ? iso.replace('T', ' ').replace(/(\.\d+)?Z$/, '') + ' UTC' : '');
|
||||||
|
const packageLabel = (p) => `${p.server_name} - ${utcTime(p.created_at)} (${formatTime(p.created_at)} local) - ${formatBytes(p.size)} - ${p.encrypted ? 'encrypted' : 'not encrypted'}`;
|
||||||
|
const destinationSummary = (d) => {
|
||||||
|
const p = d.params || {};
|
||||||
|
if (d.type === 'local') return `${settings.local_root || ''}/${p.folder || ''}`.replace('//', '/');
|
||||||
|
if (d.type === 's3') return `${p.bucket}${p.prefix ? '/' + p.prefix : ''} @ ${p.endpoint}`;
|
||||||
|
if (d.type === 'sftp') return `sftp://${p.username}@${p.host}:${p.port}/${p.directory}`;
|
||||||
|
if (d.type === 'ftp') return `${p.tls ? 'ftps' : 'ftp'}://${p.username}@${p.host}:${p.port}/${p.directory}`;
|
||||||
|
return '';
|
||||||
|
};
|
||||||
|
const plainFtp = (d) => d.type === 'ftp' && d.params && d.params.tls === false;
|
||||||
|
const STAGES = {
|
||||||
|
package: 'Create package', encrypt: 'Encrypt', upload: 'Send to destinations',
|
||||||
|
download: 'Download package', decrypt: 'Decrypt', verify: 'Verify and unpack',
|
||||||
|
prepare: 'Check and migrate databases', safety_backup: 'Save current state (safety copy)',
|
||||||
|
stop_openvpn: 'Stop OpenVPN if running', replace: 'Replace data', finalize: 'Regenerate server config, start OpenVPN'
|
||||||
|
};
|
||||||
|
const stageLabel = (n) => STAGES[n] || n;
|
||||||
|
const stageIcon = (s) => ({
|
||||||
|
pending: 'far fa-circle text-muted', running: 'fas fa-spinner fa-spin text-primary',
|
||||||
|
done: 'fas fa-check-circle text-success', error: 'fas fa-times-circle text-danger'
|
||||||
|
}[s] || 'far fa-circle text-muted');
|
||||||
|
const jobBadge = (s) => ({ done: 'status-valid', partial: 'status-warning', error: 'status-expired', interrupted: 'status-expired', running: 'status-warning' }[s] || 'status-secondary');
|
||||||
|
const jobLabel = (s) => ({ done: 'Success', partial: 'Partial', error: 'Failed', interrupted: 'Interrupted', running: 'Running' }[s] || s);
|
||||||
|
const resultBadge = (s) => ({ ok: 'status-valid', error: 'status-expired', running: 'status-warning' }[s] || 'status-secondary');
|
||||||
|
const resultLabel = (s) => ({ ok: 'Stored', error: 'Failed', running: 'Sending', pending: 'Waiting', skipped: 'Skipped' }[s] || s);
|
||||||
|
|
||||||
|
// --- loading ---
|
||||||
|
const loadSettings = async () => {
|
||||||
|
const res = await profilesApiClient.get('/backup/settings');
|
||||||
|
Object.assign(settings, res.data);
|
||||||
|
serverNameInput.value = settings.server_name || '';
|
||||||
|
};
|
||||||
|
const loadDestinations = async () => {
|
||||||
|
const res = await profilesApiClient.get('/backup/destinations');
|
||||||
|
destinations.value = res.data;
|
||||||
|
// Keep the choice of the user, drop what no longer exists or is not usable
|
||||||
|
const usable = new Set(enabledDestinations.value.filter((d) => !needsPassphrase(d)).map((d) => d.id));
|
||||||
|
selectedIds.value = selectedIds.value.filter((id) => usable.has(id));
|
||||||
|
};
|
||||||
|
const loadHistory = async () => {
|
||||||
|
const res = await profilesApiClient.get('/backup/history', { params: { limit: 10 } });
|
||||||
|
history.value = res.data;
|
||||||
|
};
|
||||||
|
const selectAllUsable = () => {
|
||||||
|
selectedIds.value = enabledDestinations.value.filter((d) => !needsPassphrase(d)).map((d) => d.id);
|
||||||
|
};
|
||||||
|
|
||||||
|
const stopPolling = () => {
|
||||||
|
if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
|
||||||
|
};
|
||||||
|
const startPolling = () => {
|
||||||
|
if (!pollTimer) pollTimer = setInterval(loadStatus, 2000);
|
||||||
|
};
|
||||||
|
const loadStatus = async () => {
|
||||||
|
const wasRunning = job.state === 'running';
|
||||||
|
try {
|
||||||
|
const res = await profilesApiClient.get('/backup/status');
|
||||||
|
Object.assign(job, res.data);
|
||||||
|
} catch (e) {
|
||||||
|
return; // keep polling, the next tick may succeed
|
||||||
|
}
|
||||||
|
if (job.state === 'running') {
|
||||||
|
startPolling();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
stopPolling();
|
||||||
|
if (wasRunning) await onJobFinished();
|
||||||
|
};
|
||||||
|
|
||||||
|
const onJobFinished = async () => {
|
||||||
|
if (job.kind === 'restore') {
|
||||||
|
restoreFinishedHere.value = true;
|
||||||
|
toast.show(job.message || 'Restore finished', job.state === 'done' ? 'success' : 'error');
|
||||||
|
} else {
|
||||||
|
toast.show(job.message || 'Backup finished', job.state === 'done' ? 'success' : (job.state === 'partial' ? 'warning' : 'error'));
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await Promise.all([loadDestinations(), loadHistory()]);
|
||||||
|
} catch (e) { /* the session may be gone after a restore: the interceptor redirects */ }
|
||||||
|
if (job.kind === 'restore') await checkSource();
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- destinations ---
|
||||||
|
const defaultsFor = (typeId) => {
|
||||||
|
const params = {};
|
||||||
|
(typeInfo(typeId)?.fields || []).forEach((f) => {
|
||||||
|
if (!f.kind.startsWith('secret')) params[f.name] = f.default ?? (f.kind === 'bool' ? false : '');
|
||||||
|
});
|
||||||
|
return params;
|
||||||
|
};
|
||||||
|
const secretIsSet = (name) => !!existingSecrets.value[name];
|
||||||
|
|
||||||
|
const openAdd = () => {
|
||||||
|
const type = settings.types[0]?.id || 'local';
|
||||||
|
Object.assign(destForm, { id: null, name: '', type, enabled: true, retention_count: settings.default_retention,
|
||||||
|
params: defaultsFor(type), secrets: {} });
|
||||||
|
existingSecrets.value = {};
|
||||||
|
destModal.value.show();
|
||||||
|
};
|
||||||
|
const openEdit = (d) => {
|
||||||
|
Object.assign(destForm, { id: d.id, name: d.name, type: d.type, enabled: d.enabled,
|
||||||
|
retention_count: d.retention_count, params: { ...defaultsFor(d.type), ...d.params }, secrets: {} });
|
||||||
|
existingSecrets.value = { ...d.secrets };
|
||||||
|
destModal.value.show();
|
||||||
|
};
|
||||||
|
const onTypeChange = () => {
|
||||||
|
destForm.params = defaultsFor(destForm.type);
|
||||||
|
destForm.secrets = {};
|
||||||
|
existingSecrets.value = {};
|
||||||
|
};
|
||||||
|
const saveDestination = async () => {
|
||||||
|
saving.value = true;
|
||||||
|
const body = { name: destForm.name, type: destForm.type, enabled: destForm.enabled,
|
||||||
|
retention_count: destForm.retention_count, params: destForm.params, secrets: destForm.secrets };
|
||||||
|
try {
|
||||||
|
if (destForm.id) await profilesApiClient.put(`/backup/destinations/${destForm.id}`, body);
|
||||||
|
else await profilesApiClient.post('/backup/destinations', body);
|
||||||
|
toast.show('Destination saved.', 'success');
|
||||||
|
destModal.value.hide();
|
||||||
|
await loadDestinations();
|
||||||
|
if (!destForm.id) selectAllUsable();
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(errText(e), 'error');
|
||||||
|
} finally {
|
||||||
|
saving.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const testDestination = async (d) => {
|
||||||
|
testingId.value = d.id;
|
||||||
|
try {
|
||||||
|
const res = await profilesApiClient.post(`/backup/destinations/${d.id}/test`);
|
||||||
|
if (res.data.needs_trust) askTrust(d, res.data);
|
||||||
|
else toast.show(res.data.message, res.data.ok ? 'success' : 'error');
|
||||||
|
await loadDestinations();
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(errText(e), 'error');
|
||||||
|
} finally {
|
||||||
|
testingId.value = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// SFTP: the server shows its host key; the administrator compares the fingerprint and trusts it
|
||||||
|
const askTrust = (d, r) => {
|
||||||
|
trustModal.value.open({
|
||||||
|
title: r.key_changed ? 'Host Key Changed' : 'Trust This Server?',
|
||||||
|
message:
|
||||||
|
(r.key_changed
|
||||||
|
? 'WARNING: the server now shows a different host key than the trusted one. This happens after a reinstall of the server, but also during an attack.\n\n'
|
||||||
|
: `The server of "${d.name}" showed this host key. Compare it with the fingerprint you know (ssh-keygen -lf on the server) before you trust it.\n\n`) +
|
||||||
|
`Type: ${r.key_type}\nSHA-256: ${r.fingerprint}\n\n` +
|
||||||
|
'Packages are sent only to a server with exactly this key.',
|
||||||
|
confirmText: r.key_changed ? 'Trust the new key' : 'Trust',
|
||||||
|
confirmBtnClass: r.key_changed ? 'btn-action-danger' : 'btn-action-primary',
|
||||||
|
data: { id: d.id, name: d.name, fingerprint: r.fingerprint }
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const confirmTrust = async (t) => {
|
||||||
|
try {
|
||||||
|
await profilesApiClient.post(`/backup/destinations/${t.id}/trust-host-key`, { fingerprint: t.fingerprint });
|
||||||
|
toast.show(`Host key of ${t.name} trusted. Press Test to check the connection.`, 'success');
|
||||||
|
await loadDestinations();
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(errText(e), 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const askDelete = (d) => {
|
||||||
|
deleteModal.value.open({
|
||||||
|
title: 'Delete Destination?',
|
||||||
|
message: `Delete "${d.name}"? Packages already stored there are not deleted.`,
|
||||||
|
confirmText: 'Yes, Delete',
|
||||||
|
data: d
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const confirmDelete = async (d) => {
|
||||||
|
try {
|
||||||
|
await profilesApiClient.delete(`/backup/destinations/${d.id}`);
|
||||||
|
toast.show(`${d.name} deleted.`, 'success');
|
||||||
|
if (restore.sourceId === d.id) restore.sourceId = null;
|
||||||
|
await loadDestinations();
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(errText(e), 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- passphrase ---
|
||||||
|
const openPassphrase = () => {
|
||||||
|
passForm.value = '';
|
||||||
|
passForm.confirm = '';
|
||||||
|
passModal.value.show();
|
||||||
|
};
|
||||||
|
const savePassphrase = async () => {
|
||||||
|
if (passForm.value !== passForm.confirm) {
|
||||||
|
toast.show('Passphrases do not match.', 'error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await updateSettings({ passphrase: passForm.value }, 'Passphrase saved.');
|
||||||
|
};
|
||||||
|
const removePassphrase = async () => {
|
||||||
|
await updateSettings({ clear_passphrase: true }, 'Passphrase removed. New packages are not encrypted.');
|
||||||
|
};
|
||||||
|
const saveServerName = async () => {
|
||||||
|
const value = serverNameInput.value.trim();
|
||||||
|
if (value === (settings.server_name || '')) return;
|
||||||
|
saving.value = true;
|
||||||
|
try {
|
||||||
|
const res = await profilesApiClient.put('/backup/settings', { server_name: value });
|
||||||
|
Object.assign(settings, res.data);
|
||||||
|
serverNameInput.value = settings.server_name || '';
|
||||||
|
toast.show(value ? 'Server name saved.' : 'Server name cleared.', 'success');
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(errText(e), 'error');
|
||||||
|
} finally {
|
||||||
|
saving.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const updateSettings = async (body, okText) => {
|
||||||
|
saving.value = true;
|
||||||
|
try {
|
||||||
|
const res = await profilesApiClient.put('/backup/settings', body);
|
||||||
|
Object.assign(settings, res.data);
|
||||||
|
toast.show(okText, 'success');
|
||||||
|
passModal.value.hide();
|
||||||
|
await loadDestinations();
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(errText(e), 'error');
|
||||||
|
} finally {
|
||||||
|
saving.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- backup ---
|
||||||
|
const runBackup = async () => {
|
||||||
|
try {
|
||||||
|
await profilesApiClient.post('/backup/run', { destination_ids: selectedIds.value });
|
||||||
|
restoreFinishedHere.value = false;
|
||||||
|
job.kind = 'backup';
|
||||||
|
job.state = 'running';
|
||||||
|
await loadStatus();
|
||||||
|
startPolling();
|
||||||
|
} catch (e) {
|
||||||
|
if (e.response?.status === 409) await loadStatus();
|
||||||
|
toast.show(errText(e), 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- restore ---
|
||||||
|
const checkSource = async () => {
|
||||||
|
restore.packages = [];
|
||||||
|
restore.packageName = '';
|
||||||
|
restore.passphrase = '';
|
||||||
|
restore.sourceError = '';
|
||||||
|
if (restore.sourceId === null) return;
|
||||||
|
restore.checking = true;
|
||||||
|
try {
|
||||||
|
const res = await profilesApiClient.get(`/backup/destinations/${restore.sourceId}/packages`);
|
||||||
|
restore.packages = res.data.packages;
|
||||||
|
} catch (e) {
|
||||||
|
restore.sourceError = errText(e);
|
||||||
|
} finally {
|
||||||
|
restore.checking = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
watch(() => restore.sourceId, checkSource);
|
||||||
|
|
||||||
|
const askRestore = () => {
|
||||||
|
const p = selectedPackage.value;
|
||||||
|
restoreModal.value.open({
|
||||||
|
title: 'Restore from Backup?',
|
||||||
|
message:
|
||||||
|
`Package: ${p.server_name}, ${utcTime(p.created_at)} (${formatTime(p.created_at)} local)\n\n` +
|
||||||
|
'This replaces:\n' +
|
||||||
|
'- the monitoring database (statistics, administrator accounts, 2FA),\n' +
|
||||||
|
'- the profiler database and the server settings,\n' +
|
||||||
|
'- the PKI (CA, keys, certificates) and the client profiles.\n\n' +
|
||||||
|
'OpenVPN is stopped and started again; connected clients are disconnected. ' +
|
||||||
|
'The current state is saved to a local safety copy first. You will have to log in again.',
|
||||||
|
confirmText: 'Yes, Restore',
|
||||||
|
confirmBtnClass: 'btn-action-danger',
|
||||||
|
data: p
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const confirmRestore = async (p) => {
|
||||||
|
try {
|
||||||
|
await profilesApiClient.post('/backup/restore', {
|
||||||
|
destination_id: restore.sourceId,
|
||||||
|
package: p.name,
|
||||||
|
passphrase: p.encrypted ? restore.passphrase : null
|
||||||
|
});
|
||||||
|
restoreFinishedHere.value = false;
|
||||||
|
restore.passphrase = '';
|
||||||
|
job.kind = 'restore';
|
||||||
|
job.state = 'running';
|
||||||
|
await loadStatus();
|
||||||
|
startPolling();
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(errText(e), 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const logInAgain = () => {
|
||||||
|
localStorage.removeItem('ovpmon_token');
|
||||||
|
localStorage.removeItem('ovpmon_user');
|
||||||
|
window.location.href = '/login';
|
||||||
|
};
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
try {
|
||||||
|
await loadSettings();
|
||||||
|
await loadDestinations();
|
||||||
|
selectAllUsable();
|
||||||
|
await Promise.all([loadHistory(), loadStatus()]);
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(`Failed to load backup settings: ${errText(e)}`, 'error');
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
onUnmounted(stopPolling);
|
||||||
|
</script>
|
||||||
@@ -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>
|
||||||
@@ -88,9 +89,12 @@
|
|||||||
<tr v-if="activeCerts.length > 0" class="section-divider">
|
<tr v-if="activeCerts.length > 0" class="section-divider">
|
||||||
<td colspan="6">Active Certificates ({{ activeCerts.length }})</td>
|
<td colspan="6">Active Certificates ({{ activeCerts.length }})</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr v-for="cert in activeCerts" :key="cert.id + '_active'">
|
<tr v-for="cert in activeCerts" :key="cert.id + '_active'" style="cursor: pointer;" tabindex="0" @click="showDetails(cert)" @keydown.enter.self="showDetails(cert)">
|
||||||
<td>
|
<td v-note-tooltip="cert.note">
|
||||||
<div class="fw-semibold" style="color: var(--text-heading);">{{ cert.username }}</div>
|
<div class="fw-semibold" style="color: var(--text-heading);">
|
||||||
|
{{ cert.username }}
|
||||||
|
<i v-if="cert.note" class="fas fa-note-sticky text-muted ms-1 small"></i>
|
||||||
|
</div>
|
||||||
<div class="certificate-file text-muted small">{{ cert.file_path || 'N/A' }}</div>
|
<div class="certificate-file text-muted small">{{ cert.file_path || 'N/A' }}</div>
|
||||||
</td>
|
</td>
|
||||||
<td><span class="status-badge status-client">Client</span></td>
|
<td><span class="status-badge status-client">Client</span></td>
|
||||||
@@ -98,12 +102,12 @@
|
|||||||
<td class="fw-semibold" :class="getDaysClass(cert.days_remaining)">
|
<td class="fw-semibold" :class="getDaysClass(cert.days_remaining)">
|
||||||
{{ cert.days_remaining }}
|
{{ cert.days_remaining }}
|
||||||
</td>
|
</td>
|
||||||
<td v-html="getStatusBadgeHTML(cert)"></td>
|
<td><StatusBadge :profile="cert" /></td>
|
||||||
<td>
|
<td>
|
||||||
<button class="btn btn-sm btn-link text-warning p-0 me-2" title="Download Config" @click="downloadConfig(cert)">
|
<button class="btn btn-sm btn-link text-warning p-0 me-2" title="Download Config" @click.stop="downloadConfig(cert)">
|
||||||
<i class="fas fa-download"></i>
|
<i class="fas fa-download"></i>
|
||||||
</button>
|
</button>
|
||||||
<button class="btn btn-sm btn-link text-danger p-0" title="Revoke" @click="revokeClient(cert)">
|
<button class="btn btn-sm btn-link text-danger p-0" title="Revoke" @click.stop="revokeClient(cert)">
|
||||||
<i class="fas fa-ban"></i>
|
<i class="fas fa-ban"></i>
|
||||||
</button>
|
</button>
|
||||||
</td>
|
</td>
|
||||||
@@ -114,9 +118,12 @@
|
|||||||
<tr class="section-divider">
|
<tr class="section-divider">
|
||||||
<td colspan="6">Expired / Revoked ({{ expiredCerts.length }})</td>
|
<td colspan="6">Expired / Revoked ({{ expiredCerts.length }})</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr v-for="cert in expiredCerts" :key="cert.id + '_expired'">
|
<tr v-for="cert in expiredCerts" :key="cert.id + '_expired'" style="cursor: pointer;" tabindex="0" @click="showDetails(cert)" @keydown.enter.self="showDetails(cert)">
|
||||||
<td>
|
<td v-note-tooltip="cert.note">
|
||||||
<div class="fw-semibold" style="color: var(--text-heading);">{{ cert.username }}</div>
|
<div class="fw-semibold" style="color: var(--text-heading);">
|
||||||
|
{{ cert.username }}
|
||||||
|
<i v-if="cert.note" class="fas fa-note-sticky text-muted ms-1 small"></i>
|
||||||
|
</div>
|
||||||
<div class="certificate-file text-muted small">{{ cert.file_path || 'N/A' }}</div>
|
<div class="certificate-file text-muted small">{{ cert.file_path || 'N/A' }}</div>
|
||||||
</td>
|
</td>
|
||||||
<td><span class="status-badge status-client">Client</span></td>
|
<td><span class="status-badge status-client">Client</span></td>
|
||||||
@@ -124,9 +131,9 @@
|
|||||||
<td class="fw-semibold text-muted">
|
<td class="fw-semibold text-muted">
|
||||||
{{ cert.days_remaining }}
|
{{ cert.days_remaining }}
|
||||||
</td>
|
</td>
|
||||||
<td v-html="getStatusBadgeHTML(cert)"></td>
|
<td><StatusBadge :profile="cert" /></td>
|
||||||
<td>
|
<td>
|
||||||
<button class="btn btn-sm btn-link text-danger p-0" title="Revoke" @click="revokeClient(cert)" :disabled="cert.is_revoked">
|
<button class="btn btn-sm btn-link text-danger p-0" title="Revoke" @click.stop="revokeClient(cert)" :disabled="cert.is_revoked">
|
||||||
<i class="fas fa-ban"></i>
|
<i class="fas fa-ban"></i>
|
||||||
</button>
|
</button>
|
||||||
</td>
|
</td>
|
||||||
@@ -140,11 +147,7 @@
|
|||||||
|
|
||||||
<NewClientModal ref="newClientModal" @create="createClient" />
|
<NewClientModal ref="newClientModal" @create="createClient" />
|
||||||
<ConfirmModal ref="confirmModal" @confirm="confirmRevoke" />
|
<ConfirmModal ref="confirmModal" @confirm="confirmRevoke" />
|
||||||
|
<ProfileDetailsModal ref="detailsModal" @save="saveNote" />
|
||||||
<div v-if="toastMessage" class="toast-message show" :class="'toast-' + toastType" style="position: fixed; bottom: 20px; right: 20px; z-index: 9999;">
|
|
||||||
<i class="fas" :class="toastType === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'"></i>
|
|
||||||
{{ toastMessage }}
|
|
||||||
</div>
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
@@ -152,8 +155,15 @@ import { ref, computed, onMounted } from 'vue';
|
|||||||
import { useApi } from '../composables/useApi';
|
import { useApi } from '../composables/useApi';
|
||||||
import NewClientModal from '../components/NewClientModal.vue';
|
import NewClientModal from '../components/NewClientModal.vue';
|
||||||
import ConfirmModal from '../components/ConfirmModal.vue';
|
import ConfirmModal from '../components/ConfirmModal.vue';
|
||||||
|
import ProfileDetailsModal from '../components/ProfileDetailsModal.vue';
|
||||||
|
import StatusBadge from '../components/StatusBadge.vue';
|
||||||
|
import vNoteTooltip from '../directives/noteTooltip';
|
||||||
|
import { useToast } from '../composables/useToast';
|
||||||
|
import { usePkiStatus } from '../composables/usePkiStatus';
|
||||||
|
|
||||||
const { profilesApiClient } = useApi();
|
const { profilesApiClient } = useApi();
|
||||||
|
const toast = useToast();
|
||||||
|
const { status: pkiStatus, refresh: refreshPkiStatus } = usePkiStatus();
|
||||||
|
|
||||||
const loading = ref(true);
|
const loading = ref(true);
|
||||||
const allProfiles = ref([]);
|
const allProfiles = ref([]);
|
||||||
@@ -162,14 +172,8 @@ const hideExpired = ref(false);
|
|||||||
|
|
||||||
const newClientModal = ref(null);
|
const newClientModal = ref(null);
|
||||||
const confirmModal = ref(null);
|
const confirmModal = ref(null);
|
||||||
const toastMessage = ref('');
|
const detailsModal = ref(null);
|
||||||
const toastType = ref('success');
|
const showToast = (msg, type = 'success') => toast.show(msg, type);
|
||||||
|
|
||||||
const showToast = (msg, type = 'success') => {
|
|
||||||
toastMessage.value = msg;
|
|
||||||
toastType.value = type;
|
|
||||||
setTimeout(() => toastMessage.value = '', 3000);
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatDate = (dateStr) => {
|
const formatDate = (dateStr) => {
|
||||||
if (!dateStr) return 'N/A';
|
if (!dateStr) return 'N/A';
|
||||||
@@ -187,23 +191,6 @@ const getDaysClass = (days) => {
|
|||||||
return 'text-success';
|
return 'text-success';
|
||||||
};
|
};
|
||||||
|
|
||||||
const getStatusBadgeHTML = (cert) => {
|
|
||||||
if (cert.is_revoked) {
|
|
||||||
return '<span class="status-badge status-expired"><i class="fas fa-ban me-1"></i>Revoked</span>';
|
|
||||||
}
|
|
||||||
if (cert.is_expired) {
|
|
||||||
return '<span class="status-badge status-expired"><i class="fas fa-times-circle me-1"></i>Expired</span>';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Days check logic for expiring soon warning
|
|
||||||
if (cert.days_remaining !== null && cert.days_remaining <= 30) {
|
|
||||||
return '<span class="status-badge status-warning"><i class="fas fa-exclamation-triangle me-1"></i>Expiring Soon</span>';
|
|
||||||
}
|
|
||||||
|
|
||||||
return '<span class="status-badge status-valid"><i class="fas fa-check-circle me-1"></i>Active</span>';
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
// Data Processing
|
// Data Processing
|
||||||
const filteredData = computed(() => {
|
const filteredData = computed(() => {
|
||||||
let data = allProfiles.value;
|
let data = allProfiles.value;
|
||||||
@@ -231,8 +218,8 @@ const categorized = computed(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Sort logic
|
// Sort logic
|
||||||
active.sort((a,b) => (a.days_remaining || 9999) - (b.days_remaining || 9999));
|
active.sort((a,b) => (a.days_remaining ?? 9999) - (b.days_remaining ?? 9999));
|
||||||
expired.sort((a,b) => (b.days_remaining || -9999) - (a.days_remaining || -9999));
|
expired.sort((a,b) => (b.days_remaining ?? -9999) - (a.days_remaining ?? -9999));
|
||||||
|
|
||||||
return { active, expired };
|
return { active, expired };
|
||||||
});
|
});
|
||||||
@@ -276,6 +263,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) => {
|
const downloadConfig = async (cert) => {
|
||||||
if (!cert.id) return;
|
if (!cert.id) return;
|
||||||
try {
|
try {
|
||||||
@@ -295,6 +296,8 @@ const downloadConfig = async (cert) => {
|
|||||||
document.body.appendChild(link);
|
document.body.appendChild(link);
|
||||||
link.click();
|
link.click();
|
||||||
document.body.removeChild(link);
|
document.body.removeChild(link);
|
||||||
|
// Release the blob after the browser has started the download
|
||||||
|
setTimeout(() => window.URL.revokeObjectURL(url), 1000);
|
||||||
} catch(e) {
|
} catch(e) {
|
||||||
showToast('Could not download config: ' + (e.response?.data?.detail || e.message), 'error');
|
showToast('Could not download config: ' + (e.response?.data?.detail || e.message), 'error');
|
||||||
}
|
}
|
||||||
@@ -325,6 +328,7 @@ const confirmRevoke = async (cert) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
|
refreshPkiStatus();
|
||||||
loadCerts();
|
loadCerts();
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -12,6 +12,10 @@
|
|||||||
<div class="stat-value">{{ stats.activeClients }}</div>
|
<div class="stat-value">{{ stats.activeClients }}</div>
|
||||||
<div class="stat-label">Active Clients</div>
|
<div class="stat-label">Active Clients</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="stat-item">
|
||||||
|
<div class="stat-value">{{ stats.totalSessions }}</div>
|
||||||
|
<div class="stat-label">Active Sessions</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-3">
|
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-3">
|
||||||
@@ -52,10 +56,10 @@
|
|||||||
<th>Client Name</th>
|
<th>Client Name</th>
|
||||||
<th>Real Address</th>
|
<th>Real Address</th>
|
||||||
<th>Status</th>
|
<th>Status</th>
|
||||||
<th @click="currentSort = 'received'" class="cursor-pointer" :class="{'active-sort': currentSort === 'received'}">
|
<th @click="currentSort = 'received'" @keydown.enter="currentSort = 'received'" tabindex="0" class="cursor-pointer" :class="{'active-sort': currentSort === 'received'}">
|
||||||
Received <i v-if="currentSort === 'received'" class="fas fa-sort-down ms-1"></i>
|
Received <i v-if="currentSort === 'received'" class="fas fa-sort-down ms-1"></i>
|
||||||
</th>
|
</th>
|
||||||
<th @click="currentSort = 'sent'" class="cursor-pointer" :class="{'active-sort': currentSort === 'sent'}">
|
<th @click="currentSort = 'sent'" @keydown.enter="currentSort = 'sent'" tabindex="0" class="cursor-pointer" :class="{'active-sort': currentSort === 'sent'}">
|
||||||
Sent <i v-if="currentSort === 'sent'" class="fas fa-sort-down ms-1"></i>
|
Sent <i v-if="currentSort === 'sent'" class="fas fa-sort-down ms-1"></i>
|
||||||
</th>
|
</th>
|
||||||
<th>Down Speed</th>
|
<th>Down Speed</th>
|
||||||
@@ -78,17 +82,24 @@
|
|||||||
{{ group.status }} Clients
|
{{ group.status }} Clients
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr v-for="c in group.items" :key="c.common_name">
|
<template v-for="c in group.items" :key="c.common_name">
|
||||||
|
<tr>
|
||||||
<td>
|
<td>
|
||||||
<a @click="openHistory(c.common_name)" class="client-link">
|
<a href="#" @click.prevent="openHistory(c.common_name)" class="client-link">
|
||||||
{{ c.common_name }} <i class="fas fa-chart-area ms-1 small opacity-50"></i>
|
{{ c.common_name }} <i class="fas fa-chart-area ms-1 small opacity-50"></i>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td class="small text-muted">{{ c.real_address || '-' }}</td>
|
<td class="small text-muted">{{ c.sessions_count > 1 ? `${c.sessions_count} devices` : (c.real_address || '-') }}</td>
|
||||||
<td>
|
<td>
|
||||||
<span class="status-badge" :class="c.status === 'Active' ? 'status-active' : 'status-disconnected'">
|
<span class="status-badge" :class="c.status === 'Active' ? 'status-active' : 'status-disconnected'">
|
||||||
{{ c.status }}
|
{{ c.status }}
|
||||||
</span>
|
</span>
|
||||||
|
<button v-if="sessionsBadge(c)" type="button" class="btn btn-sm btn-outline-secondary ms-2 py-0 px-1"
|
||||||
|
:aria-expanded="expanded.includes(c.common_name)" :title="'Show sessions'"
|
||||||
|
@click="expanded = toggleExpanded(expanded, c.common_name)">
|
||||||
|
{{ sessionsBadge(c) }}
|
||||||
|
<i class="fas ms-1 small" :class="expanded.includes(c.common_name) ? 'fa-chevron-up' : 'fa-chevron-down'"></i>
|
||||||
|
</button>
|
||||||
</td>
|
</td>
|
||||||
<td class="font-monospace small">{{ formatBytes(c.total_bytes_received) }}</td>
|
<td class="font-monospace small">{{ formatBytes(c.total_bytes_received) }}</td>
|
||||||
<td class="font-monospace small">{{ formatBytes(c.total_bytes_sent) }}</td>
|
<td class="font-monospace small">{{ formatBytes(c.total_bytes_sent) }}</td>
|
||||||
@@ -109,6 +120,15 @@
|
|||||||
|
|
||||||
<td class="small text-muted">{{ formatDate(c.last_activity) }}</td>
|
<td class="small text-muted">{{ formatDate(c.last_activity) }}</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
<tr v-for="(sess, i) in visibleSessions(c, expanded)" :key="`${c.common_name}-s${i}`" class="session-row">
|
||||||
|
<td class="small text-muted ps-4"><i class="fas fa-level-up-alt fa-rotate-90 me-2 opacity-50"></i>Session {{ i + 1 }}</td>
|
||||||
|
<td class="small text-muted">{{ sess.real_address || '-' }}</td>
|
||||||
|
<td class="small text-muted" colspan="2">Since {{ formatDate(sess.connected_since) }}</td>
|
||||||
|
<td class="font-monospace small">Down {{ sess.received_mb }} MB</td>
|
||||||
|
<td class="font-monospace small">Up {{ sess.sent_mb }} MB</td>
|
||||||
|
<td colspan="2"></td>
|
||||||
|
</tr>
|
||||||
|
</template>
|
||||||
</template>
|
</template>
|
||||||
</template>
|
</template>
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -125,8 +145,9 @@ import { useApi } from '../composables/useApi';
|
|||||||
import { useFormatters } from '../composables/useFormatters';
|
import { useFormatters } from '../composables/useFormatters';
|
||||||
import HistoryModal from '../components/HistoryModal.vue';
|
import HistoryModal from '../components/HistoryModal.vue';
|
||||||
import { useAppConfig } from '../composables/useAppConfig';
|
import { useAppConfig } from '../composables/useAppConfig';
|
||||||
|
import { sessionsBadge, toggleExpanded, visibleSessions } from '../utils/sessions';
|
||||||
|
|
||||||
const { fetchStats, apiClient } = useApi();
|
const { fetchStats } = useApi();
|
||||||
const { formatBytes, formatRate, parseServerDate } = useFormatters();
|
const { formatBytes, formatRate, parseServerDate } = useFormatters();
|
||||||
const { config } = useAppConfig();
|
const { config } = useAppConfig();
|
||||||
|
|
||||||
@@ -137,6 +158,7 @@ const searchQuery = ref('');
|
|||||||
const hideDisconnected = ref(false);
|
const hideDisconnected = ref(false);
|
||||||
const currentSort = ref('sent');
|
const currentSort = ref('sent');
|
||||||
const historyModal = ref(null);
|
const historyModal = ref(null);
|
||||||
|
const expanded = ref([]); // CNs with an open session list; survives auto-refresh
|
||||||
|
|
||||||
let intervalId = null;
|
let intervalId = null;
|
||||||
|
|
||||||
@@ -144,14 +166,16 @@ const stats = computed(() => {
|
|||||||
let totalReceived = 0;
|
let totalReceived = 0;
|
||||||
let totalSent = 0;
|
let totalSent = 0;
|
||||||
let activeClients = 0;
|
let activeClients = 0;
|
||||||
|
let totalSessions = 0;
|
||||||
|
|
||||||
clients.value.forEach(c => {
|
clients.value.forEach(c => {
|
||||||
totalReceived += c.total_bytes_received || 0;
|
totalReceived += c.total_bytes_received || 0;
|
||||||
totalSent += c.total_bytes_sent || 0;
|
totalSent += c.total_bytes_sent || 0;
|
||||||
if (c.status === 'Active') activeClients++;
|
if (c.status === 'Active') activeClients++;
|
||||||
|
totalSessions += c.sessions_count || 0;
|
||||||
});
|
});
|
||||||
|
|
||||||
return { totalReceived, totalSent, activeClients };
|
return { totalReceived, totalSent, activeClients, totalSessions };
|
||||||
});
|
});
|
||||||
|
|
||||||
const filteredClients = computed(() => {
|
const filteredClients = computed(() => {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
<div class="brand-logo">
|
<div class="brand-logo">
|
||||||
<i class="fas fa-shield-alt"></i>
|
<i class="fas fa-shield-alt"></i>
|
||||||
</div>
|
</div>
|
||||||
<h1>OpenVPN Monitor</h1>
|
<h1>OpenVPN Controller</h1>
|
||||||
<p class="text-muted">Secure Access Control</p>
|
<p class="text-muted">Secure Access Control</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -13,28 +13,32 @@
|
|||||||
<!-- Standard Login -->
|
<!-- Standard Login -->
|
||||||
<form v-if="!requires2FA" @submit.prevent="handleLogin">
|
<form v-if="!requires2FA" @submit.prevent="handleLogin">
|
||||||
<div class="mb-4">
|
<div class="mb-4">
|
||||||
<label class="form-label">Username</label>
|
<label class="form-label" for="loginUsername">Username</label>
|
||||||
<div class="input-group">
|
<div class="input-group">
|
||||||
<span class="input-group-text"><i class="fas fa-user"></i></span>
|
<span class="input-group-text"><i class="fas fa-user"></i></span>
|
||||||
<input
|
<input
|
||||||
|
id="loginUsername"
|
||||||
type="text"
|
type="text"
|
||||||
class="form-control"
|
class="form-control"
|
||||||
v-model="form.username"
|
v-model="form.username"
|
||||||
placeholder="Enter username"
|
placeholder="Enter username"
|
||||||
|
autocomplete="username"
|
||||||
required
|
required
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mb-4">
|
<div class="mb-4">
|
||||||
<label class="form-label">Password</label>
|
<label class="form-label" for="loginPassword">Password</label>
|
||||||
<div class="input-group">
|
<div class="input-group">
|
||||||
<span class="input-group-text"><i class="fas fa-lock"></i></span>
|
<span class="input-group-text"><i class="fas fa-lock"></i></span>
|
||||||
<input
|
<input
|
||||||
|
id="loginPassword"
|
||||||
type="password"
|
type="password"
|
||||||
class="form-control"
|
class="form-control"
|
||||||
v-model="form.password"
|
v-model="form.password"
|
||||||
placeholder="Enter password"
|
placeholder="Enter password"
|
||||||
|
autocomplete="current-password"
|
||||||
required
|
required
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
@@ -65,6 +69,9 @@
|
|||||||
v-model="otp"
|
v-model="otp"
|
||||||
placeholder="000 000"
|
placeholder="000 000"
|
||||||
maxlength="6"
|
maxlength="6"
|
||||||
|
inputmode="numeric"
|
||||||
|
autocomplete="one-time-code"
|
||||||
|
aria-label="6-digit authentication code"
|
||||||
required
|
required
|
||||||
autofocus
|
autofocus
|
||||||
>
|
>
|
||||||
@@ -86,7 +93,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="login-footer text-center mt-4">
|
<div class="login-footer text-center mt-4">
|
||||||
<p class="small text-muted">© 2026 Admin Dashboard</p>
|
<p class="small text-muted">© 2026 OpenVPN Controller</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -98,7 +105,7 @@ import { useRouter } from 'vue-router';
|
|||||||
import { useApi } from '../composables/useApi';
|
import { useApi } from '../composables/useApi';
|
||||||
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { apiClient } = useApi();
|
const { authApiClient } = useApi();
|
||||||
const loading = ref(false);
|
const loading = ref(false);
|
||||||
const error = ref('');
|
const error = ref('');
|
||||||
const requires2FA = ref(false);
|
const requires2FA = ref(false);
|
||||||
@@ -114,9 +121,7 @@ const handleLogin = async () => {
|
|||||||
loading.value = true;
|
loading.value = true;
|
||||||
error.value = '';
|
error.value = '';
|
||||||
try {
|
try {
|
||||||
// Auth routes are under /api/auth, while apiClient defaults to /api/v1
|
const response = await authApiClient.post('/login', form);
|
||||||
// We use a relative path with '..' to go up to /api
|
|
||||||
const response = await apiClient.post('../auth/login', form);
|
|
||||||
if (response.data.requires_2fa) {
|
if (response.data.requires_2fa) {
|
||||||
requires2FA.value = true;
|
requires2FA.value = true;
|
||||||
tempToken.value = response.data.temp_token;
|
tempToken.value = response.data.temp_token;
|
||||||
@@ -137,7 +142,7 @@ const handleVerify2FA = async () => {
|
|||||||
loading.value = true;
|
loading.value = true;
|
||||||
error.value = '';
|
error.value = '';
|
||||||
try {
|
try {
|
||||||
const response = await apiClient.post('../auth/verify-2fa', {
|
const response = await authApiClient.post('/verify-2fa', {
|
||||||
temp_token: tempToken.value,
|
temp_token: tempToken.value,
|
||||||
otp: otp.value
|
otp: otp.value
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,251 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div class="login-page">
|
|
||||||
<div class="login-card">
|
|
||||||
<div class="login-header">
|
|
||||||
<div class="brand-logo">
|
|
||||||
<i class="fas fa-shield-alt"></i>
|
|
||||||
</div>
|
|
||||||
<h1>OpenVPN Monitor</h1>
|
|
||||||
<p class="text-muted">Secure Access Control</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="login-body">
|
|
||||||
<!-- Standard Login -->
|
|
||||||
<form v-if="!requires2FA" @submit.prevent="handleLogin">
|
|
||||||
<div class="mb-4">
|
|
||||||
<label class="form-label">Username</label>
|
|
||||||
<div class="input-group">
|
|
||||||
<span class="input-group-text"><i class="fas fa-user"></i></span>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
class="form-control"
|
|
||||||
v-model="form.username"
|
|
||||||
placeholder="Enter username"
|
|
||||||
required
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="mb-4">
|
|
||||||
<label class="form-label">Password</label>
|
|
||||||
<div class="input-group">
|
|
||||||
<span class="input-group-text"><i class="fas fa-lock"></i></span>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
class="form-control"
|
|
||||||
v-model="form.password"
|
|
||||||
placeholder="Enter password"
|
|
||||||
required
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div v-if="error" class="alert alert-danger fade show mb-4">
|
|
||||||
<i class="fas fa-exclamation-circle me-2"></i>{{ error }}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button type="submit" class="btn btn-primary w-100 py-2 fw-bold" :disabled="loading">
|
|
||||||
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
|
||||||
Sign In
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<!-- 2FA Verification -->
|
|
||||||
<form v-else @submit.prevent="handleVerify2FA">
|
|
||||||
<div class="text-center mb-4">
|
|
||||||
<i class="fas fa-key fa-3x text-warning mb-3"></i>
|
|
||||||
<h3>Two-Factor Authentication</h3>
|
|
||||||
<p class="text-muted">Enter the 6-digit code from your authenticator app.</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="mb-4">
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
class="form-control form-control-lg text-center fw-bold"
|
|
||||||
v-model="otp"
|
|
||||||
placeholder="000 000"
|
|
||||||
maxlength="6"
|
|
||||||
required
|
|
||||||
autofocus
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div v-if="error" class="alert alert-danger fade show mb-4">
|
|
||||||
<i class="fas fa-exclamation-circle me-2"></i>{{ error }}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button type="submit" class="btn btn-warning w-100 py-2 fw-bold" :disabled="loading">
|
|
||||||
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
|
||||||
Verify & Continue
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<button type="button" class="btn btn-link w-100 mt-2 text-muted" @click="resetLogin">
|
|
||||||
Back to login
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="login-footer text-center mt-4">
|
|
||||||
<p class="small text-muted">© 2026 Admin Dashboard</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script setup>
|
|
||||||
import { reactive, ref } from 'vue';
|
|
||||||
import { useRouter } from 'vue-router';
|
|
||||||
import { useApi } from '../composables/useApi';
|
|
||||||
|
|
||||||
const router = useRouter();
|
|
||||||
const { apiClient } = useApi();
|
|
||||||
const loading = ref(false);
|
|
||||||
const error = ref('');
|
|
||||||
const requires2FA = ref(false);
|
|
||||||
const tempToken = ref('');
|
|
||||||
const otp = ref('');
|
|
||||||
|
|
||||||
const form = reactive({
|
|
||||||
username: '',
|
|
||||||
password: ''
|
|
||||||
});
|
|
||||||
|
|
||||||
const handleLogin = async () => {
|
|
||||||
loading.value = true;
|
|
||||||
error.value = '';
|
|
||||||
try {
|
|
||||||
// Auth routes are under /api/auth, while apiClient defaults to /api/v1
|
|
||||||
// We use a relative path with '..' to go up to /api
|
|
||||||
const response = await apiClient.post('../auth/login', form);
|
|
||||||
if (response.data.requires_2fa) {
|
|
||||||
requires2FA.value = true;
|
|
||||||
tempToken.value = response.data.temp_token;
|
|
||||||
} else {
|
|
||||||
localStorage.setItem('ovpmon_token', response.data.token);
|
|
||||||
localStorage.setItem('ovpmon_user', response.data.username);
|
|
||||||
router.push('/');
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Login Error:', err);
|
|
||||||
error.value = err.response?.data?.error || 'Login failed. Please check your connection.';
|
|
||||||
} finally {
|
|
||||||
loading.value = false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleVerify2FA = async () => {
|
|
||||||
loading.value = true;
|
|
||||||
error.value = '';
|
|
||||||
try {
|
|
||||||
const response = await apiClient.post('../auth/verify-2fa', {
|
|
||||||
temp_token: tempToken.value,
|
|
||||||
otp: otp.value
|
|
||||||
});
|
|
||||||
localStorage.setItem('ovpmon_token', response.data.token);
|
|
||||||
localStorage.setItem('ovpmon_user', response.data.username);
|
|
||||||
router.push('/');
|
|
||||||
} catch (err) {
|
|
||||||
error.value = err.response?.data?.error || 'Verification failed.';
|
|
||||||
} finally {
|
|
||||||
loading.value = false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const resetLogin = () => {
|
|
||||||
requires2FA.value = false;
|
|
||||||
tempToken.value = '';
|
|
||||||
otp.value = '';
|
|
||||||
error.value = '';
|
|
||||||
};
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.login-page {
|
|
||||||
min-height: 100vh;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
background-color: var(--bg-body);
|
|
||||||
padding: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.login-card {
|
|
||||||
width: 100%;
|
|
||||||
max-width: 400px;
|
|
||||||
background: var(--bg-card);
|
|
||||||
padding: 40px;
|
|
||||||
border-radius: 12px;
|
|
||||||
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
|
|
||||||
border: 1px solid var(--border-color);
|
|
||||||
}
|
|
||||||
|
|
||||||
.login-header {
|
|
||||||
text-align: center;
|
|
||||||
margin-bottom: 30px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.brand-logo {
|
|
||||||
width: 60px;
|
|
||||||
height: 60px;
|
|
||||||
background: var(--accent-color);
|
|
||||||
color: white;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
font-size: 24px;
|
|
||||||
border-radius: 12px;
|
|
||||||
margin: 0 auto 15px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.login-header h1 {
|
|
||||||
font-size: 24px;
|
|
||||||
font-weight: 700;
|
|
||||||
margin: 0;
|
|
||||||
color: var(--text-heading);
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-label {
|
|
||||||
font-weight: 600;
|
|
||||||
font-size: 0.85rem;
|
|
||||||
color: var(--text-heading);
|
|
||||||
}
|
|
||||||
|
|
||||||
.input-group-text {
|
|
||||||
background: var(--bg-element);
|
|
||||||
border-color: var(--border-color);
|
|
||||||
color: var(--text-muted);
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-control {
|
|
||||||
background: var(--bg-input);
|
|
||||||
border-color: var(--border-color);
|
|
||||||
color: var(--text-main);
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-control:focus {
|
|
||||||
border-color: var(--accent-color);
|
|
||||||
box-shadow: 0 0 0 3px rgba(9, 105, 218, 0.1);
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-primary {
|
|
||||||
background-color: #1652B8;
|
|
||||||
border-color: #1652B8;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-primary:hover {
|
|
||||||
background-color: #1449a5;
|
|
||||||
border-color: #1449a5;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-warning {
|
|
||||||
background-color: #EC7C31;
|
|
||||||
border-color: #EC7C31;
|
|
||||||
color: white;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-warning:hover {
|
|
||||||
background-color: #d66d2a;
|
|
||||||
border-color: #d66d2a;
|
|
||||||
color: white;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
+102
-35
@@ -5,10 +5,6 @@
|
|||||||
<h1>PKI Infrastructure Configuration</h1>
|
<h1>PKI Infrastructure Configuration</h1>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-if="message.text" :class="['toast-message', 'toast-' + message.type, 'show']">
|
|
||||||
<i :class="['fas', message.icon]"></i> {{ message.text }}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form @submit.prevent="handleSave">
|
<form @submit.prevent="handleSave">
|
||||||
<div class="config-row">
|
<div class="config-row">
|
||||||
<div class="config-col">
|
<div class="config-col">
|
||||||
@@ -149,33 +145,42 @@
|
|||||||
|
|
||||||
|
|
||||||
<div class="btn-action-group">
|
<div class="btn-action-group">
|
||||||
<button type="button" class="btn-action btn-action-save" @click="handleSave" :disabled="isLoading">
|
<button type="button" class="btn-action btn-action-save" @click="handleSave" :disabled="isBusy">
|
||||||
<i class="fas fa-save"></i>
|
<i class="fas fa-save"></i>
|
||||||
Save PKI
|
Save PKI
|
||||||
</button>
|
</button>
|
||||||
<button type="button" class="btn-action btn-action-primary" @click="handleInit" :disabled="isLoading">
|
<button type="button" class="btn-action btn-action-primary" @click="handleInit" :disabled="isBusy || initStatus.initialized"
|
||||||
<i v-if="isLoading && action==='init'" class="fas fa-spinner fa-spin"></i>
|
:title="initStatus.initialized ? 'PKI is already initialized. Use Clear PKI to start over' : ''">
|
||||||
|
<i v-if="isInitRunning" class="fas fa-spinner fa-spin"></i>
|
||||||
<i v-else class="fas fa-play-circle"></i>
|
<i v-else class="fas fa-play-circle"></i>
|
||||||
Init PKI
|
Init PKI
|
||||||
</button>
|
</button>
|
||||||
<button type="button" class="btn-action btn-action-danger" @click="handleClear" :disabled="isLoading">
|
<button type="button" class="btn-action btn-action-danger" @click="handleClear" :disabled="isBusy">
|
||||||
<i v-if="isLoading && action==='clear'" class="fas fa-spinner fa-spin"></i>
|
<i v-if="isLoading && action==='clear'" class="fas fa-spinner fa-spin"></i>
|
||||||
<i v-else class="fas fa-trash-alt"></i>
|
<i v-else class="fas fa-trash-alt"></i>
|
||||||
Clear PKI
|
Clear PKI
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
<div v-if="isInitRunning" class="config-label">{{ stepText }}</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<ConfirmModal ref="initModal" @confirm="runInit" />
|
||||||
|
<ConfirmModal ref="clearModal" @confirm="runClear" />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref, onMounted, reactive } from 'vue';
|
import { ref, computed, onMounted, onUnmounted, reactive } from 'vue';
|
||||||
|
|
||||||
import { useApi } from '../composables/useApi';
|
import { useApi } from '../composables/useApi';
|
||||||
|
import { useToast } from '../composables/useToast';
|
||||||
|
import { usePkiStatus } from '../composables/usePkiStatus';
|
||||||
|
import ConfirmModal from '../components/ConfirmModal.vue';
|
||||||
|
|
||||||
const { profilesApiClient } = useApi();
|
const { profilesApiClient } = useApi();
|
||||||
|
const toast = useToast();
|
||||||
|
const { refresh: refreshPkiStatus } = usePkiStatus();
|
||||||
|
|
||||||
// State
|
// State
|
||||||
const form = reactive({
|
const form = reactive({
|
||||||
@@ -196,26 +201,30 @@ const form = reactive({
|
|||||||
easyrsa_batch: true
|
easyrsa_batch: true
|
||||||
});
|
});
|
||||||
|
|
||||||
const message = reactive({
|
const initModal = ref(null);
|
||||||
text: '',
|
const clearModal = ref(null);
|
||||||
type: 'success', // success, warning, error (mapped to css classes)
|
|
||||||
icon: 'fa-check-circle'
|
|
||||||
});
|
|
||||||
|
|
||||||
const isLoading = ref(false);
|
const isLoading = ref(false);
|
||||||
const action = ref(''); // 'save', 'init', 'clear'
|
const action = ref(''); // 'save', 'init', 'clear'
|
||||||
|
|
||||||
// Methods
|
// PKI init job state, taken from the server (GET /system/init/status)
|
||||||
const showMessage = (text, type = 'success') => {
|
const initStatus = reactive({ state: 'idle', step: null, initialized: false, error: null });
|
||||||
message.text = text;
|
const isInitRunning = computed(() => initStatus.state === 'running' || action.value === 'init');
|
||||||
message.type = type;
|
const isBusy = computed(() => isLoading.value || isInitRunning.value);
|
||||||
message.icon = type === 'success' ? 'fa-check-circle' : type === 'warning' ? 'fa-exclamation-triangle' : 'fa-exclamation-circle';
|
|
||||||
|
|
||||||
// Auto hide
|
const STEP_TEXTS = {
|
||||||
setTimeout(() => {
|
'init-pki': 'Initializing PKI...',
|
||||||
message.text = '';
|
'ca': 'Building CA...',
|
||||||
}, 4000);
|
'server-cert': 'Building server certificate...',
|
||||||
|
'dh': 'Generating DH parameters (this can take several minutes)...',
|
||||||
|
'ta-key': 'Generating TLS key...',
|
||||||
|
'crl': 'Generating CRL...'
|
||||||
};
|
};
|
||||||
|
const stepText = computed(() => STEP_TEXTS[initStatus.step] || 'Initializing PKI...');
|
||||||
|
|
||||||
|
let pollTimer = null;
|
||||||
|
|
||||||
|
// Methods
|
||||||
|
const showMessage = (text, type = 'success') => toast.show(text, type);
|
||||||
|
|
||||||
// API Fetch Wrapper
|
// API Fetch Wrapper
|
||||||
// API Wrapper removed, using profilesApiClient directly
|
// API Wrapper removed, using profilesApiClient directly
|
||||||
@@ -228,7 +237,7 @@ const loadConfig = async () => {
|
|||||||
|
|
||||||
// Populate form
|
// Populate form
|
||||||
Object.keys(data).forEach(key => {
|
Object.keys(data).forEach(key => {
|
||||||
if (form.hasOwnProperty(key)) {
|
if (Object.hasOwn(form, key)) {
|
||||||
form[key] = data[key];
|
form[key] = data[key];
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -238,6 +247,40 @@ const loadConfig = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const stopPolling = () => {
|
||||||
|
if (pollTimer) {
|
||||||
|
clearInterval(pollTimer);
|
||||||
|
pollTimer = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const startPolling = () => {
|
||||||
|
if (!pollTimer) pollTimer = setInterval(() => loadStatus(), 3000);
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadStatus = async (initial = false) => {
|
||||||
|
const wasRunning = initStatus.state === 'running';
|
||||||
|
try {
|
||||||
|
const res = await profilesApiClient.get('/system/init/status');
|
||||||
|
Object.assign(initStatus, res.data);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
return; // keep polling, the next tick may succeed
|
||||||
|
}
|
||||||
|
if (initStatus.state === 'running') {
|
||||||
|
startPolling();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
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
|
||||||
|
if (wasRunning && initStatus.state === 'done') {
|
||||||
|
showMessage('PKI initialized successfully!', 'success');
|
||||||
|
} else if ((wasRunning || initial) && initStatus.state === 'error') {
|
||||||
|
showMessage(`Error initializing: ${initStatus.error}`, 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
isLoading.value = true;
|
isLoading.value = true;
|
||||||
action.value = 'save';
|
action.value = 'save';
|
||||||
@@ -252,34 +295,55 @@ const handleSave = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleInit = async () => {
|
const handleInit = () => {
|
||||||
if (!confirm('Are you sure you want to Initialize system? This will start the PKI initialization process.')) return;
|
initModal.value.open({
|
||||||
|
title: 'Initialize PKI?',
|
||||||
|
message: 'Are you sure you want to initialize the system? This will start the PKI initialization process.',
|
||||||
|
confirmText: 'Yes, initialize',
|
||||||
|
confirmBtnClass: 'btn-action-primary'
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const runInit = async () => {
|
||||||
isLoading.value = true;
|
isLoading.value = true;
|
||||||
action.value = 'init';
|
action.value = 'init'; // locks the button until the server confirms the job state
|
||||||
try {
|
try {
|
||||||
const res = await profilesApiClient.post('/system/init');
|
await profilesApiClient.post('/system/init');
|
||||||
const data = res.data;
|
initStatus.state = 'running'; // 202: the job is running in the background
|
||||||
showMessage(data.message || 'System initialized successfully!', 'success');
|
startPolling();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
showMessage(`Error initializing: ${err.message}`, 'error');
|
if (err.response && err.response.status === 409) {
|
||||||
|
// Already running (second tab) or already initialized: attach to the server state
|
||||||
|
await loadStatus();
|
||||||
|
} else {
|
||||||
|
showMessage(`Error initializing: ${err.response?.data?.detail || err.message}`, 'error');
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
isLoading.value = false;
|
isLoading.value = false;
|
||||||
action.value = '';
|
action.value = '';
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleClear = async () => {
|
const handleClear = () => {
|
||||||
if (!confirm('Are you sure you want to CLEAR PKI? This will delete all certificates and cannot be undone.')) return;
|
clearModal.value.open({
|
||||||
|
title: 'Clear PKI?',
|
||||||
|
message: 'Are you sure you want to CLEAR the PKI? This will delete all certificates and cannot be undone.',
|
||||||
|
confirmText: 'Yes, clear',
|
||||||
|
confirmBtnClass: 'btn-action-danger'
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const runClear = async () => {
|
||||||
isLoading.value = true;
|
isLoading.value = true;
|
||||||
action.value = 'clear';
|
action.value = 'clear';
|
||||||
try {
|
try {
|
||||||
const res = await profilesApiClient.delete('/system/pki');
|
const res = await profilesApiClient.delete('/system/pki');
|
||||||
const data = res.data;
|
const data = res.data;
|
||||||
showMessage(data.message || 'PKI cleared successfully!', 'warning');
|
showMessage(data.message || 'PKI cleared successfully!', 'warning');
|
||||||
|
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 = '';
|
||||||
@@ -288,5 +352,8 @@ const handleClear = async () => {
|
|||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
loadConfig();
|
loadConfig();
|
||||||
|
loadStatus(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
onUnmounted(stopPolling);
|
||||||
</script>
|
</script>
|
||||||
Loaded 100 of 243 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user