Compare commits

..
23 Commits
Author SHA1 Message Date
ayurishchevandClaude Sonnet 5.5 79c950f8f7 Prod upgrade fixes: profiler compatibility with new FastAPI, pinned dependencies
- profiler: Literal instead of Query(enum=...) (broke on FastAPI 0.162)
- pin fastapi/starlette/uvicorn/pydantic for the profiler, upper bounds for APP_CORE
- health check: show the service log when an HTTP check fails
- update.sh: the "before" version comes from deploy.state
- migrate.py: hint about OVPMON_*_DB_PATH when the default database is missing
- docs: --source --no-pull mode, dependency pinning, PIP_CONSTRAINT
- tests: new test for the section parameter, fixed test_server_process.py

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 00:03:39 +03:00
ayurishchevandClaude Sonnet 5.5 1bbf9b7cc1 Clients UI: show several sessions of one user
- API: /api/v1/stats returns sessions_count and sessions per client
- UI: badge "xN", "N devices", expandable session list, Active Sessions KPI
- deploy/ui-dist rebuilt, docs: plan, summary, API reference, UI architecture

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 18:49:40 +03:00
ayurishchev 4815821f17 Merge pull request 'Docs restructure gatherer jwt hardening' (#2) from docs-restructure-gatherer-jwt-hardening into main
Reviewed-on: #2
2026-10-07 16:46:35 +03:00
ayurishchevandClaude Sonnet 5.5 00eacbbca8 Docs: plan and summary for the average speed over 24 hours, API and data architecture notes
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KC7BXv32Jwj8mY5sKX8u2F
2026-10-07 14:30:01 +03:00
ayurishchevandClaude Sonnet 5.5 b3466f9c61 History and Analytics: average speed from bytes for periods over 24 hours
The aggregate tables (stats_*) keep only bytes, and the queries returned 0 as speed, so the Speed
mode was empty for 7d and 30d. Speed is now the bucket average: bytes * 8 / 1e6 / bucket seconds;
for the current incomplete bucket the duration is min(bucket length, time since its start), at least
1 s. Series are labelled "RX Mbps (avg)" / "TX Mbps (avg)" for ranges over 24h. One test.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KC7BXv32Jwj8mY5sKX8u2F
2026-10-07 14:28:02 +03:00
ayurishchevandClaude Sonnet 5.5 e364a40e4b Backup UI: plan and summary for the badges alignment
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KC7BXv32Jwj8mY5sKX8u2F
2026-10-07 14:11:32 +03:00
ayurishchevandClaude Sonnet 5.5 87d8bbcd8c Backup UI: align badges in the Destinations table to the top of the row
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KC7BXv32Jwj8mY5sKX8u2F
2026-10-07 14:10:31 +03:00
ayurishchevandClaude Sonnet 5.5 b61989bd22 UI delivery: plan, summary and docs (CSP origins, --csp-connect-extra, nginx-unprivileged)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:33:27 +03:00
ayurishchevandClaude Sonnet 5.5 3347fffe8e UI delivery, stage D: app-ui image on nginx-unprivileged (user nginx, port 8080)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:31:53 +03:00
ayurishchevandClaude Sonnet 5.5 71ea4c5945 UI delivery, stage C: npm ci in the all-in-one image build
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:29:45 +03:00
ayurishchevandClaude Sonnet 5.5 d5e83eaff5 UI delivery, stage B: single CSP with optional connect-src origins (OVPMON_CSP_CONNECT_EXTRA)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:28:30 +03:00
ayurishchevandClaude Sonnet 5.5 d38acd74de UI delivery, stage A: rebuild deploy/ui-dist from current APP_UI sources
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:19:27 +03:00
ayurishchevandClaude Sonnet 5.5 9443ab6fce UI review: docs, summary and plan
Summary of U1-U18, change log row, APP_UI README, UI architecture,
accepted risk of the token in localStorage.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:14:40 +03:00
ayurishchevandClaude Sonnet 5.5 32d6b0e525 UI review, stage 4: accessibility, product name, favicon, ESLint
Login: label for/id, autocomplete, inputmode for the 2FA code; clickable
table rows, headers and client links work from the keyboard. One product
name (OpenVPN Controller), own favicon (logo.svg) instead of vite.svg,
footer text fixed. Minimal ESLint config (npm run lint, clean).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:13:25 +03:00
ayurishchevandClaude Sonnet 5.5 897c82ab88 UI review, stage 3: cleanup, shared chart code, confirmations, routing
useTrafficChart composable replaces the duplicated chart code in Analytics
and HistoryModal; theme observer is released on unmount; blob URLs are
revoked. ConfirmModal gets a unique id; confirm() in Server/PKI and
SweetAlert2 in Account are replaced by ConfirmModal and toasts, sweetalert2
and sass removed. Separate authApiClient for /api/auth. 404 redirect, lazy
Clients, token-based isAuthenticated, theme from prefers-color-scheme set
before mount. BaseModal reactive size, NewClientModal name check and focus
on opened, HistoryModal ignores stale answers. Login.vue.bak, the dead
global axios interceptor and empty <p> removed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:10:41 +03:00
ayurishchevandClaude Sonnet 5.5 600119cdd1 UI review, stage 2: nginx security headers, gzip, cache; npm ci; no v-html
default.conf.template: X-Content-Type-Options, X-Frame-Options,
Referrer-Policy, CSP, gzip, immutable cache for /assets/, no-cache for
index.html and config.json, server_tokens off, drop proxy_pass_header.
Dockerfile uses npm ci, .dockerignore added (nginx stays root: the image
entrypoint and port 80 need it). Status badge is a component instead of
v-html.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:07:16 +03:00
ayurishchevandClaude Sonnet 5.5 b78de98f26 UI review, stage 1: 401 on /auth/*, expiring certs, VPN netmask, formatBytes
401 from change-password/change-username no longer logs the user out;
Analytics reads the plain /profiles array; VPN settings send vpn_netmask
with vpn_network (the API reset it to 255.255.255.0); formatBytes guards
null/NaN/negative; Certificates sorts 0 days correctly. Vitest added for
formatters, CIDR parsing and the 401 interceptor.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:05:55 +03:00
ayurishchevandClaude Sonnet 5.5 3fac8d70d8 Deploy scripts: compose version check, ovpmon_backup.db in native backups
Docker: variant B needs Docker Compose 2.17+ (additional_contexts); install.sh
and update.sh check it in the preflight. Native: backup.sh, update.sh,
restore.sh and --rollback now copy and restore ovpmon_backup.db (Backup and
Restore settings) as an optional file. Verified install, update, backup,
restore and rollback on Debian 12 (systemd), Alpine 3.23 (OpenRC) and both
container variants.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 12:58:42 +03:00
ayurishchevandClaude Sonnet 5.5 f8cdcd0fc6 Backup and Restore: packages, Local/S3/SFTP/FTP destinations, UI and API
Encrypted packages (databases, PKI, client profiles) with safe restore and
a pre-restore safety copy, usable for server-to-server migration across
container and system-service installs. New Management page, ovp_backups
volume, migrations code in the profiler image, server name in package names.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 09:38:09 +03:00
ayurishchevandClaude Sonnet 5.5 d29c261347 OpenVPN templates: drop windows-driver, tls-client, client user/group
windows-driver was removed in OpenVPN 2.7 and broke clients; add
explicit-exit-notify for UDP clients, tidy the server template.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 09:38:09 +03:00
ayurishchevandClaude Sonnet 5.5 7d6f44c965 Gatherer: aggregate several sessions of one user under the account
Session key uses the OpenVPN Client ID (survives float), one usage_history
row per user per tick, summed speeds in the API, last_bytes/real_address
per account, migration 2 (active_sessions.session_id). Also throttles the
"status file missing" log and reports recovery.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 09:38:09 +03:00
ayurishchev f8c2f3c21d Merge pull request 'Docs restructure, code review, gatherer reliability, JWT key fail-closed' (#1) from docs-restructure-gatherer-jwt-hardening into main
Reviewed-on: #1
2026-10-05 20:33:02 +03:00
ayurishchevandClaude Sonnet 5.5 ad6995bb63 Docs restructure, code review, gatherer reliability, JWT key fail-closed
Documentation
- Three levels: DOCS/General (overview, configuration), DOCS/Deployment
  (choose a method, first steps), details per method in Containers/ and
  System_Services/; new root README and DOCS/README map.
- Remove superseded pages (Deployment.md, Deployment_Docker/Native.md, Index.md);
  split the two scenario guides by section.
- Isolate the Timeweb/Hysteria2 records in DEPLOYMENTS/timeweb-hysteria2/
  (not linked from DOCS, listed in .graphifyignore).
- Add DOCS/code_review/ with a time-stamped analysis of the code base.

Gatherer (BUG-02, BUG-03)
- Session key (CN, address, connected_since_ts), baseline from the
  active_sessions snapshot, grace period for sessions missing from the status.
- Status file integrity (TITLE/TIME/END) and freshness; a torn read skips the tick.
- Cache applied after commit; main loop survives exceptions, backs off, and
  stops cleanly on SIGTERM/SIGINT; new client rows start with the first
  frame's totals; five tests.

JWT signing key (SEC-01)
- No built-in default: Core and Profiler refuse to start with a missing,
  placeholder or short (< 32) key; shipped config.ini has an empty value.
- Same rule in install.sh, update.sh (issues a new key when missing or weak),
  docker lib/entrypoint; five tests, conftest.py for the test key.

Each change has a plan and a summary under DOCS/Changes/.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-05 20:30:45 +03:00
207 changed files with 11209 additions and 2318 deletions

No files matched your search

+3
View File
@@ -8,3 +8,6 @@ deploy/native/ui-dist.tar.gz
# Python caches (tests and compile steps create them inside the tree)
__pycache__/
*.pyc
# local development environment
venv/
+5
View File
@@ -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/
+4
View File
@@ -13,6 +13,7 @@ The **Core Monitoring** module provides the backend logic for collecting, extrac
- A background service/daemon.
- Parses OpenVPN server logs (`status.log`).
- 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
@@ -26,6 +27,9 @@ python3 -m venv venv
source venv/bin/activate
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
python3 openvpn_api_v3.py
+9 -1
View File
@@ -2,12 +2,20 @@
host = 0.0.0.0
port = 5001
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]
log_path = /var/log/openvpn/openvpn-status.log
db_path = openvpn_monitor.db
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]
level = INFO
+6
View File
@@ -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)
+3
View File
@@ -37,6 +37,9 @@ def main(argv=None):
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:
+9
View File
@@ -459,8 +459,17 @@ def _m001_baseline(conn):
_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
+108 -33
View File
@@ -10,6 +10,7 @@ import pyotp
import bcrypt
from functools import wraps
from db import DatabaseManager
from secret_key import resolve_secret_key, SecretKeyError
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)
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:
def get_config_value(self, section, key, fallback=None):
try:
@@ -41,18 +65,27 @@ class OpenVPNAPI:
return fallback
def __init__(self, config_file='config.ini'):
self.db_manager = DatabaseManager(config_file)
self.db_manager.init_database()
self.config = configparser.ConfigParser()
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
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
self.ensure_default_admin()
@@ -159,15 +192,20 @@ class OpenVPNAPI:
c.total_bytes_received,
c.total_bytes_sent,
-- Пиковая скорость Download за последние 2 минуты
(SELECT MAX(uh.bytes_received_rate_mbps)
FROM usage_history uh
WHERE uh.client_id = c.id
AND uh.timestamp >= datetime('now', '-30 seconds')) as current_recv_rate,
-- (скорость пользователя = сумма по его сессиям на одной отметке времени)
(SELECT MAX(s.rate) FROM (
SELECT SUM(uh.bytes_received_rate_mbps) as rate
FROM usage_history uh
WHERE uh.client_id = c.id
AND uh.timestamp >= datetime('now', '-30 seconds')
GROUP BY uh.timestamp) s) as current_recv_rate,
-- Пиковая скорость Upload за последние 2 минуты
(SELECT MAX(uh.bytes_sent_rate_mbps)
FROM usage_history uh
WHERE uh.client_id = c.id
AND uh.timestamp >= datetime('now', '-30 seconds')) as current_sent_rate,
(SELECT MAX(s.rate) FROM (
SELECT SUM(uh.bytes_sent_rate_mbps) as rate
FROM usage_history uh
WHERE uh.client_id = c.id
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
FROM clients c
ORDER BY c.status DESC, c.common_name
@@ -178,7 +216,32 @@ class OpenVPNAPI:
for row in cursor.fetchall():
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
except Exception as e:
@@ -278,17 +341,27 @@ class OpenVPNAPI:
points_count = 96
if is_high_res:
# Внутренний запрос: сумма по сессиям на одной отметке времени
# (старые строки хранят по записи на сессию), внешний: MAX скорости в интервале
query = f'''
SELECT
datetime((strftime('%s', uh.timestamp) / {interval}) * {interval}, 'unixepoch') as timestamp,
SUM(uh.bytes_received) as bytes_received,
SUM(uh.bytes_sent) as bytes_sent,
MAX(uh.bytes_received_rate_mbps) as bytes_received_rate_mbps,
MAX(uh.bytes_sent_rate_mbps) as bytes_sent_rate_mbps
FROM usage_history uh
JOIN clients c ON uh.client_id = c.id
WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ?
GROUP BY datetime((strftime('%s', uh.timestamp) / {interval}) * {interval}, 'unixepoch')
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_sent) as bytes_sent,
SUM(uh.bytes_received_rate_mbps) as bytes_received_rate_mbps,
SUM(uh.bytes_sent_rate_mbps) as bytes_sent_rate_mbps
FROM usage_history uh
JOIN clients c ON uh.client_id = c.id
WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ?
GROUP BY uh.timestamp
) u
GROUP BY datetime((strftime('%s', u.timestamp) / {interval}) * {interval}, 'unixepoch')
ORDER BY timestamp ASC
'''
elif is_aggregated:
@@ -297,8 +370,8 @@ class OpenVPNAPI:
t.timestamp,
t.bytes_received,
t.bytes_sent,
0 as bytes_received_rate_mbps,
0 as bytes_sent_rate_mbps
{avg_rate_sql(target_table, 't.bytes_received', 't.timestamp')} as bytes_received_rate_mbps,
{avg_rate_sql(target_table, 't.bytes_sent', 't.timestamp')} as bytes_sent_rate_mbps
FROM {target_table} t
JOIN clients c ON t.client_id = c.id
WHERE c.common_name = ? AND t.timestamp BETWEEN ? AND ?
@@ -308,13 +381,14 @@ class OpenVPNAPI:
query = f'''
SELECT
uh.timestamp,
uh.bytes_received,
uh.bytes_sent,
uh.bytes_received_rate_mbps,
uh.bytes_sent_rate_mbps
SUM(uh.bytes_received) as bytes_received,
SUM(uh.bytes_sent) as bytes_sent,
SUM(uh.bytes_received_rate_mbps) as bytes_received_rate_mbps,
SUM(uh.bytes_sent_rate_mbps) as bytes_sent_rate_mbps
FROM usage_history uh
JOIN clients c ON uh.client_id = c.id
WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ?
GROUP BY uh.timestamp
ORDER BY uh.timestamp ASC
'''
@@ -451,7 +525,8 @@ class OpenVPNAPI:
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,"
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
# Group by interval_seconds
+467 -223
View File
@@ -1,11 +1,29 @@
import sqlite3
import time
import os
import calendar
import signal
import threading
import configparser
import logging
from collections import namedtuple
from datetime import datetime, timedelta
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) ---
class TimeSeriesAggregator:
def __init__(self, db_provider):
@@ -34,24 +52,24 @@ class TimeSeriesAggregator:
conn = self.db_provider()
cursor = conn.cursor()
now = datetime.utcnow()
# --- РАСЧЕТ ВРЕМЕННЫХ КВАНТОВ ---
# 1. Сутки (00:00:00)
ts_1d = now.replace(hour=0, minute=0, second=0, microsecond=0).strftime('%Y-%m-%d %H:%M:%S')
# 2. 6 часов (00, 06, 12, 18)
hour_6h = now.hour - (now.hour % 6)
ts_6h = now.replace(hour=hour_6h, minute=0, second=0, microsecond=0).strftime('%Y-%m-%d %H:%M:%S')
# 3. 1 час (XX:00:00)
ts_1h = now.replace(minute=0, second=0, microsecond=0).strftime('%Y-%m-%d %H:%M:%S')
# 4. 15 минут (00, 15, 30, 45)
min_15m = now.minute - (now.minute % 15)
ts_15m = now.replace(minute=min_15m, second=0, microsecond=0).strftime('%Y-%m-%d %H:%M:%S')
# 5. 5 минут (00, 05, 10...)
min_5m = now.minute - (now.minute % 5)
ts_5m = now.replace(minute=min_5m, second=0, microsecond=0).strftime('%Y-%m-%d %H:%M:%S')
@@ -60,16 +78,16 @@ class TimeSeriesAggregator:
updates_count = 0
for client in client_updates:
client_id = client.get('db_id')
# Пропускаем, если ID не определен
if client_id is None:
if client_id is None:
continue
rx = client.get('bytes_received_inc', 0)
tx = client.get('bytes_sent_inc', 0)
# Пропускаем, если нет трафика
if rx == 0 and tx == 0:
if rx == 0 and tx == 0:
continue
# Запись во все уровни агрегации
@@ -78,7 +96,7 @@ class TimeSeriesAggregator:
self._upsert_bucket(cursor, 'stats_hourly', ts_1h, client_id, rx, tx)
self._upsert_bucket(cursor, 'stats_6h', ts_6h, client_id, rx, tx)
self._upsert_bucket(cursor, 'stats_daily', ts_1d, client_id, rx, tx)
updates_count += 1
conn.commit()
@@ -100,24 +118,95 @@ class OpenVPNDataGatherer:
self.last_check_time = None
# Инициализируем дату последней очистки вчерашним днем для корректного старта
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.init_database()
# Инициализация модуля агрегации
# Передаем ссылку на метод подключения к БД
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
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):
"""Загрузка конфигурации или создание дефолтной со сложной структурой"""
config = configparser.ConfigParser()
# Полная структура конфига согласно требованиям
defaults = {
'api': {
@@ -129,6 +218,9 @@ class OpenVPNDataGatherer:
'log_path': '/var/log/openvpn/openvpn-status.log',
'db_path': 'openvpn_monitor.db',
'check_interval': '10', # Интервал 10 секунд
'session_grace_ticks': '3', # Тиков до удаления пропавшей из статуса сессии
'status_stale_seconds': '60', # Файл статуса старше этого = OpenVPN остановлен
'status_invalid_max': '6', # Подряд пропущенных тиков до уровня ERROR в логе
},
'logging': {
'level': 'INFO',
@@ -170,7 +262,7 @@ class OpenVPNDataGatherer:
with open(config_file, 'w') as f:
config.write(f)
print(f"Created default configuration file: {config_file}")
except Exception as e:
print(f"Error loading config: {e}")
# Fallback в памяти
@@ -179,14 +271,14 @@ class OpenVPNDataGatherer:
config.add_section(section)
for key, val in options.items():
config.set(section, key, val)
return config
def setup_logging(self):
try:
log_level = self.config.get('logging', 'level', fallback='INFO')
log_file = self.config.get('logging', 'log_file', fallback='openvpn_gatherer.log')
# Создаем директорию для логов если нужно
log_dir = os.path.dirname(log_file)
if log_dir and not os.path.exists(log_dir):
@@ -217,17 +309,17 @@ class OpenVPNDataGatherer:
return self.config.get(section, key, fallback=default)
except:
return default
# get_db_connection and init_database removed
def cleanup_old_data(self):
"""Очистка данных согласно retention policies в config.ini"""
self.logger.info("Starting data cleanup procedure...")
conn = self.db_manager.get_connection()
cursor = conn.cursor()
# Маппинг: Таблица -> Ключ конфига -> Дефолт (дни)
retention_rules = [
('usage_history', 'raw_retention_days', 7),
@@ -249,88 +341,190 @@ class OpenVPNDataGatherer:
if deleted > 0:
self.logger.info(f"Cleaned {table}: removed {deleted} records older than {days} days")
total_deleted += deleted
conn.commit()
if total_deleted == 0:
self.logger.info("Cleanup finished: nothing to delete")
except Exception as e:
self.logger.error(f"Cleanup Error: {e}")
conn.rollback()
finally:
conn.close()
def parse_log_file(self):
def parse_status(self, path, now=None):
"""
Парсинг лога версии 2 (CSV формат).
Ожидает формат: CLIENT_LIST,Common Name,Real Address,...,Bytes Received,Bytes Sent,...
Разбор файла статуса версии 2 (CSV формат) с проверкой целостности и свежести.
Ожидает: 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')
clients = []
if now is None:
now = self._now()
try:
if not os.path.exists(log_path):
self.logger.warning(f"Log file not found: {log_path}")
return clients
with open(log_path, 'r') as file:
for line in file:
line = line.strip()
# Фильтруем только строки с данными клиентов
if not line.startswith('CLIENT_LIST'):
continue
parts = line.split(',')
# V2 Index Map:
# 1: Common Name
# 2: Real Address
# 5: Bytes Received
# 6: Bytes Sent
if len(parts) >= 8 and parts[1] != 'Common Name':
# SKIPPING 'UNDEF' CLIENTS
if parts[1].strip() == 'UNDEF':
continue
try:
client = {
'common_name': parts[1].strip(),
'real_address': parts[2].strip(),
'bytes_received': int(parts[5].strip()),
'bytes_sent': int(parts[6].strip()),
'status': 'Active'
}
clients.append(client)
except (ValueError, IndexError) as e:
self.logger.warning(f"Error parsing client line: {e}")
self.logger.debug(f"Parsed {len(clients)} active clients")
if not os.path.exists(path):
return StatusReading(False, [], False, f"status file not found: {path}")
with open(path, 'r') as file:
lines = [line.strip() for line in file]
except Exception as e:
self.logger.error(f"Error parsing log file: {e}")
return clients
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
# Фильтруем только строки с данными клиентов
if not line.startswith('CLIENT_LIST'):
continue
parts = line.split(',')
# V2 Index Map:
# 1: Common Name
# 2: Real Address
# 5: Bytes Received
# 6: Bytes Sent
# 8: Connected Since (time_t) - начало сессии, epoch
if len(parts) >= 8 and parts[1] != 'Common Name':
# SKIPPING 'UNDEF' CLIENTS
if parts[1].strip() == 'UNDEF':
continue
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 = {
'common_name': parts[1].strip(),
'real_address': parts[2].strip(),
'session_id': session_id,
'bytes_received': int(parts[5].strip()),
'bytes_sent': int(parts[6].strip()),
'connected_since_ts': since_ts,
'status': 'Active'
}
clients.append(client)
except (ValueError, IndexError) as 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")
return StatusReading(True, clients, False, "")
def parse_log_file(self):
"""Читает файл статуса из [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)
@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):
"""
Обновление статусов и расчет инкрементов трафика.
Использует In-Memory Cache (self.session_cache) для корректной обработки
множественных сессий одного пользователя (Ping-Pong effect fix).
Изменения кэша накапливаются в new_cache и применяются только после успешного commit:
при откате транзакции кэш остаётся прежним, приращения не теряются.
При ошибке БД откатывает транзакцию и пробрасывает исключение (его обработает цикл).
"""
conn = self.db_manager.get_connection()
cursor = conn.cursor()
now_ts = self._now()
last_seen_str = datetime.fromtimestamp(now_ts).strftime(TS_FORMAT)
try:
# 1. Загружаем текущее состояние CNs из БД для обновления статусов
cursor.execute('SELECT id, common_name, status, total_bytes_received, total_bytes_sent FROM clients')
db_clients = {row[1]: {'id': row[0], 'status': row[2]} for row in cursor.fetchall()}
# Структура для агрегации инкрементов по 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, RealAddr) для очистки кэша
active_session_keys = set()
# Новое состояние кэша сессий (применяется после commit) и активные CN
new_cache = {}
active_cns = set()
# 2. Обрабатываем каждую активную сессию
@@ -339,67 +533,40 @@ class OpenVPNDataGatherer:
real_addr = client['real_address']
curr_recv = client['bytes_received']
curr_sent = client['bytes_sent']
# Уникальный ключ сессии
session_key = (name, real_addr)
active_session_keys.add(session_key)
since_ts = client.get('connected_since_ts')
# Уникальный ключ сессии: Client ID не меняется при float (смене адреса);
# без Client ID - адрес. Переподключение (новый connected_since) - новая сессия
session_key = (name, client.get('session_id') or real_addr, since_ts)
active_cns.add(name)
# --- ЛОГИКА РАСЧЕТА ДЕЛЬТЫ (In-Memory) ---
if session_key in self.session_cache:
prev_state = self.session_cache[session_key]
prev_state = self.session_cache.get(session_key)
if prev_state is not None:
prev_recv = prev_state['bytes_received']
prev_sent = prev_state['bytes_sent']
# Расчет RX
if curr_recv < prev_recv:
# Рестарт сессии (счетчик сбросился)
inc_recv = curr_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:
inc_sent = curr_sent
self.logger.info(f"Session reset detected for {session_key} (Sent)")
else:
inc_sent = curr_sent - prev_sent
else:
# Новая сессия (или после рестарта сервиса)
# Если сервиса только запустился, мы не знаем предыдущего состояния.
# Чтобы избежать спайков, считаем инкремент = 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_sent': curr_sent,
'last_seen': datetime.now(),
'connected_since': datetime.now() # Track start time
}
if curr_recv < prev_recv:
self.logger.info(f"Session reset detected for {session_key} (Recv)")
if curr_sent < prev_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:
# 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()
# Сессия не в кэше: новая, продолжающаяся после перезапуска или вернувшаяся
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))
new_cache[session_key] = {
'bytes_received': curr_recv,
'bytes_sent': curr_sent,
'last_seen': last_seen_str,
'connected_since': connected_since,
'missing_ticks': 0
}
# Добавляем в клиентский объект (для истории/графиков)
# Важно: это инкремент конкретной сессии
client['bytes_received_inc'] = inc_recv
@@ -407,29 +574,36 @@ class OpenVPNDataGatherer:
# Ensure db_id is available for active_sessions later (populated in step 4 or from cache)
# We defer writing to active_sessions until we have DB IDs
client['session_key'] = session_key
# --- АГРЕГАЦИЯ ДЛЯ БД (по Common Name) ---
if name not in cn_updates:
cn_updates[name] = {
'inc_recv': 0, 'inc_tx': 0,
'max_rx': 0, 'max_tx': 0, # Для last_bytes в БД сохраним текущие счетчики самой большой сессии (примерно)
'real_address': real_addr # Берем последний адрес
'inc_recv': 0, 'inc_tx': 0,
'max_rx': 0, 'max_tx': 0, # Для last_bytes в БД: сумма текущих счётчиков всех сессий CN
'real_address': real_addr,
'addr_since': since_ts or 0 # Начало сессии, чей адрес сохранён
}
cn_updates[name]['inc_recv'] += inc_recv
cn_updates[name]['inc_tx'] += inc_sent
# Сохраняем "текущее" значение как максимальное из сессий, чтобы в БД last_bytes было хоть что-то осмысленное
# (хотя при in-memory подходе поле last_bytes в БД теряет смысл для логики, но нужно для UI)
cn_updates[name]['max_rx'] = max(cn_updates[name]['max_rx'], curr_recv)
cn_updates[name]['max_tx'] = max(cn_updates[name]['max_tx'], curr_sent)
cn_updates[name]['real_address'] = real_addr
# last_bytes в БД = сумма текущих счётчиков всех сессий CN (нужно для UI)
cn_updates[name]['max_rx'] += curr_recv
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
# 3. Очистка кэша от мертвых сессий
# Создаем список ключей для удаления, чтобы не менять словарь во время итерации
dead_sessions = [k for k in self.session_cache if k not in active_session_keys]
for k in dead_sessions:
del self.session_cache[k]
self.logger.debug(f"Removed inactive session from cache: {k}")
# 3. Льготный период для сессий, которых нет в текущем статусе:
# запись остаётся в кэше, пока missing_ticks < session_grace_ticks
for key, state in self.session_cache.items():
if key in new_cache:
continue
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)
for name, data in cn_updates.items():
@@ -437,9 +611,9 @@ class OpenVPNDataGatherer:
# UPDATE
db_id = db_clients[name]['id']
cursor.execute('''
UPDATE clients
SET status = 'Active',
real_address = ?,
UPDATE clients
SET status = 'Active',
real_address = ?,
total_bytes_received = total_bytes_received + ?,
total_bytes_sent = total_bytes_sent + ?,
last_bytes_received = ?,
@@ -455,22 +629,25 @@ class OpenVPNDataGatherer:
data['max_tx'],
db_id
))
# Прокидываем DB ID обратно в объекты клиентов (для TSDB)
# Так как active_clients - это список сессий, ищем все сессии этого юзера
for client in active_clients:
if client['common_name'] == name:
client['db_id'] = db_id
else:
# INSERT (New Client)
# INSERT (New Client): итоги стартуют с прироста первого кадра, а не с нуля
# (иначе трафик первого тика нового клиента не попадал в total_bytes_*)
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)
VALUES (?, ?, 'Active', 0, 0, ?, ?)
VALUES (?, ?, 'Active', ?, ?, ?, ?)
''', (
name,
data['real_address'],
data['inc_recv'],
data['inc_tx'],
data['max_rx'],
data['max_tx']
))
@@ -484,8 +661,8 @@ class OpenVPNDataGatherer:
for name, db_info in db_clients.items():
if name not in active_cns and db_info['status'] == 'Active':
cursor.execute('''
UPDATE clients
SET status = 'Disconnected', updated_at = CURRENT_TIMESTAMP
UPDATE clients
SET status = 'Disconnected', updated_at = CURRENT_TIMESTAMP
WHERE id = ?
''', (db_info['id'],))
self.logger.info(f"Client disconnected: {name}")
@@ -493,64 +670,89 @@ class OpenVPNDataGatherer:
# 6. SYNC ACTIVE SESSIONS TO DB (Snapshot)
# Clear old state
cursor.execute('DELETE FROM active_sessions')
# Insert current state
# Insert current state (только сессии, присутствующие в статусе)
for client in active_clients:
# client['db_id'] should be populated by now (from step 4)
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:
cursor.execute('''
INSERT INTO active_sessions
(client_id, common_name, real_address, bytes_received, bytes_sent, connected_since, last_seen)
VALUES (?, ?, ?, ?, ?, ?, ?)
INSERT INTO active_sessions
(client_id, common_name, real_address, bytes_received, bytes_sent, connected_since, last_seen, session_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (
client['db_id'],
client['common_name'],
client['real_address'],
client['bytes_received'],
client['bytes_sent'],
sess_data.get('connected_since', datetime.now()),
sess_data.get('last_seen', datetime.now())
sess_data['connected_since'],
sess_data['last_seen'],
client.get('session_id')
))
conn.commit()
except Exception as e:
self.logger.error(f"Error updating client status: {e}")
except Exception:
# Кэш не менялся: приращения не потеряны, следующий тик посчитает разницу за весь интервал
conn.rollback()
raise
finally:
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
@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):
"""Расчет скорости в Mbps"""
if time_diff <= 0:
time_diff = 1.0 # Защита от деления на 0
# Коэффициент: (байты * 8 бит) / (секунды * 1 млн)
factor = 8 / (time_diff * 1_000_000)
for client in clients:
client['bytes_received_rate_mbps'] = client.get('bytes_received_inc', 0) * factor
client['bytes_sent_rate_mbps'] = client.get('bytes_sent_inc', 0) * factor
return clients
def store_usage_history(self, clients):
"""Сохранение высокодетализированной (Raw) истории"""
if not clients:
return
conn = self.db_manager.get_connection()
cursor = conn.cursor()
try:
for client in clients:
if client.get('db_id'):
cursor.execute('''
INSERT INTO usage_history
INSERT INTO usage_history
(client_id, bytes_received, bytes_sent, bytes_received_rate_mbps, bytes_sent_rate_mbps)
VALUES (?, ?, ?, ?, ?)
''', (
@@ -560,62 +762,104 @@ class OpenVPNDataGatherer:
client.get('bytes_received_rate_mbps', 0),
client.get('bytes_sent_rate_mbps', 0)
))
conn.commit()
except Exception as e:
self.logger.error(f"Error storing raw history: {e}")
conn.rollback()
finally:
conn.close()
def run_monitoring_cycle(self):
"""Один цикл мониторинга"""
current_time = datetime.now()
# 1. Получаем активных клиентов
active_clients = self.parse_log_file()
# 2. Обновляем статусы и считаем дельту трафика
clients_with_updates = self.update_client_status_and_bytes(active_clients)
if clients_with_updates:
# 3. Считаем интервал времени
time_diff = 10.0 # Номинал
if self.last_check_time:
time_diff = (current_time - self.last_check_time).total_seconds()
# 4. Считаем скорости
clients_rated = self.calculate_rates(clients_with_updates, time_diff)
# 5. Сохраняем RAW историю (для графиков реального времени)
self.store_usage_history(clients_rated)
# 6. Агрегируем в TSDB (5m, 15m, 1h, 6h, 1d)
self.ts_aggregator.aggregate(clients_rated)
self.last_check_time = current_time
# 1. Читаем файл статуса (с проверкой целостности и свежести)
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. Обновляем статусы и считаем дельту трафика
clients_with_updates = self.update_client_status_and_bytes(reading.clients)
if clients_with_updates:
# 3. Считаем интервал времени
time_diff = 10.0 # Номинал
if self.last_check_time:
time_diff = (current_time - self.last_check_time).total_seconds()
# 4. Сворачиваем сессии в записи по CN и считаем скорости (сумма по сессиям)
clients_rated = self.calculate_rates(
self.merge_sessions_by_cn(clients_with_updates), time_diff)
# 5. Сохраняем RAW историю (для графиков реального времени)
self.store_usage_history(clients_rated)
# 6. Агрегируем в TSDB (5m, 15m, 1h, 6h, 1d)
self.ts_aggregator.aggregate(clients_rated)
self.last_check_time = current_time
# 7. Проверка необходимости очистки (раз в сутки)
if current_time.date() > self.last_cleanup_date:
self.logger.info("New day detected. Initiating cleanup.")
self.cleanup_old_data()
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):
"""Запуск цикла"""
interval = int(self.get_config_value('openvpn_monitor', 'check_interval', 10))
"""Запуск цикла. Цикл переживает любые исключения; остановка по SIGTERM/SIGINT штатная."""
interval = self.interval
self.logger.info(f"Starting OpenVPN Monitoring. Interval: {interval}s")
self.logger.info("Press Ctrl+C to stop")
# Обработчики сигналов ставятся только в главном потоке; прежние восстанавливаем при выходе
previous = {}
try:
while True:
self.run_monitoring_cycle()
time.sleep(interval)
except KeyboardInterrupt:
self.logger.info("Monitoring stopped by user")
except Exception as e:
self.logger.error(f"Critical error in main loop: {e}")
for sig in (signal.SIGTERM, signal.SIGINT):
previous[sig] = signal.signal(sig, self._handle_signal)
except ValueError:
pass
failures = 0
try:
while not self.stop_event.is_set():
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__":
gatherer = OpenVPNDataGatherer()
+6 -7
View File
@@ -1,7 +1,6 @@
Flask>=3.0.0
Flask-Cors>=4.0.0
PyJWT>=2.10.0
pyotp>=2.9.0
qrcode>=7.4.2
bcrypt>=4.2.0
Flask>=3.0.0,<4
Flask-Cors>=4.0.0,<7
PyJWT>=2.10.0,<3
pyotp>=2.9.0,<3
qrcode>=7.4.2,<9
bcrypt>=4.2.0,<6
+42
View File
@@ -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
+45
View File
@@ -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)
+276
View File
@@ -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]
+5 -4
View File
@@ -151,8 +151,9 @@ def test_old_schema_is_migrated_without_data_loss(tmp_path, schema):
# 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")]
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
@@ -204,7 +205,7 @@ def test_fresh_database_gets_full_schema_without_backup(tmp_path):
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,)]
assert query(db, "SELECT version FROM schema_migrations") == [(1,), (2,)]
def test_auto_migrate_off_refuses_while_pending(tmp_path, monkeypatch):
@@ -242,5 +243,5 @@ def test_simultaneous_start_makes_one_backup(tmp_path):
assert errors == []
assert len(glob.glob(db + ".bak-*")) == 1
assert sorted(len(r.applied) for r in reports) == [0, 1]
assert query(db, "SELECT version FROM schema_migrations") == [(1,)]
assert sorted(len(r.applied) for r in reports) == [0, len(migrations.MIGRATIONS)]
assert query(db, "SELECT version FROM schema_migrations") == [(1,), (2,)]
+41
View File
@@ -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'
+29
View File
@@ -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")
+6 -1
View File
@@ -11,7 +11,12 @@ COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# 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 . .
+3
View File
@@ -19,6 +19,9 @@ python3 -m venv venv
source venv/bin/activate
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
python3 main.py
# Swagger UI available at http://localhost:8000/docs
+4 -3
View File
@@ -1,7 +1,8 @@
[api]
# Secret key for JWT token verification.
# MUST match the key in APP_CORE/config.ini if not overridden by ENV.
secret_key = ovpmon-secret-change-me
# Secret key for JWT token verification.
# MUST match the key of APP_CORE (same OVPMON_API_SECRET_KEY or the same value in its config.ini).
# 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]
# Path to the profiler database relative to component root
+6
View File
@@ -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)
+11 -1
View File
@@ -1,5 +1,6 @@
import uvicorn
from fastapi import FastAPI
import logging
import sys
import os
@@ -9,7 +10,7 @@ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from database import db_path
import migrations
from routers import system, server, profiles, server_process
from routers import system, server, profiles, server_process, backup
from utils.logging import setup_logging
from fastapi.middleware.cors import CORSMiddleware
@@ -20,6 +21,14 @@ setup_logging()
# 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(
title="OpenVPN Profiler API",
description="REST API for managing OpenVPN profiles and configuration",
@@ -39,6 +48,7 @@ app.include_router(system.router, prefix="/api", tags=["System"])
app.include_router(server.router, prefix="/api", tags=["Server"])
app.include_router(profiles.router, prefix="/api", tags=["Profiles"])
app.include_router(server_process.router, prefix="/api", tags=["Process Control"])
app.include_router(backup.router, prefix="/api", tags=["Backup"])
@app.get("/")
def read_root():
+3
View File
@@ -37,6 +37,9 @@ def main(argv=None):
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:
+7 -2
View File
@@ -1,8 +1,13 @@
fastapi
uvicorn
fastapi==0.143.3
starlette==1.8.0
uvicorn==0.54.0
pydantic==2.14.1
sqlalchemy
psutil
python-multipart
jinja2
pyjwt
requests
cryptography
minio
paramiko
+218
View File
@@ -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 -3
View File
@@ -4,6 +4,7 @@ from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
from database import get_db
from utils.auth import verify_token
from utils.guards import forbid_during_restore
from models import UserProfile
from schemas import UserProfile as UserProfileSchema, UserProfileCreate, UserProfileNoteUpdate
from services import pki, generator
@@ -69,7 +70,7 @@ def list_profiles(db: Session = Depends(get_db)):
return updated_profiles
@router.post("/profiles", response_model=UserProfileSchema)
@router.post("/profiles", response_model=UserProfileSchema, dependencies=[Depends(forbid_during_restore)])
def create_profile(
profile_in: UserProfileCreate,
db: Session = Depends(get_db)
@@ -123,7 +124,7 @@ def create_profile(
db.refresh(new_profile)
return new_profile
@router.put("/profiles/{profile_id}/note", response_model=UserProfileSchema)
@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:
@@ -134,7 +135,7 @@ def update_profile_note(profile_id: int, body: UserProfileNoteUpdate, db: Sessio
db.refresh(profile)
return profile
@router.delete("/profiles/{profile_id}")
@router.delete("/profiles/{profile_id}", dependencies=[Depends(forbid_during_restore)])
def revoke_profile(profile_id: int, db: Session = Depends(get_db)):
profile = db.query(UserProfile).filter(UserProfile.id == profile_id).first()
if not profile:
+2 -1
View File
@@ -4,13 +4,14 @@ from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from utils.auth import verify_token
from utils.guards import forbid_during_restore
from services import generator, process, config, pki
logger = logging.getLogger(__name__)
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)):
try:
pki.require_server_ready(db)
+2 -1
View File
@@ -4,6 +4,7 @@ from services import process, pki
from database import get_db
from sqlalchemy.orm import Session
from utils.auth import verify_token
from utils.guards import forbid_during_restore
from typing import Optional
from fastapi import Depends
@@ -22,7 +23,7 @@ class ProcessStats(BaseModel):
memory_mb: float
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, db: Session = Depends(get_db)):
"""
Control the OpenVPN server process.
+7 -4
View File
@@ -1,7 +1,10 @@
from typing import Literal, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from database import get_db
from utils.auth import verify_token
from utils.guards import forbid_during_restore
from schemas import (
ConfigResponse, SystemSettings, PKISetting,
SystemSettingsUpdate, PKISettingUpdate
@@ -12,7 +15,7 @@ router = APIRouter(dependencies=[Depends(verify_token)])
@router.get("/config", response_model=ConfigResponse)
def get_config(
section: str = Query(None, enum=["server", "pki"]),
section: Optional[Literal["server", "pki"]] = Query(None),
db: Session = Depends(get_db)
):
response = ConfigResponse()
@@ -22,14 +25,14 @@ def get_config(
response.pki = config.get_pki_settings(db)
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(
settings: SystemSettingsUpdate,
db: Session = Depends(get_db)
):
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(
settings: PKISettingUpdate,
db: Session = Depends(get_db)
@@ -48,7 +51,7 @@ def init_system_pki(db: Session = Depends(get_db)):
def get_init_status(db: Session = Depends(get_db)):
return pki.init_status(db)
@router.delete("/system/pki")
@router.delete("/system/pki", dependencies=[Depends(forbid_during_restore)])
def clear_system_pki(db: Session = Depends(get_db)):
if pki.is_init_running():
raise HTTPException(status_code=409, detail="PKI initialization is running")
+21
View File
@@ -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)."""
+98
View File
@@ -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)
+657
View File
@@ -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)
+335
View File
@@ -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
+252
View File
@@ -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]
+15
View File
@@ -144,6 +144,19 @@ 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)."""
@@ -243,6 +256,8 @@ 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:
+3 -9
View File
@@ -1,25 +1,19 @@
client
dev tun
windows-driver wintun
proto {{ protocol }}
remote {{ remote_ip }} {{ port }}
resolv-retry infinite
nobind
{% if protocol == 'udp' %}
explicit-exit-notify
{% endif %}
{% if tun_mtu %}
tun-mtu {{ tun_mtu }}
{% endif %}
user nobody
group nobody
persist-key
persist-tun
{% if protocol == 'tcp' %}
tls-client
{% else %}
#tls-client
{% endif %}
mute-replay-warnings
remote-cert-tls server
+1 -5
View File
@@ -1,9 +1,6 @@
dev tun
proto {{ protocol }}
{% if protocol == 'tcp' %}
tls-server
{% else %}
# explicit-exit-notify 1
{% if protocol != 'tcp' %}
explicit-exit-notify 1
{% endif %}
port {{ port }}
@@ -28,7 +25,6 @@ server {{ vpn_network }} {{ vpn_netmask }}
ifconfig-pool-persist /etc/openvpn/ipp.txt
log /var/log/openvpn/openvpn.log
log-append /var/log/openvpn/openvpn.log
verb 3
+404
View File
@@ -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"
+17
View File
@@ -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")
+21
View File
@@ -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
+45
View File
@@ -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
+14 -20
View File
@@ -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 main import app
import sys
import os
# Add project root to sys.path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from utils.auth import verify_token
app.dependency_overrides[verify_token] = lambda: {"sub": "test"}
client = TestClient(app)
def test_get_stats():
response = client.get("/server/process/stats")
print(f"Stats response status: {response.status_code}")
print(f"Stats response body: {response.json()}")
response = client.get("/api/server/process/stats")
assert response.status_code == 200
data = response.json()
assert "pid" in data
assert "cpu_percent" 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__":
print("Running API tests...")
try:
test_get_stats()
test_control_invalid()
print("Tests passed!")
except Exception as e:
print(f"Tests failed: {e}")
def test_control_invalid():
response = client.post("/api/server/process/invalid_action")
assert response.status_code == 400
+18 -16
View File
@@ -1,29 +1,31 @@
import jwt
import configparser
import logging
import os
from fastapi import Header, HTTPException, status
from pathlib import Path
from .config import get_config_value
from .secret_key import resolve_secret_key, SecretKeyError
logger = logging.getLogger(__name__)
def get_secret_key():
# Use consistent OVPMON_API_SECRET_KEY as primary source
key = get_config_value('api', 'secret_key', fallback='ovpmon-secret-change-me')
if key == 'ovpmon-secret-change-me':
print("[AUTH] WARNING: Using default fallback SECRET_KEY")
else:
# Check if it was from env (get_config_value prioritizes env)
import os
if os.getenv('OVPMON_API_SECRET_KEY'):
print("[AUTH] Using SECRET_KEY from OVPMON_API_SECRET_KEY environment variable")
elif os.getenv('OVPMON_SECRET_KEY'):
print("[AUTH] Using SECRET_KEY from OVPMON_SECRET_KEY environment variable")
else:
print("[AUTH] SECRET_KEY loaded (config.ini or fallback)")
"""JWT signing key: OVPMON_API_SECRET_KEY, else [api] secret_key of config.ini. No built-in default."""
try:
# get_config_value returns the environment value first, then the config.ini value
key, source = resolve_secret_key(
os.getenv('OVPMON_API_SECRET_KEY'),
get_config_value('api', 'secret_key'),
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 {source}")
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()
+10
View File
@@ -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)
+42
View File
@@ -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
+6
View File
@@ -0,0 +1,6 @@
node_modules
dist
.vscode
.git
*.bak
*.log
+12 -4
View File
@@ -2,14 +2,22 @@
FROM node:20-alpine AS build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
RUN npm ci
COPY . .
RUN npm run build
# 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 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;"]
+21 -9
View File
@@ -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.
## Project Structure
- `src/views/`: Page components (Dashboard, Login, Profiles, etc.).
- `src/components/`: Reusable widgets (Charts, Sidebar).
- `src/stores/`: Pinia state management (Auth, Client Data).
- `src/views/`: Pages (Analytics, Clients, Certificates, PKI and VPN configuration, Server Process, Backup and Restore, Account, Login).
- `src/components/`: Reusable widgets (`BaseModal`, `ConfirmModal`, `StatusBadge`, toasts, dialogs).
- `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
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
```bash
npm install
npm run dev
# Access at http://localhost:5173
npm ci # exact versions from package-lock.json (npm install after changing package.json)
npm run dev # 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
See `DOCS/UI/Architecture.md` for detailed architecture notes.
+51
View File
@@ -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
+40 -3
View File
@@ -1,21 +1,58 @@
server {
listen 80;
listen ${OVP_UI_PORT};
server_name localhost;
server_tokens off;
root /usr/share/nginx/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 / {
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)
location /api/ {
proxy_pass http://${OVP_API_HOST}:${OVP_API_PORT};
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass_header Authorization;
}
# Модуль 2: Управление профилями (FastAPI, порт 8000)
@@ -34,4 +71,4 @@ server {
location = /50x.html {
root /usr/share/nginx/html;
}
}
}
+26
View File
@@ -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
View File
@@ -3,7 +3,7 @@
<head>
<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" />
<title>OpenVPN Controller</title>
</head>
+1594 -16
View File
File diff suppressed because it is too large. Load diff
+9 -4
View File
@@ -6,7 +6,9 @@
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
"preview": "vite preview",
"test": "vitest run",
"lint": "eslint src"
},
"dependencies": {
"@fortawesome/fontawesome-free": "^7.1.0",
@@ -14,13 +16,16 @@
"bootstrap": "^5.3.8",
"chart.js": "^4.5.1",
"qrcode.vue": "^3.6.0",
"sass": "^1.97.2",
"sweetalert2": "^11.26.17",
"vue": "^3.5.24",
"vue-router": "^4.6.4"
},
"devDependencies": {
"@eslint/js": "^10.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
View File
@@ -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

+15 -23
View File
@@ -13,7 +13,7 @@
<aside v-if="isAuthenticated" class="sidebar" :class="{ 'compact': isCompact }">
<div class="sidebar-header">
<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">
<i class="fas fa-times"></i>
@@ -24,7 +24,6 @@
<!-- SECTION: MONITORING -->
<div class="nav-section-header">MONITORING</div>
<p></p>
<router-link to="/" class="nav-link" active-class="active" title="Analytics">
<i class="fas fa-chart-line"></i> <span>Analytics</span>
</router-link>
@@ -34,7 +33,6 @@
<!-- SECTION: CONFIGURATION -->
<div class="nav-section-header mt-3">CONFIGURATION</div>
<p></p>
<router-link to="/config/pki" class="nav-link" active-class="active" title="PKI">
<i class="fas fa-fingerprint"></i> <span>PKI</span>
</router-link>
@@ -48,17 +46,18 @@
<!-- SECTION: MANAGEMENT -->
<div class="nav-section-header mt-3">MANAGEMENT</div>
<p></p>
<router-link to="/certificates" class="nav-link" active-class="active" title="Certificates">
<i class="fas fa-certificate"></i> <span>Certificates</span>
</router-link>
<router-link to="/server" class="nav-link" active-class="active" title="Server Process">
<i class="fas fa-terminal"></i> <span>Server Process</span>
</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 -->
<div class="nav-section-header mt-3">ACCOUNT</div>
<p></p>
<router-link to="/account" class="nav-link" active-class="active" title="Account Settings">
<i class="fas fa-user-cog"></i> <span>Account Settings</span>
</router-link>
@@ -93,10 +92,10 @@
<i class="fas fa-globe me-1 text-muted"></i>{{ timezoneAbbr }}
</span>
<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 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>
<div class="header-divider d-none d-md-block"></div>
@@ -135,11 +134,12 @@ 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 { apiClient } = useApi();
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 isSidebarOpen = ref(false);
const isCompact = ref(false);
@@ -148,7 +148,11 @@ 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') || '');
// Keep the header name in sync with the server (login, rename, stale session)
@@ -180,13 +184,6 @@ const handleLogout = () => {
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 = () => {
isCompact.value = !isCompact.value;
localStorage.setItem('sidebarCompact', isCompact.value);
@@ -199,7 +196,7 @@ const refreshPage = () => {
// Close sidebar on route change
watch(() => route.path, () => {
isSidebarOpen.value = false;
if (route.name !== 'Login') {
if (isAuthenticated.value) {
syncUsername();
refreshPkiStatus();
}
@@ -208,15 +205,10 @@ watch(() => route.path, () => {
onMounted(async () => {
await loadConfig();
window.addEventListener('ovpmon-user-changed', onUserChanged);
if (route.name !== 'Login') {
if (isAuthenticated.value) {
syncUsername();
refreshPkiStatus();
}
// Init Theme
const savedTheme = localStorage.getItem('theme') || 'light';
isDark.value = savedTheme === 'dark';
document.documentElement.setAttribute('data-theme', savedTheme);
// Init Sidebar
const savedCompact = localStorage.getItem('sidebarCompact');
+42 -1
View File
@@ -272,6 +272,11 @@ body {
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 */
.sidebar.compact {
width: 64px;
@@ -1999,4 +2004,40 @@ input[type="number"].config-input {
.stats-grid .stat-item.full-width {
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);
}
+3 -4
View File
@@ -22,7 +22,7 @@
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { Modal } from 'bootstrap';
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);
let bsModal = null;
const sizeClass = props.size || '';
const sizeClass = computed(() => props.size || '');
const show = () => {
bsModal?.show();
@@ -63,7 +63,6 @@ onMounted(() => {
modalRef.value.addEventListener('hidden.bs.modal', () => {
emit('closed');
emit('close');
});
});
+5 -3
View File
@@ -1,7 +1,7 @@
<template>
<BaseModal id="confirmModal" :title="title" ref="modal">
<BaseModal :id="modalId" :title="title" ref="modal">
<template #body>
<p class="text-main">{{ message }}</p>
<p class="text-main" style="white-space: pre-line;">{{ message }}</p>
</template>
<template #footer>
<button v-if="showCancel" type="button" class="btn-action btn-action-secondary" @click="close">Cancel</button>
@@ -13,9 +13,11 @@
</template>
<script setup>
import { ref } from 'vue';
import { ref, useId } from '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 modal = ref(null);
+27 -137
View File
@@ -54,15 +54,12 @@
</template>
<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
import Chart from 'chart.js/auto';
import { ref, onMounted, onUnmounted } from 'vue';
import { useApi } from '../composables/useApi';
import { useFormatters } from '../composables/useFormatters';
import { useTrafficChart } from '../composables/useTrafficChart';
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 { parseServerDate } = useFormatters();
const modalRef = ref(null);
const chartCanvas = ref(null);
@@ -71,10 +68,10 @@ const range = ref('24h');
const isSpeedMode = ref(false);
const loading = ref(false);
let bsModal = null;
let chartInstance = 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) => {
clientName.value = name;
@@ -90,159 +87,52 @@ const close = () => {
const loadHistory = async () => {
if (!clientName.value) return;
const id = ++requestId;
loading.value = true;
try {
const res = await fetchClientHistory(clientName.value, range.value);
if (id !== requestId) return;
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();
} else {
cachedData = [];
if (chartInstance) chartInstance.destroy();
chart.destroy();
}
} catch (e) {
console.error(e);
if (id === requestId) console.error(e);
} finally {
loading.value = false;
if (id === requestId) loading.value = false;
}
};
const renderChart = () => {
if (!chartCanvas.value || !cachedData) return;
if (chartInstance) chartInstance.destroy();
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 }
}
}
}
});
if (!cachedData) return;
chart.render(cachedData, { range: range.value, speedMode: isSpeedMode.value });
};
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(() => {
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', () => {
if (chartInstance) {
chartInstance.destroy();
chartInstance = null;
}
requestId++;
loading.value = false;
cachedData = null;
chart.destroy();
});
});
onUnmounted(() => {
if (chartInstance) chartInstance.destroy();
requestId++;
bsModal?.dispose();
});
defineExpose({ open, close });
+14 -7
View File
@@ -1,11 +1,15 @@
<template>
<BaseModal id="newClientModal" title="Create New Client" ref="modal">
<BaseModal id="newClientModal" title="Create New Client" ref="modal" @opened="inputRef?.focus()">
<template #body>
<div class="mb-3">
<label for="clientName" class="form-label small text-muted text-uppercase fw-bold">Client Name</label>
<div class="input-group">
<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 class="form-text mt-2 text-muted small">
<i class="fas fa-info-circle me-1"></i> Use only alphanumeric characters, dashes, or underscores.
@@ -14,7 +18,7 @@
</template>
<template #footer>
<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
</button>
</template>
@@ -22,7 +26,7 @@
</template>
<script setup>
import { ref } from 'vue';
import { ref, computed } from 'vue';
import BaseModal from './BaseModal.vue';
const emit = defineEmits(['create']);
@@ -30,10 +34,13 @@ const modal = ref(null);
const clientName = ref('');
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 = () => {
clientName.value = '';
modal.value.show();
setTimeout(() => inputRef.value?.focus(), 500);
modal.value.show(); // the input is focused on the opened event
};
const close = () => {
@@ -41,7 +48,7 @@ const close = () => {
};
const confirm = () => {
if (clientName.value) {
if (isValid.value) {
emit('create', clientName.value);
close();
}
@@ -3,7 +3,7 @@
<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>
<span v-if="profile" class="status-badge" :class="status.cls">{{ status.label }}</span>
<StatusBadge v-if="profile" :profile="profile" />
</div>
</template>
<template #body>
@@ -36,6 +36,7 @@
<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);
@@ -44,14 +45,6 @@ const note = ref('');
const dirty = computed(() => note.value !== (profile.value?.note || ''));
const status = computed(() => {
const p = profile.value;
if (p?.is_revoked) return { label: 'Revoked', cls: 'status-expired' };
if (p?.is_expired) return { label: 'Expired', cls: 'status-expired' };
if (p?.days_remaining != null && p.days_remaining <= 30) return { label: 'Expiring Soon', cls: 'status-warning' };
return { label: 'Active', cls: 'status-valid' };
});
const daysLabel = computed(() => {
const days = profile.value?.days_remaining;
if (days == null) return '';
+27
View File
@@ -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>
+31 -18
View File
@@ -4,13 +4,35 @@ import { useAppConfig } from './useAppConfig';
// Singleton instances
const apiClient = 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
const getBaseUrl = (config) => config?.api_base_url || 'http://localhost:5001/api/v1';
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
const setupInterceptors = (instance, getBase) => {
// 401 on a regular API request: the session is gone, clear it and go to the login page
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) => {
const { config } = useAppConfig();
reqConfig.baseURL = getBase(config.value);
@@ -22,24 +44,14 @@ const setupInterceptors = (instance, getBase) => {
return reqConfig;
});
instance.interceptors.response.use(
response => response,
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);
}
);
if (endSessionOn401) {
instance.interceptors.response.use(response => response, handleUnauthorized);
}
};
setupInterceptors(apiClient, getBaseUrl);
setupInterceptors(profilesApiClient, getProfilesBaseUrl);
setupInterceptors(authApiClient, getAuthBaseUrl, { endSessionOn401: false });
export function useApi() {
const fetchStats = async () => {
@@ -59,13 +71,14 @@ export function useApi() {
const fetchCertificates = async () => {
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 {
apiClient,
profilesApiClient,
authApiClient,
fetchStats,
fetchClientHistory,
fetchAnalytics,
+57
View File
@@ -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');
});
});
+6 -4
View File
@@ -1,15 +1,17 @@
export function useFormatters() {
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 dm = decimals < 0 ? 0 : decimals;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
const i = Math.min(Math.max(Math.floor(Math.log(value) / Math.log(k)), 0), sizes.length - 1);
return parseFloat((value / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
function formatRate(rate) {
return parseFloat(rate).toFixed(3) + ' Mbps';
return (parseFloat(rate) || 0).toFixed(3) + ' Mbps';
}
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');
});
});
+43
View File
@@ -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());
}
+142
View File
@@ -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 };
}
+3 -16
View File
@@ -8,23 +8,10 @@ import 'bootstrap/dist/js/bootstrap.bundle.min.js';
import '@fortawesome/fontawesome-free/css/all.min.css';
import './assets/main.css';
import axios from 'axios';
import { initTheme } from './composables/useTheme';
// Global Axios Defaults (No Base URL - handled by useApi.js)
// We keep global error handling for 401s as a fallback
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);
}
);
// Theme is applied before mounting: no flash of the wrong theme
initTheme();
const app = createApp(App);
+11 -2
View File
@@ -1,5 +1,4 @@
import { createRouter, createWebHistory } from 'vue-router';
import Clients from '../views/Clients.vue';
import Login from '../views/Login.vue';
import { usePkiStatus } from '../composables/usePkiStatus';
import { useToast } from '../composables/useToast';
@@ -13,7 +12,7 @@ const routes = [
{
path: '/clients',
name: 'Clients',
component: Clients
component: () => import('../views/Clients.vue')
},
{
path: '/certificates',
@@ -37,6 +36,11 @@ const routes = [
name: 'ServerManagement',
component: () => import('../views/ServerManagement.vue')
},
{
path: '/backup',
name: 'BackupRestore',
component: () => import('../views/BackupRestore.vue')
},
{
path: '/account',
name: 'Account',
@@ -47,6 +51,11 @@ const routes = [
name: 'Login',
component: Login,
meta: { public: true }
},
// Unknown address: back to the start page (the guard sends guests to the login page)
{
path: '/:pathMatch(.*)*',
redirect: '/'
}
];
+34
View File
@@ -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;
}
+36
View File
@@ -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();
}
});
});
+12
View File
@@ -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 || []) : [];
+21
View File
@@ -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([]);
});
});
+29 -91
View File
@@ -50,7 +50,7 @@
<h4 class="m-0 text-heading">Secure Your Account</h4>
</div>
<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>
<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>
@@ -87,6 +87,9 @@
v-model="otp"
placeholder="000000"
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">
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
@@ -117,10 +120,7 @@
</div>
</div>
<!-- Alerts/Notifications Modal -->
<ConfirmModal ref="confirmModal" />
<!-- Action Confirmations Modal -->
<!-- Confirmation before 2FA is disabled; results are shown as toasts -->
<ConfirmModal ref="disable2FAModal" @confirm="handleDisable2FA" />
<!-- Password Change Modal -->
@@ -134,6 +134,7 @@
class="form-control"
v-model="passwordForm.current_password"
placeholder="Enter current password"
autocomplete="current-password"
required
>
</div>
@@ -144,6 +145,7 @@
class="form-control"
v-model="passwordForm.new_password"
placeholder="Min. 8 characters"
autocomplete="new-password"
required
>
</div>
@@ -154,6 +156,7 @@
class="form-control"
v-model="passwordForm.confirm_password"
placeholder="Confirm new password"
autocomplete="new-password"
required
>
</div>
@@ -191,6 +194,7 @@
class="form-control"
v-model="usernameForm.current_password"
placeholder="Enter current password"
autocomplete="current-password"
required
>
</div>
@@ -223,16 +227,16 @@
import { ref, onMounted, reactive } from 'vue';
import { useApi } from '../composables/useApi';
import QrcodeVue from 'qrcode.vue';
import Swal from 'sweetalert2';
import BaseModal from '../components/BaseModal.vue';
import ConfirmModal from '../components/ConfirmModal.vue';
import { useToast } from '../composables/useToast';
const { apiClient } = useApi();
const { apiClient, authApiClient } = useApi();
const toast = useToast();
// UI Refs
const pwModal = ref(null);
const userModal = ref(null);
const confirmModal = ref(null);
const disable2FAModal = ref(null);
// Password Logic
@@ -252,36 +256,21 @@ const showPwModal = () => {
const handleChangePassword = async () => {
if (passwordForm.new_password !== passwordForm.confirm_password) {
Swal.fire({
title: 'Error!',
text: 'New passwords do not match',
icon: 'error',
confirmButtonColor: '#EC7C31'
});
toast.show('New passwords do not match', 'error');
return;
}
pwLoading.value = true;
try {
await apiClient.post('../auth/change-password', {
await authApiClient.post('/change-password', {
current_password: passwordForm.current_password,
new_password: passwordForm.new_password
});
pwModal.value.hide();
Swal.fire({
title: 'Success!',
text: 'Password updated successfully.',
icon: 'success',
confirmButtonColor: '#1652B8'
});
toast.show('Password updated successfully.', 'success');
} catch (err) {
Swal.fire({
title: 'Failed',
text: err.response?.data?.error || 'Failed to update password',
icon: 'error',
confirmButtonColor: '#cf222e'
});
toast.show(err.response?.data?.error || 'Failed to update password', 'error');
} finally {
pwLoading.value = false;
}
@@ -300,18 +289,13 @@ const showUserModal = () => {
const handleChangeUsername = async () => {
if (!/^[A-Za-z][A-Za-z0-9_.-]{2,31}$/.test(usernameForm.new_username)) {
Swal.fire({
title: 'Error!',
text: 'Username must be 3-32 chars, start with a letter, and contain only letters, digits, . _ -',
icon: 'error',
confirmButtonColor: '#EC7C31'
});
toast.show('Username must be 3-32 chars, start with a letter, and contain only letters, digits, . _ -', 'error');
return;
}
userLoading.value = true;
try {
const res = await apiClient.post('../auth/change-username', {
const res = await authApiClient.post('/change-username', {
new_username: usernameForm.new_username,
current_password: usernameForm.current_password,
otp: usernameForm.otp || undefined
@@ -320,19 +304,9 @@ const handleChangeUsername = async () => {
try { localStorage.setItem('ovpmon_user', res.data.username); } catch (e) { /* ignore */ }
window.dispatchEvent(new Event('ovpmon-user-changed'));
userModal.value.hide();
Swal.fire({
title: 'Success!',
text: 'Username updated. Use the new username the next time you sign in.',
icon: 'success',
confirmButtonColor: '#1652B8'
});
toast.show('Username updated. Use the new username the next time you sign in.', 'success');
} catch (err) {
Swal.fire({
title: 'Failed',
text: err.response?.data?.error || 'Failed to update username',
icon: 'error',
confirmButtonColor: '#cf222e'
});
toast.show(err.response?.data?.error || 'Failed to update username', 'error');
} finally {
userLoading.value = false;
}
@@ -344,7 +318,6 @@ const step2 = ref(false);
const loading = ref(false);
const otp = ref('');
const setupData = ref({ secret: '', uri: '' });
const isDark = ref(document.documentElement.getAttribute('data-theme') === 'dark');
const fetchUserStatus = async () => {
loading.value = true;
@@ -358,27 +331,16 @@ const fetchUserStatus = async () => {
}
};
onMounted(() => {
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 });
});
onMounted(fetchUserStatus);
const initSetup = async () => {
loading.value = true;
try {
const res = await apiClient.post('../auth/setup-2fa');
const res = await authApiClient.post('/setup-2fa');
setupData.value = res.data;
step2.value = true;
} catch (err) {
Swal.fire('Error', 'Failed to initialize 2FA setup.', 'error');
toast.show(err.response?.data?.error || 'Failed to initialize 2FA setup.', 'error');
} finally {
loading.value = false;
}
@@ -388,26 +350,14 @@ const verifyAndEnable = async () => {
if (!otp.value || otp.value.length !== 6) return;
loading.value = true;
try {
await apiClient.post('../auth/enable-2fa', {
await authApiClient.post('/enable-2fa', {
secret: setupData.value.secret,
otp: otp.value
});
isEnabled.value = true;
confirmModal.value.open({
title: 'Success!',
message: 'Two-factor authentication has been enabled successfully. Your dashboard is now more secure.',
confirmText: 'Great!',
confirmBtnClass: 'btn-action-save',
showCancel: false
});
toast.show('Two-factor authentication has been enabled. Your dashboard is now more secure.', 'success');
} catch (err) {
confirmModal.value.open({
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
});
toast.show(err.response?.data?.error || 'The code you entered is invalid. Please check your authenticator app and try again.', 'error');
} finally {
loading.value = false;
}
@@ -424,25 +374,13 @@ const disableConfirm = () => {
const handleDisable2FA = async () => {
try {
await apiClient.post('../auth/disable-2fa');
await authApiClient.post('/disable-2fa');
isEnabled.value = false;
step2.value = false;
confirmModal.value.open({
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
});
toast.show('Two-factor authentication has been disabled. Your account is now using standard password protection.', 'warning');
} catch (err) {
confirmModal.value.open({
title: 'Error',
message: err.response?.data?.error || 'Failed to disable two-factor authentication. Please try again.',
confirmText: 'OK',
confirmBtnClass: 'btn-action-danger',
showCancel: false
});
toast.show(err.response?.data?.error || 'Failed to disable two-factor authentication. Please try again.', 'error');
}
};
</script>
+34 -151
View File
@@ -151,16 +151,18 @@ import Chart from 'chart.js/auto';
import { useApi } from '../composables/useApi';
import { useFormatters } from '../composables/useFormatters';
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 { formatBytes, parseServerDate } = useFormatters();
const { formatBytes } = useFormatters();
const { config } = useAppConfig();
// Refs
const mainChartRef = ref(null);
const pieChartRef = ref(null);
let mainChartInstance = null;
let pieChartInstance = null;
const mainChart = useTrafficChart(mainChartRef, { maxPoints: 96 });
// State
const loading = reactive({ analytics: true, certs: true });
@@ -179,17 +181,14 @@ const kpi = reactive({
const topClients = ref([]);
const expiringCertsList = ref([]);
let cachedHistory = null;
// Helpers
const MAX_CHART_POINTS = 96;
let cachedHistory = [];
const loadAnalytics = async () => {
loading.analytics = true;
try {
const res = await fetchAnalytics(range.value);
if (res.success) {
proccessData(res.data);
processData(res.data);
}
} catch (e) {
console.error(e);
@@ -201,17 +200,16 @@ const loadAnalytics = async () => {
const loadCerts = async () => {
loading.certs = true;
try {
const res = await fetchCertificates();
if(res.success && Array.isArray(res.data)) {
const list = res.data.filter(cert => {
// Only active, non-revoked, and expiring soon (within 45 days)
return !cert.is_revoked && !cert.is_expired &&
cert.days_remaining !== null && cert.days_remaining <= 45;
});
kpi.expiringCerts = list.length;
expiringCertsList.value = list.sort((a,b) => (a.days_remaining || 0) - (b.days_remaining || 0));
}
// fetchCertificates returns the plain array of profiles
const profiles = await fetchCertificates();
const list = profiles.filter(cert => {
// Only active, non-revoked, and expiring soon (within 45 days)
return !cert.is_revoked && !cert.is_expired &&
cert.days_remaining != null && cert.days_remaining <= 45;
});
kpi.expiringCerts = list.length;
expiringCertsList.value = list.sort((a, b) => a.days_remaining - b.days_remaining);
} catch (e) {
console.error(e);
} finally {
@@ -219,7 +217,7 @@ const loadCerts = async () => {
}
};
const proccessData = (data) => {
const processData = (data) => {
kpi.concurrentUsers = data.max_concurrent_24h || 0;
// Traffic Distribution
@@ -238,87 +236,21 @@ const proccessData = (data) => {
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();
renderPieChart();
};
const renderMainChart = () => {
if (!mainChartRef.value) return;
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 } }
}
}
});
mainChart.render(cachedHistory, { range: range.value, speedMode: isSpeedMode.value });
};
const renderPieChart = () => {
@@ -326,8 +258,7 @@ const renderPieChart = () => {
if (pieChartInstance) pieChartInstance.destroy();
const ctx = pieChartRef.value.getContext('2d');
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
const bgColor = isDark ? '#161b22' : '#ffffff';
const bgColor = getThemeColors().isDark ? '#161b22' : '#ffffff';
pieChartInstance = new Chart(ctx, {
type: 'doughnut',
@@ -335,7 +266,7 @@ const renderPieChart = () => {
labels: ['Received', 'Sent'],
datasets: [{
data: [kpi.totalReceived, kpi.totalSent],
backgroundColor: ['#1652B8', '#EC7C31'],
backgroundColor: [COLOR_RX, COLOR_TX],
borderColor: bgColor,
borderWidth: 2,
hoverOffset: 4
@@ -350,65 +281,18 @@ 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
let intervalId;
// Redraw the charts when the theme is toggled
useThemeObserver(() => {
renderMainChart();
renderPieChart();
});
onMounted(() => {
loadAnalytics();
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;
intervalId = setInterval(() => {
@@ -419,7 +303,6 @@ onMounted(() => {
onUnmounted(() => {
if (intervalId) clearInterval(intervalId);
if (mainChartInstance) mainChartInstance.destroy();
if (pieChartInstance) pieChartInstance.destroy();
});
</script>
+803
View File
@@ -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>
+9 -23
View File
@@ -89,7 +89,7 @@
<tr v-if="activeCerts.length > 0" class="section-divider">
<td colspan="6">Active Certificates ({{ activeCerts.length }})</td>
</tr>
<tr v-for="cert in activeCerts" :key="cert.id + '_active'" style="cursor: pointer;" @click="showDetails(cert)">
<tr v-for="cert in activeCerts" :key="cert.id + '_active'" style="cursor: pointer;" tabindex="0" @click="showDetails(cert)" @keydown.enter.self="showDetails(cert)">
<td v-note-tooltip="cert.note">
<div class="fw-semibold" style="color: var(--text-heading);">
{{ cert.username }}
@@ -102,7 +102,7 @@
<td class="fw-semibold" :class="getDaysClass(cert.days_remaining)">
{{ cert.days_remaining }}
</td>
<td v-html="getStatusBadgeHTML(cert)"></td>
<td><StatusBadge :profile="cert" /></td>
<td>
<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>
@@ -118,7 +118,7 @@
<tr class="section-divider">
<td colspan="6">Expired / Revoked ({{ expiredCerts.length }})</td>
</tr>
<tr v-for="cert in expiredCerts" :key="cert.id + '_expired'" style="cursor: pointer;" @click="showDetails(cert)">
<tr v-for="cert in expiredCerts" :key="cert.id + '_expired'" style="cursor: pointer;" tabindex="0" @click="showDetails(cert)" @keydown.enter.self="showDetails(cert)">
<td v-note-tooltip="cert.note">
<div class="fw-semibold" style="color: var(--text-heading);">
{{ cert.username }}
@@ -131,7 +131,7 @@
<td class="fw-semibold text-muted">
{{ cert.days_remaining }}
</td>
<td v-html="getStatusBadgeHTML(cert)"></td>
<td><StatusBadge :profile="cert" /></td>
<td>
<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>
@@ -156,6 +156,7 @@ import { useApi } from '../composables/useApi';
import NewClientModal from '../components/NewClientModal.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';
@@ -190,23 +191,6 @@ const getDaysClass = (days) => {
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
const filteredData = computed(() => {
let data = allProfiles.value;
@@ -234,8 +218,8 @@ const categorized = computed(() => {
});
// Sort logic
active.sort((a,b) => (a.days_remaining || 9999) - (b.days_remaining || 9999));
expired.sort((a,b) => (b.days_remaining || -9999) - (a.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));
return { active, expired };
});
@@ -312,6 +296,8 @@ const downloadConfig = async (cert) => {
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// Release the blob after the browser has started the download
setTimeout(() => window.URL.revokeObjectURL(url), 1000);
} catch(e) {
showToast('Could not download config: ' + (e.response?.data?.detail || e.message), 'error');
}
+31 -7
View File
@@ -12,6 +12,10 @@
<div class="stat-value">{{ stats.activeClients }}</div>
<div class="stat-label">Active Clients</div>
</div>
<div class="stat-item">
<div class="stat-value">{{ stats.totalSessions }}</div>
<div class="stat-label">Active Sessions</div>
</div>
</div>
<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>Real Address</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>
</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>
</th>
<th>Down Speed</th>
@@ -78,17 +82,24 @@
{{ group.status }} Clients
</td>
</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>
<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>
</a>
</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>
<span class="status-badge" :class="c.status === 'Active' ? 'status-active' : 'status-disconnected'">
{{ c.status }}
</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 class="font-monospace small">{{ formatBytes(c.total_bytes_received) }}</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>
</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>
</tbody>
@@ -125,8 +145,9 @@ import { useApi } from '../composables/useApi';
import { useFormatters } from '../composables/useFormatters';
import HistoryModal from '../components/HistoryModal.vue';
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 { config } = useAppConfig();
@@ -137,6 +158,7 @@ const searchQuery = ref('');
const hideDisconnected = ref(false);
const currentSort = ref('sent');
const historyModal = ref(null);
const expanded = ref([]); // CNs with an open session list; survives auto-refresh
let intervalId = null;
@@ -144,14 +166,16 @@ const stats = computed(() => {
let totalReceived = 0;
let totalSent = 0;
let activeClients = 0;
let totalSessions = 0;
clients.value.forEach(c => {
totalReceived += c.total_bytes_received || 0;
totalSent += c.total_bytes_sent || 0;
if (c.status === 'Active') activeClients++;
totalSessions += c.sessions_count || 0;
});
return { totalReceived, totalSent, activeClients };
return { totalReceived, totalSent, activeClients, totalSessions };
});
const filteredClients = computed(() => {
+14 -9
View File
@@ -5,7 +5,7 @@
<div class="brand-logo">
<i class="fas fa-shield-alt"></i>
</div>
<h1>OpenVPN Monitor</h1>
<h1>OpenVPN Controller</h1>
<p class="text-muted">Secure Access Control</p>
</div>
@@ -13,28 +13,32 @@
<!-- Standard Login -->
<form v-if="!requires2FA" @submit.prevent="handleLogin">
<div class="mb-4">
<label class="form-label">Username</label>
<label class="form-label" for="loginUsername">Username</label>
<div class="input-group">
<span class="input-group-text"><i class="fas fa-user"></i></span>
<input
id="loginUsername"
type="text"
class="form-control"
v-model="form.username"
placeholder="Enter username"
autocomplete="username"
required
>
</div>
</div>
<div class="mb-4">
<label class="form-label">Password</label>
<label class="form-label" for="loginPassword">Password</label>
<div class="input-group">
<span class="input-group-text"><i class="fas fa-lock"></i></span>
<input
id="loginPassword"
type="password"
class="form-control"
v-model="form.password"
placeholder="Enter password"
autocomplete="current-password"
required
>
</div>
@@ -65,6 +69,9 @@
v-model="otp"
placeholder="000 000"
maxlength="6"
inputmode="numeric"
autocomplete="one-time-code"
aria-label="6-digit authentication code"
required
autofocus
>
@@ -86,7 +93,7 @@
</div>
<div class="login-footer text-center mt-4">
<p class="small text-muted">&copy; 2026 Admin Dashboard</p>
<p class="small text-muted">&copy; 2026 OpenVPN Controller</p>
</div>
</div>
</div>
@@ -98,7 +105,7 @@ import { useRouter } from 'vue-router';
import { useApi } from '../composables/useApi';
const router = useRouter();
const { apiClient } = useApi();
const { authApiClient } = useApi();
const loading = ref(false);
const error = ref('');
const requires2FA = ref(false);
@@ -114,9 +121,7 @@ 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);
const response = await authApiClient.post('/login', form);
if (response.data.requires_2fa) {
requires2FA.value = true;
tempToken.value = response.data.temp_token;
@@ -137,7 +142,7 @@ const handleVerify2FA = async () => {
loading.value = true;
error.value = '';
try {
const response = await apiClient.post('../auth/verify-2fa', {
const response = await authApiClient.post('/verify-2fa', {
temp_token: tempToken.value,
otp: otp.value
});
-251
View File
@@ -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">&copy; 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>
+25 -6
View File
@@ -165,6 +165,8 @@
</form>
</div>
<ConfirmModal ref="initModal" @confirm="runInit" />
<ConfirmModal ref="clearModal" @confirm="runClear" />
</div>
</template>
@@ -174,6 +176,7 @@ import { ref, computed, onMounted, onUnmounted, reactive } from 'vue';
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 toast = useToast();
@@ -198,6 +201,8 @@ const form = reactive({
easyrsa_batch: true
});
const initModal = ref(null);
const clearModal = ref(null);
const isLoading = ref(false);
const action = ref(''); // 'save', 'init', 'clear'
@@ -232,7 +237,7 @@ const loadConfig = async () => {
// Populate form
Object.keys(data).forEach(key => {
if (form.hasOwnProperty(key)) {
if (Object.hasOwn(form, key)) {
form[key] = data[key];
}
});
@@ -290,9 +295,16 @@ const handleSave = async () => {
}
};
const handleInit = async () => {
if (!confirm('Are you sure you want to Initialize system? This will start the PKI initialization process.')) return;
const handleInit = () => {
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;
action.value = 'init'; // locks the button until the server confirms the job state
try {
@@ -312,9 +324,16 @@ const handleInit = async () => {
}
};
const handleClear = async () => {
if (!confirm('Are you sure you want to CLEAR PKI? This will delete all certificates and cannot be undone.')) return;
const handleClear = () => {
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;
action.value = 'clear';
try {
+16 -2
View File
@@ -84,6 +84,8 @@
</div>
</div>
<ConfirmModal ref="confirmModal" @confirm="runControl" />
</div>
</template>
@@ -92,6 +94,7 @@ import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
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 toast = useToast();
@@ -114,6 +117,7 @@ const stats = reactive({
uptime: null
});
const confirmModal = ref(null);
const isLoading = ref(false);
const action = ref(''); // 'start', 'stop', 'restart'
let pollInterval = null;
@@ -131,9 +135,19 @@ const fetchStats = async () => {
}
};
const handleControl = async (cmd) => {
if (!confirm(`Are you sure you want to ${cmd.toUpperCase()} the OpenVPN service?`)) return;
const CONFIRM_CLASSES = { start: 'btn-action-primary', restart: 'btn-action-save', stop: 'btn-action-danger' };
const handleControl = (cmd) => {
confirmModal.value.open({
title: `${cmd.charAt(0).toUpperCase()}${cmd.slice(1)} the service?`,
message: `Are you sure you want to ${cmd.toUpperCase()} the OpenVPN service?`,
confirmText: `Yes, ${cmd}`,
confirmBtnClass: CONFIRM_CLASSES[cmd],
data: cmd
});
};
const runControl = async (cmd) => {
isLoading.value = true;
action.value = cmd;
+18 -18
View File
@@ -264,6 +264,7 @@ import { ref, onMounted, reactive, watch } from 'vue';
import { useApi } from '../composables/useApi';
import { useToast } from '../composables/useToast';
import { usePkiStatus } from '../composables/usePkiStatus';
import { maskToCidr, parseCidr } from '../utils/cidr';
const { profilesApiClient } = useApi();
const toast = useToast();
@@ -302,15 +303,8 @@ watch(isSplitTunnel, (val) => {
form.tunnel_type = val ? 'SPLIT' : 'FULL';
});
// Helpers
function maskToCidr(mask) {
if (!mask) return '';
const parts = mask.split('.');
let bits = 0;
const map = {255:8, 254:7, 252:6, 248:5, 240:4, 224:3, 192:2, 128:1, 0:0};
for(let p of parts) bits += map[parseInt(p)] || 0;
return bits;
}
// Netmask received from the server: used when the subnet is typed without a /nn suffix
let currentNetmask = '';
// Methods
const showMessage = (text, type = 'success') => toast.show(text, type);
@@ -329,7 +323,7 @@ const loadConfig = async () => {
const data = payload.server ? payload.server : payload;
Object.keys(data).forEach(key => {
if (form.hasOwnProperty(key)) {
if (Object.hasOwn(form, key)) {
if (key === 'tunnel_type') {
isSplitTunnel.value = data[key] === 'SPLIT';
}
@@ -337,9 +331,10 @@ const loadConfig = async () => {
}
});
currentNetmask = data.vpn_netmask || '';
if (data.vpn_network && data.vpn_netmask) {
const cidrSuffix = maskToCidr(data.vpn_netmask);
if (cidrSuffix) {
if (cidrSuffix !== null) {
form.vpn_network = `${data.vpn_network}/${cidrSuffix}`;
}
}
@@ -351,20 +346,25 @@ const loadConfig = async () => {
};
const handleSave = async () => {
// The API takes the address and the netmask separately: without vpn_netmask it resets the mask to 255.255.255.0
const subnet = parseCidr(form.vpn_network);
if (!subnet) {
showMessage('VPN subnet must be an IPv4 network in CIDR format, e.g. 172.20.1.0/24', 'error');
return;
}
isLoading.value = true;
action.value = 'save';
const payload = { ...form };
payload.split_routes = payload.split_routes.filter(r => r && r.trim() !== '');
payload.dns_servers = payload.dns_servers.filter(d => d && d.trim() !== '');
if (payload.vpn_network.includes('/')) {
const [ip, suffix] = payload.vpn_network.split('/');
payload.vpn_network = ip;
}
payload.vpn_network = subnet.network;
payload.vpn_netmask = subnet.netmask || currentNetmask || '255.255.255.0';
try {
await profilesApiClient.put('/config/server', payload);
currentNetmask = payload.vpn_netmask;
showMessage('Server configuration saved!', 'success');
} catch (err) {
showMessage(`Error saving: ${err.response?.data?.detail || err.message}`, 'error');
+1 -1
View File
@@ -9,7 +9,7 @@ export default defineConfig({
output: {
manualChunks: {
'vendor-charts': ['chart.js'],
'vendor-ui': ['bootstrap', 'sweetalert2']
'vendor-ui': ['bootstrap']
}
}
}
+17
View File
@@ -0,0 +1,17 @@
# Deployment records: ENTRY on Timeweb with a Hysteria2 chain
Records of **one concrete deployment**: the OpenVPN Monitor on an Alpine host at Timeweb ("ENTRY") whose VPN clients leave the internet through a Hysteria2 tunnel to an exit node ("EXIT", Debian, Gcore). Host addresses, the account name and the certificate fingerprint appear in these files; no passwords or keys are stored.
**This folder is not part of the product documentation.** To install the application use [DOCS/Deployment](../../DOCS/Deployment/README.md). Nothing in `DOCS/` depends on these files, and you do not need Hysteria2 to run the application.
| Document | Content |
|---|---|
| [Hysteria_Chain_Manifest.md](Hysteria_Chain_Manifest.md) | The entry-exit chain: prerequisites, EXIT and ENTRY setup, clients, diagnostics, error table |
| [Egress_via_Hysteria2.md](Egress_via_Hysteria2.md) | Routing the OpenVPN client network through the `hytun` tunnel (policy routing, anti-leak) |
| [SUMMARY-ovpn-monitor.md](SUMMARY-ovpn-monitor.md) | State of the host, access, install, security findings and fixes, open items (Russian) |
| [REBOOT-TEST.md](REBOOT-TEST.md) | Reboot tests of both nodes |
| [PLAN-validation-and-privilege-drop.md](PLAN-validation-and-privilege-drop.md) | Plan: settings validation and running the APIs unprivileged (Russian) |
| [IMPLEMENTATION-01-settings-validation.md](IMPLEMENTATION-01-settings-validation.md) | Rollout record: settings validation |
| [IMPLEMENTATION-02-privilege-separation.md](IMPLEMENTATION-02-privilege-separation.md) | Rollout record: privilege separation and CRL publishing |
The product-side description of the same changes is in [DOCS/Changes](../../DOCS/Changes/README.md) (settings validation, privilege separation).
File renamed without changes.
@@ -80,4 +80,4 @@ Results (throw-away second OpenVPN instance on another port/subnet running as `n
The helper reads an optional **`/etc/ovpmon/helper.conf`** (INI, section `[helper]`) with keys `install_dir`, `service_manager` (`openrc` or `systemd`), `service_unit`, `config_path`, `staged_path`. Without the file the built-in values apply, which are exactly the previous hard-coded ones (OpenRC `rc-service openvpn`, `/etc/openvpn/server.conf`, PKI below `/opt/OpenVPN-Monitoring-Simple`): existing hosts behave as before. The helper runs through `doas` with a stripped environment, so it reads its own file: it must be a regular file owned by root and not group/world writable, every value is validated strictly (absolute paths without `..`, `config_path` below `/etc/openvpn/`, `staged_path` below `/var/lib/ovpmon/`, unit name `^[A-Za-z0-9@._-]{1,64}$`, fixed set of managers), unknown keys and invalid values make the helper refuse. With `systemd` it runs `systemctl <action> <unit>` (default unit `openvpn-server@server`, fixed argument list and `PATH`); the `/etc/openvpn/openvpn.conf` link is created only for OpenRC. The `doas` rules file is unchanged (on Debian/Ubuntu the package is `opendoas`, rules in `/etc/doas.conf`).
`APP_PROFILER/services/process.py` honours `OVPMON_RUNTIME=host|container` (explicit override of the container detection) and, for the root (non-helper) path, `OVPMON_OPENVPN_SERVICE` (default `openvpn`) and `OVPMON_OPENVPN_CONFIG` (default `/etc/openvpn/server.conf`). Installation: [Scenario 2](../Deployment/Scenario2_System_Services.md). Test: `APP_PROFILER/test_helper_config.py`.
`APP_PROFILER/services/process.py` honours `OVPMON_RUNTIME=host|container` (explicit override of the container detection) and, for the root (non-helper) path, `OVPMON_OPENVPN_SERVICE` (default `openvpn`) and `OVPMON_OPENVPN_CONFIG` (default `/etc/openvpn/server.conf`). Installation: [Scenario 2](../Deployment/System_Services/README.md). Test: `APP_PROFILER/test_helper_config.py`.
+21
View File
@@ -0,0 +1,21 @@
# Анализ кодовой базы: итог (2026-10-05)
План: [2026-10-05_Code_Review_PLAN.md](2026-10-05_Code_Review_PLAN.md). Отчёт: [DOCS/code_review/2026-10-05_1607Z_Codebase_Analysis.md](../code_review/2026-10-05_1607Z_Codebase_Analysis.md).
## Что сделано
- Прочитан код `APP_CORE`, `APP_PROFILER`, root-помощника, контейнеров и ключевых скриптов `deploy/`; UI проверен на места риска.
- Граф знаний использован для метрик по областям, самых связных узлов, мостов, когезии сообществ и связей между компонентами. Найден артефакт графа: стандартный `logging` разрешается в `APP_PROFILER/utils/logging.py` (пять ложных рёбер).
- Запущены `pyflakes`, `bandit`, `shellcheck`, `bash -n` и оба набора тестов (в изолированном venv вне репозитория).
## Результат
28 находок с серьёзностью и статусом проверки (12 по безопасности, 9 по корректности, 7 по архитектуре) и отдельный раздел по тестам и качеству; 21 рекомендация в порядке P0, P1, P2. Три главных: ключ JWT по умолчанию, перебор 2FA без ограничения, застревание отзыва сертификата. Измерено: тесты Core 7 из 7, профайлер 11 из 13 (два устаревших теста), 0 ошибок `shellcheck`, 30 замечаний `bandit` (все B608 проверены вручную).
## Не выполнено
Динамическая проверка на живом хосте, сканирование зависимостей, нагрузка. Список в разделе 5 отчёта.
## Побочные эффекты
Код не менялся. Тесты создали `APP_PROFILER/profiler.log`; файл удалён.
@@ -0,0 +1,20 @@
# Анализ кодовой базы: план (2026-10-05)
## Цель
Комплексная оценка кодовой базы с опорой на граф знаний (`graphify-out/`): архитектура, безопасность, корректность, сопровождаемость, тесты, эксплуатация. Результат фиксируется в `DOCS/code_review/` с отметкой времени в имени файла.
## Метод
1. Граф: метрики по областям, связи между компонентами, узлы-мосты, когезия сообществ, самые связные узлы.
2. Чтение кода: `APP_CORE` (API, сборщик, БД), `APP_PROFILER` (роутеры, PKI, процесс, генератор), root-помощник `ovpmon-helper`, UI (маршруты, API-клиент, места риска XSS), контейнеры и compose, скрипты `deploy/`.
3. Инструменты в изолированном venv вне репозитория: `pyflakes`, `bandit`, `shellcheck`, `bash -n`, оба набора тестов.
4. Каждая находка помечается статусом проверки: подтверждено кодом, воспроизведено инструментом, не воспроизведено.
## Границы
Код и конфигурации не меняются. Динамическое тестирование на живом хосте, сканирование уязвимостей зависимостей (`pip-audit`, `npm audit`) и нагрузочные испытания не выполняются.
## Результат
`DOCS/code_review/<UTC-время>_Codebase_Analysis.md` и сводка по выполненному в `2026-10-05_Code_Review.md`.
@@ -0,0 +1,49 @@
# Documentation refactoring: summary (2026-10-05)
Plan: [2026-10-05_Docs_Refactoring_PLAN.md](2026-10-05_Docs_Refactoring_PLAN.md).
## Result
| Category | Where | Content |
|---|---|---|
| General information | `DOCS/General/` | new `Overview.md` (components, ports, data, glossary), new `Configuration.md`, `Security_Architecture.md`, `Database_Migrations.md` |
| Installation methods | `DOCS/Deployment/README.md`, `First_Steps.md` | side-by-side comparison, a recommendation, rules common to both methods; the post-install path (sign in, account, PKI, VPN, start, first client, network) written once for both |
| Details: containers | `DOCS/Deployment/Containers/` | `README` (quick start, variants, requirements, install), `Operations`, `Reference`, `Troubleshooting` |
| Details: system services | `DOCS/Deployment/System_Services/` | `README` (quick start, supported systems, install per OS, verification), `Operations`, `Reference`, `Web_UI`, `Firewall`, `Nginx_Configuration`, `Service_Management`, `Troubleshooting` |
| Entry points | `README.md`, `DOCS/README.md` | the root README is short: what it is, install in three steps, a map; `DOCS/README.md` maps goals to pages |
| Changes | `DOCS/Changes/README.md` | the change log moved out of the root README |
The two long scenario files (261 and 493 lines) were split by sections; the text was moved as it is, only cross-references were updated.
## Isolated: Hysteria2 on Timeweb
`DEPLOYMENTS/timeweb-hysteria2/` (outside `DOCS/`): the chain manifest, the egress change, the host summary, the reboot test, the plan and both rollout records of the settings validation and privilege separation (they describe the rollout on that host). It has its own README; the general documentation does not link to it; the folder is listed in `.graphifyignore`. The host addresses, the account name and the certificate fingerprint now live only there.
Left in the general documentation on purpose: neutral technical mentions of the Hysteria2 tunnel as an example of an uplink (the firewall script and its change records) and two verification rows of the privilege-separation record. They contain no host data.
## Removed or replaced
| Removed | Why |
|---|---|
| `General/Deployment.md` | outdated (port 5000, `UI/client`, other variable name), contradicted the current guides; superseded by `Deployment/` |
| `General/Deployment_Docker.md`, `Deployment_Native.md` | pointers only (the native one carried an outdated quick start) |
| `General/Index.md` | replaced by `DOCS/README.md` |
| `Deployment/Scenario1_Containers.md`, `Scenario2_System_Services.md` | split into the two folders |
## Other fixes
- `Security_Architecture.md`: links to files on the author's Mac (`file:///Users/...`) replaced by repository-relative links; a link to a file that does not exist (`Setup2FA.vue`) turned into text.
- Comments in `deploy/*` scripts, `docker-compose*.yml` and the nginx template, and two runtime error messages (`deploy/allinone/entrypoint.sh`, `deploy/docker/lib.sh`), now point to the new pages. No logic changed (`bash -n` passes on all changed scripts); the all-in-one image picks up the new message at the next rebuild.
- The change records of 2026-09/10 keep their original wording; only their links were updated.
## Verification
- Every relative Markdown link and anchor in `README.md`, `DOCS/`, `DEPLOYMENTS/` and the component READMEs: 60 files, 0 problems.
- No document under `DOCS/` links to `DEPLOYMENTS/`.
- Facts of the new pages were taken from the previous guides and checked against the sources: UI menu and button names (`App.vue`, `PKIConfig.vue`, `ServerManagement.vue`, `Certificates.vue`), container NAT and forwarding (`entrypoint.sh`, compose files).
## Not done
- The newcomer path was **not** walked through on a clean host: the commands are those of the existing, previously tested guides.
- The knowledge graph is stale for the moved files: run `/graphify --update .`.
- Translation: all documents stay in English (the two Russian records live in `DEPLOYMENTS/`).
@@ -0,0 +1,59 @@
# Documentation refactoring: plan (2026-10-05)
## Goal
A newcomer who has never seen the project can bring up a working environment by **any** supported method, using the documentation alone. The documentation is split into three categories; everything specific to one concrete host (Hysteria2 chain on Timeweb) is taken out of the general documentation.
## Problems found (from the knowledge graph and a read of all documents)
| Problem | Evidence |
|---|---|
| No single place says which installation method to pick | the README has three one-line quick starts, `DOCS/General/Index.md` lists four deployment pages |
| Outdated guide competes with the current ones | `General/Deployment.md` (port 5000, `UI/client`, `OVPMON_SECRET_KEY`) contradicts Scenario 1 and 2; `Deployment_Docker.md` and `Deployment_Native.md` are pointers only (the native pointer still says "build the UI with Docker first") |
| Two 260-500 line files mix quick start, reference, operations and troubleshooting | `Scenario1_Containers.md` (261 lines), `Scenario2_System_Services.md` (493 lines) |
| No common "after the install" path | the same three sentences are repeated in each scenario and in the README |
| The README carries a 14-row change log and security notes before the newcomer reaches the install | README sections order |
| Host-specific records sit in the general tree | `DOCS/Operations/` (IPs, login, certificate fingerprint of the Timeweb host) and `Changes/2026-09-30_Egress_via_Hysteria2.md` |
## Target structure
```
README.md what it is, architecture, install in 3 steps, map of the docs
DOCS/README.md documentation map by goal ("I want to ...")
DOCS/General/ 1. general information
Overview.md components, ports, data, glossary
Configuration.md config.ini and environment variables
Security_Architecture.md (kept)
Database_Migrations.md (kept)
systemd/ openrc/ privilege-separation/ service files and the helper: used by the install scripts, not moved
DOCS/Deployment/ 2. installation methods
README.md choose a method, requirements side by side
First_Steps.md the same for every method: sign in, PKI, server, first profile
Containers/ 3a. details: containers (variants A and B)
README.md Operations.md Reference.md Troubleshooting.md
System_Services/ 3b. details: Alpine, Debian, Ubuntu without containers
README.md Operations.md Reference.md Web_UI.md Firewall.md Nginx.md Troubleshooting.md
DOCS/Core_Monitoring, Profiler_Management, UI API and component reference (kept)
DOCS/Changes/ records of changes, with an index (README.md)
DEPLOYMENTS/timeweb-hysteria2/ isolated: records of the Hysteria2 chain and the host on Timeweb
```
## Steps
1. Isolate the host-specific records: `git mv DOCS/Operations` and the Hysteria2 change to `DEPLOYMENTS/timeweb-hysteria2/`; nothing in the general documentation links there; the folder is added to `.graphifyignore`.
2. Split Scenario 1 and Scenario 2 by their sections into the folders above (content is moved, not rewritten); add a short quick start on top of each folder `README.md`.
3. Write the new documents: `Overview`, `Configuration`, `Deployment/README`, `First_Steps`, `DOCS/README`, `Changes/README`.
4. Remove the superseded pages (`General/Deployment.md`, `Deployment_Docker.md`, `Deployment_Native.md`, `Index.md`); move `Service_Management.md` and `Nginx_Configuration.md` under `System_Services/`.
5. Rewrite the root `README.md` and fix the references: comments in `deploy/*` scripts and compose files (comments only), component READMEs, other documents.
6. Check every relative Markdown link and every script reference; `bash -n` on the changed scripts.
## Rules
- Content is not lost: sections are moved as they are; only duplicated text is replaced by a link.
- Install scripts keep working: the paths they read (`DOCS/General/systemd`, `openrc`, `privilege-separation`) do not change.
- Documents stay in English like the rest of the repository.
- No code or behaviour changes; script edits are comments only.
## Out of scope
Translating the documents, rewriting the API references, rebuilding the knowledge graph (the moved files need a `/graphify --update`).
@@ -0,0 +1,46 @@
# Сборщик трафика: устойчивость и точность учёта (итог, 2026-10-05)
План: [2026-10-05_Gatherer_Reliability_PLAN.md](2026-10-05_Gatherer_Reliability_PLAN.md). Закрыты находки BUG-02 и BUG-03 [отчёта анализа кода](../code_review/2026-10-05_1607Z_Codebase_Analysis.md).
## Что сделано
| Область | Изменение |
|---|---|
| Идентичность сессии | ключ `(CN, адрес, connected_since_ts)` из `Connected Since (time_t)` статуса v2; порог 10 МБ остался только как запасной путь без `time_t` |
| Новая сессия | считается с нуля при любом первом объёме (BUG-03); строка нового клиента создаётся с итогами первого кадра (BUG-03b, найдено при ревью) |
| Перезапуск демона | базовая линия из снимка `active_sessions`; трафик простоя учитывается; без снимка прирост 0 и запись в лог |
| Исчезновение из статуса | льготный период `session_grace_ticks`; плюс «память» о удалённых сессиях на 1 час против двойного учёта |
| Чтение статуса | `parse_status`: нужны `TITLE`, `TIME`, последняя строка `END`; рваный кадр пропускает тик целиком; устаревший `TIME` означает остановленный OpenVPN |
| Кэш и БД | изменения кэша применяются после `commit`; при ошибке БД откат и исключение (цикл повторит, прирост не теряется) |
| Цикл | исключение не завершает демон; пауза `max(interval, min(interval*2^n, 60))`; `SIGTERM`/`SIGINT` останавливают после текущего цикла; настройки проверяются при старте |
| `active_sessions.connected_since` | реальное начало сессии в UTC (раньше локальное время первого наблюдения) |
| Конфигурация | `session_grace_ticks=3`, `status_stale_seconds=60`, `status_invalid_max=6` в `[openvpn_monitor]` |
| Документация | `Data_Architecture.md` (разделы B и B1), `API_Reference.md` (`connected_since`, `last_seen`), `config.ini` |
Схема БД и формат API не менялись. Файлы: `APP_CORE/openvpn_gatherer_v3.py`, `APP_CORE/test_gatherer.py` (5 тестов), `APP_CORE/config.ini`.
## Разработка и ревью
Код и тесты написал субагент без запуска тестов. Ревью выполнено отдельно: чтение кода и запуск проверок. Результат ревью: код соответствует плану, отклонения субагента обоснованы (ошибка БД пробрасывается циклу, «память» удалённых сессий, невалидный файл без `TIME`, пауза не меньше интервала). Найден и исправлен один дефект: `INSERT` нового клиента с нулевыми итогами (4 теста из 5 были красными до правки).
## Проверка
| Проверка | Результат |
|---|---|
| `pytest` Core: `test_gatherer.py` + `test_migrations.py` | 12 из 12 (5 новых + 7 прежних) |
| Новые тесты на старой логике (`HEAD`) | 5 из 5 красные |
| `pyflakes` | новых замечаний нет (`sqlite3` не используется: было и раньше) |
| Реальный процесс: рост счётчика 1 МБ/с, `SIGTERM` посреди передачи, перезапуск | итоги `clients` и `usage_history` равны последним счётчикам (12 000 000 / 1 200 000), трафик простоя учтён, оба выхода с кодом 0, предупреждений нет |
| Неверный `check_interval=abc` | сообщение `Invalid configuration` и отказ запуска |
## Не проверялось
- Гонка чтения реального файла OpenVPN (рваный кадр проверен синтетически); `kill -TERM` на живом OpenVPN-хосте и остановка OpenVPN для проверки `Disconnected` по устаревшему `TIME`.
- Обновление через `update.sh` на тестовом хосте (бэкап, перезапуск, откат).
- Сигналы под supervisord, systemd и OpenRC: все три отправляют `SIGTERM`, но на живых службах не запускались.
## Остаточные риски
- Однократно после обновления: сессии, подключённые в момент обновления, получают базовую линию (строки старого снимка не совпадают с новыми ключами).
- Мигание статуса клиента при кадре, прошедшем проверку `END`, но смешанном из старого и нового содержимого: учёт защищён льготным периодом, статус нет.
- Три записи цикла (учёт, история, агрегация) по-прежнему в отдельных транзакциях; healthcheck контейнера проверяет только наличие процесса.
Loaded 100 of 207 files, more files were not shown because too many files have changed in this diff. Show more