Compare commits
21
Commits
f8c2f3c21d
...
main
No files matched your search
@@ -8,3 +8,6 @@ deploy/native/ui-dist.tar.gz
|
|||||||
# Python caches (tests and compile steps create them inside the tree)
|
# Python caches (tests and compile steps create them inside the tree)
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
*.pyc
|
||||||
|
|
||||||
|
# local development environment
|
||||||
|
venv/
|
||||||
@@ -13,6 +13,7 @@ The **Core Monitoring** module provides the backend logic for collecting, extrac
|
|||||||
- A background service/daemon.
|
- A background service/daemon.
|
||||||
- Parses OpenVPN server logs (`status.log`).
|
- Parses OpenVPN server logs (`status.log`).
|
||||||
- Aggregates bandwidth usage into time-series tables (`usage_history`, `stats_hourly`, etc.).
|
- Aggregates bandwidth usage into time-series tables (`usage_history`, `stats_hourly`, etc.).
|
||||||
|
- Several simultaneous sessions of one user (`duplicate-cn`) are one record: traffic, speed and history are summed per common name; a session is identified by `Client ID` (see `DOCS/Core_Monitoring/Data_Architecture.md`).
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
|
|||||||
@@ -37,6 +37,9 @@ def main(argv=None):
|
|||||||
if st.too_new:
|
if st.too_new:
|
||||||
raise migrations._too_new_error(st)
|
raise migrations._too_new_error(st)
|
||||||
print(f"Database: {db_path}" + ("" if st.exists else " (does not exist yet)"))
|
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:
|
if args.check:
|
||||||
print(f"Schema version: {st.current} (latest known: {migrations.latest_version()})")
|
print(f"Schema version: {st.current} (latest known: {migrations.latest_version()})")
|
||||||
if not st.pending:
|
if not st.pending:
|
||||||
|
|||||||
@@ -459,8 +459,17 @@ def _m001_baseline(conn):
|
|||||||
_ensure_column('users', 'is_2fa_enabled', 'INTEGER DEFAULT 0')
|
_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 = [
|
MIGRATIONS = [
|
||||||
Migration(1, "baseline", _m001_baseline),
|
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
|
# No separate "fresh" schema: the baseline migration creates everything on a new database
|
||||||
|
|||||||
+90
-25
@@ -29,6 +29,29 @@ app = Flask(__name__)
|
|||||||
# Cross-origin access is off by default (the UI is same-origin behind Nginx); allow extra origins via OVPMON_CORS_ORIGINS (comma-separated)
|
# Cross-origin access is off by default (the UI is same-origin behind Nginx); allow extra origins via OVPMON_CORS_ORIGINS (comma-separated)
|
||||||
CORS(app, resources={r"/api/*": {"origins": [o.strip() for o in os.getenv("OVPMON_CORS_ORIGINS", "").split(",") if o.strip()]}}, supports_credentials=True)
|
CORS(app, resources={r"/api/*": {"origins": [o.strip() for o in os.getenv("OVPMON_CORS_ORIGINS", "").split(",") if o.strip()]}}, supports_credentials=True)
|
||||||
|
|
||||||
|
# Length of one bucket of the aggregate tables, seconds. The aggregates hold only bytes, so for periods
|
||||||
|
# longer than a day the speed is the bucket average: bytes * 8 / 1e6 / bucket duration.
|
||||||
|
BUCKET_SECONDS = {
|
||||||
|
'stats_5min': 300,
|
||||||
|
'stats_15min': 900,
|
||||||
|
'stats_hourly': 3600,
|
||||||
|
'stats_6h': 21600,
|
||||||
|
'stats_daily': 86400,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def avg_rate_sql(table, bytes_expr, ts_expr):
|
||||||
|
"""SQL expression of the average speed (Mbps) of a bucket of an aggregate table.
|
||||||
|
|
||||||
|
The current (incomplete) bucket lasts min(bucket length, time since its start), at least 1 second;
|
||||||
|
timestamps of the aggregates are UTC. `table` is taken only from BUCKET_SECONDS (never user input),
|
||||||
|
the other arguments are fixed column expressions of the caller.
|
||||||
|
"""
|
||||||
|
seconds = BUCKET_SECONDS[table]
|
||||||
|
return (f"({bytes_expr}) * 8.0 / 1000000.0 / "
|
||||||
|
f"MAX(1, MIN({seconds}, CAST(strftime('%s', 'now') AS INTEGER) - CAST(strftime('%s', {ts_expr}) AS INTEGER)))")
|
||||||
|
|
||||||
|
|
||||||
class OpenVPNAPI:
|
class OpenVPNAPI:
|
||||||
def get_config_value(self, section, key, fallback=None):
|
def get_config_value(self, section, key, fallback=None):
|
||||||
try:
|
try:
|
||||||
@@ -169,15 +192,20 @@ class OpenVPNAPI:
|
|||||||
c.total_bytes_received,
|
c.total_bytes_received,
|
||||||
c.total_bytes_sent,
|
c.total_bytes_sent,
|
||||||
-- Пиковая скорость Download за последние 2 минуты
|
-- Пиковая скорость Download за последние 2 минуты
|
||||||
(SELECT MAX(uh.bytes_received_rate_mbps)
|
-- (скорость пользователя = сумма по его сессиям на одной отметке времени)
|
||||||
FROM usage_history uh
|
(SELECT MAX(s.rate) FROM (
|
||||||
WHERE uh.client_id = c.id
|
SELECT SUM(uh.bytes_received_rate_mbps) as rate
|
||||||
AND uh.timestamp >= datetime('now', '-30 seconds')) as current_recv_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 минуты
|
-- Пиковая скорость Upload за последние 2 минуты
|
||||||
(SELECT MAX(uh.bytes_sent_rate_mbps)
|
(SELECT MAX(s.rate) FROM (
|
||||||
FROM usage_history uh
|
SELECT SUM(uh.bytes_sent_rate_mbps) as rate
|
||||||
WHERE uh.client_id = c.id
|
FROM usage_history uh
|
||||||
AND uh.timestamp >= datetime('now', '-30 seconds')) as current_sent_rate,
|
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
|
strftime('%Y-%m-%d %H:%M:%S', c.updated_at) as last_updated
|
||||||
FROM clients c
|
FROM clients c
|
||||||
ORDER BY c.status DESC, c.common_name
|
ORDER BY c.status DESC, c.common_name
|
||||||
@@ -188,7 +216,32 @@ class OpenVPNAPI:
|
|||||||
|
|
||||||
for row in cursor.fetchall():
|
for row in cursor.fetchall():
|
||||||
data.append(dict(zip(columns, row)))
|
data.append(dict(zip(columns, row)))
|
||||||
|
|
||||||
|
# Active sessions per CN (the table may be absent on an old database)
|
||||||
|
sessions_by_cn = {}
|
||||||
|
try:
|
||||||
|
cursor.execute('''
|
||||||
|
SELECT common_name, real_address, connected_since, bytes_received, bytes_sent
|
||||||
|
FROM active_sessions
|
||||||
|
ORDER BY connected_since, real_address
|
||||||
|
''')
|
||||||
|
for cn, addr, since, rx, tx in cursor.fetchall():
|
||||||
|
sessions_by_cn.setdefault(cn, []).append({
|
||||||
|
'real_address': addr,
|
||||||
|
'connected_since': since,
|
||||||
|
'bytes_received': rx or 0,
|
||||||
|
'bytes_sent': tx or 0,
|
||||||
|
'received_mb': round((rx or 0) / (1024 * 1024), 2),
|
||||||
|
'sent_mb': round((tx or 0) / (1024 * 1024), 2),
|
||||||
|
})
|
||||||
|
except sqlite3.Error:
|
||||||
|
sessions_by_cn = {}
|
||||||
|
|
||||||
|
for client in data:
|
||||||
|
sessions = sessions_by_cn.get(client['common_name'], []) if client['status'] == 'Active' else []
|
||||||
|
client['sessions_count'] = len(sessions)
|
||||||
|
client['sessions'] = sessions
|
||||||
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -288,17 +341,27 @@ class OpenVPNAPI:
|
|||||||
points_count = 96
|
points_count = 96
|
||||||
|
|
||||||
if is_high_res:
|
if is_high_res:
|
||||||
|
# Внутренний запрос: сумма по сессиям на одной отметке времени
|
||||||
|
# (старые строки хранят по записи на сессию), внешний: MAX скорости в интервале
|
||||||
query = f'''
|
query = f'''
|
||||||
SELECT
|
SELECT
|
||||||
datetime((strftime('%s', uh.timestamp) / {interval}) * {interval}, 'unixepoch') as timestamp,
|
datetime((strftime('%s', u.timestamp) / {interval}) * {interval}, 'unixepoch') as timestamp,
|
||||||
SUM(uh.bytes_received) as bytes_received,
|
SUM(u.bytes_received) as bytes_received,
|
||||||
SUM(uh.bytes_sent) as bytes_sent,
|
SUM(u.bytes_sent) as bytes_sent,
|
||||||
MAX(uh.bytes_received_rate_mbps) as bytes_received_rate_mbps,
|
MAX(u.bytes_received_rate_mbps) as bytes_received_rate_mbps,
|
||||||
MAX(uh.bytes_sent_rate_mbps) as bytes_sent_rate_mbps
|
MAX(u.bytes_sent_rate_mbps) as bytes_sent_rate_mbps
|
||||||
FROM usage_history uh
|
FROM (
|
||||||
JOIN clients c ON uh.client_id = c.id
|
SELECT uh.timestamp as timestamp,
|
||||||
WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ?
|
SUM(uh.bytes_received) as bytes_received,
|
||||||
GROUP BY datetime((strftime('%s', uh.timestamp) / {interval}) * {interval}, 'unixepoch')
|
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
|
ORDER BY timestamp ASC
|
||||||
'''
|
'''
|
||||||
elif is_aggregated:
|
elif is_aggregated:
|
||||||
@@ -307,8 +370,8 @@ class OpenVPNAPI:
|
|||||||
t.timestamp,
|
t.timestamp,
|
||||||
t.bytes_received,
|
t.bytes_received,
|
||||||
t.bytes_sent,
|
t.bytes_sent,
|
||||||
0 as bytes_received_rate_mbps,
|
{avg_rate_sql(target_table, 't.bytes_received', 't.timestamp')} as bytes_received_rate_mbps,
|
||||||
0 as bytes_sent_rate_mbps
|
{avg_rate_sql(target_table, 't.bytes_sent', 't.timestamp')} as bytes_sent_rate_mbps
|
||||||
FROM {target_table} t
|
FROM {target_table} t
|
||||||
JOIN clients c ON t.client_id = c.id
|
JOIN clients c ON t.client_id = c.id
|
||||||
WHERE c.common_name = ? AND t.timestamp BETWEEN ? AND ?
|
WHERE c.common_name = ? AND t.timestamp BETWEEN ? AND ?
|
||||||
@@ -318,13 +381,14 @@ class OpenVPNAPI:
|
|||||||
query = f'''
|
query = f'''
|
||||||
SELECT
|
SELECT
|
||||||
uh.timestamp,
|
uh.timestamp,
|
||||||
uh.bytes_received,
|
SUM(uh.bytes_received) as bytes_received,
|
||||||
uh.bytes_sent,
|
SUM(uh.bytes_sent) as bytes_sent,
|
||||||
uh.bytes_received_rate_mbps,
|
SUM(uh.bytes_received_rate_mbps) as bytes_received_rate_mbps,
|
||||||
uh.bytes_sent_rate_mbps
|
SUM(uh.bytes_sent_rate_mbps) as bytes_sent_rate_mbps
|
||||||
FROM usage_history uh
|
FROM usage_history uh
|
||||||
JOIN clients c ON uh.client_id = c.id
|
JOIN clients c ON uh.client_id = c.id
|
||||||
WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ?
|
WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ?
|
||||||
|
GROUP BY uh.timestamp
|
||||||
ORDER BY uh.timestamp ASC
|
ORDER BY uh.timestamp ASC
|
||||||
'''
|
'''
|
||||||
|
|
||||||
@@ -461,7 +525,8 @@ class OpenVPNAPI:
|
|||||||
if target_table == 'usage_history':
|
if target_table == 'usage_history':
|
||||||
rate_cols = "SUM(bytes_received_rate_mbps) as total_rx_rate, SUM(bytes_sent_rate_mbps) as total_tx_rate,"
|
rate_cols = "SUM(bytes_received_rate_mbps) as total_rx_rate, SUM(bytes_sent_rate_mbps) as total_tx_rate,"
|
||||||
else:
|
else:
|
||||||
rate_cols = "0 as total_rx_rate, 0 as total_tx_rate,"
|
rate_cols = (f"{avg_rate_sql(target_table, 'SUM(bytes_received)', 'timestamp')} as total_rx_rate, "
|
||||||
|
f"{avg_rate_sql(target_table, 'SUM(bytes_sent)', 'timestamp')} as total_tx_rate,")
|
||||||
|
|
||||||
# Aggregation Query
|
# Aggregation Query
|
||||||
# Group by interval_seconds
|
# Group by interval_seconds
|
||||||
|
|||||||
@@ -135,7 +135,7 @@ class OpenVPNDataGatherer:
|
|||||||
self.ts_aggregator = TimeSeriesAggregator(self.db_manager.get_connection)
|
self.ts_aggregator = TimeSeriesAggregator(self.db_manager.get_connection)
|
||||||
|
|
||||||
# In-Memory Cache для отслеживания сессий:
|
# In-Memory Cache для отслеживания сессий:
|
||||||
# (CN, RealAddress, connected_since_ts) -> {
|
# (CN, Client ID или RealAddress, connected_since_ts) -> {
|
||||||
# 'bytes_received', 'bytes_sent': счётчики на прошлом тике,
|
# 'bytes_received', 'bytes_sent': счётчики на прошлом тике,
|
||||||
# 'last_seen': строка времени, 'connected_since': строка UTC (начало сессии),
|
# 'last_seen': строка времени, 'connected_since': строка UTC (начало сессии),
|
||||||
# 'missing_ticks': сколько тиков подряд сессии нет в статусе (льготный период)}
|
# 'missing_ticks': сколько тиков подряд сессии нет в статусе (льготный период)}
|
||||||
@@ -183,7 +183,7 @@ class OpenVPNDataGatherer:
|
|||||||
conn = self.db_manager.get_connection()
|
conn = self.db_manager.get_connection()
|
||||||
try:
|
try:
|
||||||
rows = conn.execute(
|
rows = conn.execute(
|
||||||
'SELECT common_name, real_address, bytes_received, bytes_sent, connected_since '
|
'SELECT common_name, real_address, bytes_received, bytes_sent, connected_since, session_id '
|
||||||
'FROM active_sessions'
|
'FROM active_sessions'
|
||||||
).fetchall()
|
).fetchall()
|
||||||
finally:
|
finally:
|
||||||
@@ -192,10 +192,11 @@ class OpenVPNDataGatherer:
|
|||||||
self.logger.warning(f"Could not load active_sessions snapshot: {e}")
|
self.logger.warning(f"Could not load active_sessions snapshot: {e}")
|
||||||
return
|
return
|
||||||
|
|
||||||
for name, real_addr, rx, tx, since in rows:
|
for name, real_addr, rx, tx, since, session_id in rows:
|
||||||
try:
|
try:
|
||||||
since_ts = calendar.timegm(time.strptime(str(since)[:19].replace('T', ' '), TS_FORMAT))
|
since_ts = calendar.timegm(time.strptime(str(since)[:19].replace('T', ' '), TS_FORMAT))
|
||||||
self.baseline[(name, real_addr, since_ts)] = (int(rx), int(tx), self.started_at)
|
# Тот же ключ, что у сборщика; строки снимка без session_id совпадают по адресу
|
||||||
|
self.baseline[(name, session_id or real_addr, since_ts)] = (int(rx), int(tx), self.started_at)
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
# Старый формат (локальное время первого наблюдения) - совпасть с ключом не может
|
# Старый формат (локальное время первого наблюдения) - совпасть с ключом не может
|
||||||
continue
|
continue
|
||||||
@@ -382,7 +383,14 @@ class OpenVPNDataGatherer:
|
|||||||
|
|
||||||
status_time = None
|
status_time = None
|
||||||
clients = []
|
clients = []
|
||||||
|
# Индекс колонки Client ID в строках CLIENT_LIST (None = в статусе колонки нет)
|
||||||
|
client_id_idx = None
|
||||||
for line in lines:
|
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,'):
|
if line.startswith('TIME,'):
|
||||||
try:
|
try:
|
||||||
status_time = int(line.split(',')[2])
|
status_time = int(line.split(',')[2])
|
||||||
@@ -417,9 +425,19 @@ class OpenVPNDataGatherer:
|
|||||||
if since_ts is not None and since_ts <= 0:
|
if since_ts is not None and since_ts <= 0:
|
||||||
since_ts = None
|
since_ts = None
|
||||||
|
|
||||||
|
# Client ID не меняется при float (смене адреса): идентификатор сессии;
|
||||||
|
# нет колонки или не число - session_id None (ключ сессии с real_address)
|
||||||
|
session_id = None
|
||||||
|
if client_id_idx is not None and client_id_idx < len(parts):
|
||||||
|
try:
|
||||||
|
session_id = str(int(parts[client_id_idx].strip()))
|
||||||
|
except ValueError:
|
||||||
|
session_id = None
|
||||||
|
|
||||||
client = {
|
client = {
|
||||||
'common_name': parts[1].strip(),
|
'common_name': parts[1].strip(),
|
||||||
'real_address': parts[2].strip(),
|
'real_address': parts[2].strip(),
|
||||||
|
'session_id': session_id,
|
||||||
'bytes_received': int(parts[5].strip()),
|
'bytes_received': int(parts[5].strip()),
|
||||||
'bytes_sent': int(parts[6].strip()),
|
'bytes_sent': int(parts[6].strip()),
|
||||||
'connected_since_ts': since_ts,
|
'connected_since_ts': since_ts,
|
||||||
@@ -454,11 +472,11 @@ class OpenVPNDataGatherer:
|
|||||||
Прирост для сессии, которой нет в кэше (правила: DOCS/Changes/2026-10-05_Gatherer_Reliability_PLAN.md, 2.2).
|
Прирост для сессии, которой нет в кэше (правила: DOCS/Changes/2026-10-05_Gatherer_Reliability_PLAN.md, 2.2).
|
||||||
Возвращает (inc_recv, inc_sent).
|
Возвращает (inc_recv, inc_sent).
|
||||||
"""
|
"""
|
||||||
name, real_addr, since_ts = key
|
name, sess_id, since_ts = key
|
||||||
|
|
||||||
if since_ts is None:
|
if since_ts is None:
|
||||||
# Нестандартный статус: время начала сессии неизвестно, запасная эвристика по размеру счётчиков
|
# Нестандартный статус: время начала сессии неизвестно, запасная эвристика по размеру счётчиков
|
||||||
self.logger.warning(f"No connected_since time_t for {name} ({real_addr}): using 10 MB heuristic")
|
self.logger.warning(f"No connected_since time_t for {name} ({sess_id}): using 10 MB heuristic")
|
||||||
threshold = 10 * 1024 * 1024
|
threshold = 10 * 1024 * 1024
|
||||||
if curr_recv < threshold and curr_sent < threshold:
|
if curr_recv < threshold and curr_sent < threshold:
|
||||||
return curr_recv, curr_sent
|
return curr_recv, curr_sent
|
||||||
@@ -476,7 +494,7 @@ class OpenVPNDataGatherer:
|
|||||||
|
|
||||||
# Сессия старше демона, снимка нет: базовая линия, трафик до этого момента потерян
|
# Сессия старше демона, снимка нет: базовая линия, трафик до этого момента потерян
|
||||||
self.logger.warning(
|
self.logger.warning(
|
||||||
f"Session of {name} ({real_addr}) started before the gatherer and has no snapshot: "
|
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"
|
f"baseline set, {curr_recv} B received / {curr_sent} B sent before this moment are not counted"
|
||||||
)
|
)
|
||||||
return 0, 0
|
return 0, 0
|
||||||
@@ -501,7 +519,8 @@ class OpenVPNDataGatherer:
|
|||||||
db_clients = {row[1]: {'id': row[0], 'status': row[2]} for row in cursor.fetchall()}
|
db_clients = {row[1]: {'id': row[0], 'status': row[2]} for row in cursor.fetchall()}
|
||||||
|
|
||||||
# Структура для агрегации инкрементов по Common Name перед записью в БД
|
# Структура для агрегации инкрементов по Common Name перед записью в БД
|
||||||
# cn -> { 'inc_rx': 0, 'inc_tx': 0, 'curr_rx': 0, 'curr_tx': 0, 'real_address': '...'}
|
# cn -> { 'inc_recv': 0, 'inc_tx': 0, 'max_rx': 0 (сумма текущих счётчиков сессий),
|
||||||
|
# 'max_tx': 0, 'real_address': '...' (сессия с самым поздним началом)}
|
||||||
cn_updates = {}
|
cn_updates = {}
|
||||||
|
|
||||||
# Новое состояние кэша сессий (применяется после commit) и активные CN
|
# Новое состояние кэша сессий (применяется после commit) и активные CN
|
||||||
@@ -516,9 +535,9 @@ class OpenVPNDataGatherer:
|
|||||||
curr_sent = client['bytes_sent']
|
curr_sent = client['bytes_sent']
|
||||||
since_ts = client.get('connected_since_ts')
|
since_ts = client.get('connected_since_ts')
|
||||||
|
|
||||||
# Уникальный ключ сессии: один и тот же CN/адрес может переподключиться
|
# Уникальный ключ сессии: Client ID не меняется при float (смене адреса);
|
||||||
# (новый connected_since) - это уже новая сессия
|
# без Client ID - адрес. Переподключение (новый connected_since) - новая сессия
|
||||||
session_key = (name, real_addr, since_ts)
|
session_key = (name, client.get('session_id') or real_addr, since_ts)
|
||||||
active_cns.add(name)
|
active_cns.add(name)
|
||||||
|
|
||||||
# --- ЛОГИКА РАСЧЕТА ДЕЛЬТЫ (In-Memory) ---
|
# --- ЛОГИКА РАСЧЕТА ДЕЛЬТЫ (In-Memory) ---
|
||||||
@@ -560,17 +579,20 @@ class OpenVPNDataGatherer:
|
|||||||
if name not in cn_updates:
|
if name not in cn_updates:
|
||||||
cn_updates[name] = {
|
cn_updates[name] = {
|
||||||
'inc_recv': 0, 'inc_tx': 0,
|
'inc_recv': 0, 'inc_tx': 0,
|
||||||
'max_rx': 0, 'max_tx': 0, # Для last_bytes в БД сохраним текущие счетчики самой большой сессии (примерно)
|
'max_rx': 0, 'max_tx': 0, # Для last_bytes в БД: сумма текущих счётчиков всех сессий CN
|
||||||
'real_address': real_addr # Берем последний адрес
|
'real_address': real_addr,
|
||||||
|
'addr_since': since_ts or 0 # Начало сессии, чей адрес сохранён
|
||||||
}
|
}
|
||||||
|
|
||||||
cn_updates[name]['inc_recv'] += inc_recv
|
cn_updates[name]['inc_recv'] += inc_recv
|
||||||
cn_updates[name]['inc_tx'] += inc_sent
|
cn_updates[name]['inc_tx'] += inc_sent
|
||||||
# Сохраняем "текущее" значение как максимальное из сессий, чтобы в БД last_bytes было хоть что-то осмысленное
|
# last_bytes в БД = сумма текущих счётчиков всех сессий CN (нужно для UI)
|
||||||
# (хотя при in-memory подходе поле last_bytes в БД теряет смысл для логики, но нужно для UI)
|
cn_updates[name]['max_rx'] += curr_recv
|
||||||
cn_updates[name]['max_rx'] = max(cn_updates[name]['max_rx'], curr_recv)
|
cn_updates[name]['max_tx'] += curr_sent
|
||||||
cn_updates[name]['max_tx'] = max(cn_updates[name]['max_tx'], curr_sent)
|
# real_address = адрес сессии с самым поздним началом
|
||||||
cn_updates[name]['real_address'] = real_addr
|
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. Льготный период для сессий, которых нет в текущем статусе:
|
# 3. Льготный период для сессий, которых нет в текущем статусе:
|
||||||
# запись остаётся в кэше, пока missing_ticks < session_grace_ticks
|
# запись остаётся в кэше, пока missing_ticks < session_grace_ticks
|
||||||
@@ -657,8 +679,8 @@ class OpenVPNDataGatherer:
|
|||||||
if sess_data:
|
if sess_data:
|
||||||
cursor.execute('''
|
cursor.execute('''
|
||||||
INSERT INTO active_sessions
|
INSERT INTO active_sessions
|
||||||
(client_id, common_name, real_address, bytes_received, bytes_sent, connected_since, last_seen)
|
(client_id, common_name, real_address, bytes_received, bytes_sent, connected_since, last_seen, session_id)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
''', (
|
''', (
|
||||||
client['db_id'],
|
client['db_id'],
|
||||||
client['common_name'],
|
client['common_name'],
|
||||||
@@ -666,7 +688,8 @@ class OpenVPNDataGatherer:
|
|||||||
client['bytes_received'],
|
client['bytes_received'],
|
||||||
client['bytes_sent'],
|
client['bytes_sent'],
|
||||||
sess_data['connected_since'],
|
sess_data['connected_since'],
|
||||||
sess_data['last_seen']
|
sess_data['last_seen'],
|
||||||
|
client.get('session_id')
|
||||||
))
|
))
|
||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
@@ -690,6 +713,19 @@ class OpenVPNDataGatherer:
|
|||||||
|
|
||||||
return active_clients
|
return active_clients
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def merge_sessions_by_cn(sessions):
|
||||||
|
"""Сворачивает список сессий в список по CN: одна запись на пользователя за тик (сумма приростов)."""
|
||||||
|
merged = {}
|
||||||
|
for s in sessions:
|
||||||
|
m = merged.setdefault(s['common_name'], {
|
||||||
|
'common_name': s['common_name'], 'db_id': s.get('db_id'),
|
||||||
|
'bytes_received_inc': 0, 'bytes_sent_inc': 0
|
||||||
|
})
|
||||||
|
m['bytes_received_inc'] += s.get('bytes_received_inc', 0)
|
||||||
|
m['bytes_sent_inc'] += s.get('bytes_sent_inc', 0)
|
||||||
|
return list(merged.values())
|
||||||
|
|
||||||
def calculate_rates(self, clients, time_diff):
|
def calculate_rates(self, clients, time_diff):
|
||||||
"""Расчет скорости в Mbps"""
|
"""Расчет скорости в Mbps"""
|
||||||
if time_diff <= 0:
|
if time_diff <= 0:
|
||||||
@@ -745,9 +781,15 @@ class OpenVPNDataGatherer:
|
|||||||
# Рваное чтение / нет файла: тик пропускаем целиком, БД и кэш не трогаем.
|
# Рваное чтение / нет файла: тик пропускаем целиком, БД и кэш не трогаем.
|
||||||
# last_check_time тоже не меняем: скорость следующего тика считается за весь интервал
|
# last_check_time тоже не меняем: скорость следующего тика считается за весь интервал
|
||||||
self.invalid_ticks += 1
|
self.invalid_ticks += 1
|
||||||
level = logging.ERROR if self.invalid_ticks >= self.invalid_max else logging.WARNING
|
# В журнал: 1-й тик, порог status_invalid_max (ERROR), далее раз в 60 тиков.
|
||||||
self.logger.log(level, f"Skipping tick ({self.invalid_ticks} in a row): {reading.reason}")
|
# Иначе на свежей установке без запущенного 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:
|
else:
|
||||||
|
if self.invalid_ticks:
|
||||||
|
self.logger.info(f"Status file is readable again after {self.invalid_ticks} skipped ticks")
|
||||||
self.invalid_ticks = 0
|
self.invalid_ticks = 0
|
||||||
if reading.stale:
|
if reading.stale:
|
||||||
self.logger.warning(reading.reason)
|
self.logger.warning(reading.reason)
|
||||||
@@ -761,8 +803,9 @@ class OpenVPNDataGatherer:
|
|||||||
if self.last_check_time:
|
if self.last_check_time:
|
||||||
time_diff = (current_time - self.last_check_time).total_seconds()
|
time_diff = (current_time - self.last_check_time).total_seconds()
|
||||||
|
|
||||||
# 4. Считаем скорости
|
# 4. Сворачиваем сессии в записи по CN и считаем скорости (сумма по сессиям)
|
||||||
clients_rated = self.calculate_rates(clients_with_updates, time_diff)
|
clients_rated = self.calculate_rates(
|
||||||
|
self.merge_sessions_by_cn(clients_with_updates), time_diff)
|
||||||
|
|
||||||
# 5. Сохраняем RAW историю (для графиков реального времени)
|
# 5. Сохраняем RAW историю (для графиков реального времени)
|
||||||
self.store_usage_history(clients_rated)
|
self.store_usage_history(clients_rated)
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
Flask>=3.0.0
|
Flask>=3.0.0,<4
|
||||||
Flask-Cors>=4.0.0
|
Flask-Cors>=4.0.0,<7
|
||||||
PyJWT>=2.10.0
|
PyJWT>=2.10.0,<3
|
||||||
pyotp>=2.9.0
|
pyotp>=2.9.0,<3
|
||||||
qrcode>=7.4.2
|
qrcode>=7.4.2,<9
|
||||||
bcrypt>=4.2.0
|
bcrypt>=4.2.0,<6
|
||||||
|
|
||||||
@@ -0,0 +1,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)
|
||||||
@@ -3,6 +3,7 @@ import logging
|
|||||||
import signal
|
import signal
|
||||||
import sqlite3
|
import sqlite3
|
||||||
import time
|
import time
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
@@ -17,11 +18,11 @@ HEADER = ("HEADER,CLIENT_LIST,Common Name,Real Address,Virtual Address,Virtual I
|
|||||||
|
|
||||||
|
|
||||||
def write_status(path, now, clients, complete=True):
|
def write_status(path, now, clients, complete=True):
|
||||||
"""Synthetic OpenVPN status file v2. clients: (cn, real_address, rx, tx, connected_since_ts)."""
|
"""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]
|
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 in clients:
|
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},"
|
lines.append(f"CLIENT_LIST,{cn},{real},10.8.0.2,,{rx},{tx},Mon Jan 1 00:00:00 2027,{since},"
|
||||||
f"UNDEF,1,0,AES-256-GCM")
|
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)",
|
lines += ["HEADER,ROUTING_TABLE,Virtual Address,Common Name,Real Address,Last Ref,Last Ref (time_t)",
|
||||||
"GLOBAL_STATS,Max bcast/mcast queue length,0"]
|
"GLOBAL_STATS,Max bcast/mcast queue length,0"]
|
||||||
if complete:
|
if complete:
|
||||||
@@ -167,6 +168,24 @@ def test_torn_read_skips_the_tick(env):
|
|||||||
assert env.history_sum() == (3000, 2)
|
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):
|
def test_session_missing_for_a_tick_and_beyond_grace(env):
|
||||||
g = env.gatherer()
|
g = env.gatherer()
|
||||||
since = T0 + 5
|
since = T0 + 5
|
||||||
@@ -196,6 +215,47 @@ def test_session_missing_for_a_tick_and_beyond_grace(env):
|
|||||||
assert len(g.session_cache) == 1
|
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):
|
def test_loop_survives_exceptions_and_stops_on_signal(env):
|
||||||
g = env.gatherer()
|
g = env.gatherer()
|
||||||
g.stop_event = FakeEvent()
|
g.stop_event = FakeEvent()
|
||||||
|
|||||||
@@ -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
|
# Missing tables and columns are there, existing rows get the defaults
|
||||||
assert {"active_sessions", "users", "login_attempts"} <= table_names(db)
|
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 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
|
# 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-*")
|
backups = glob.glob(db + ".bak-*")
|
||||||
assert backups == [report.backup]
|
assert backups == [report.backup]
|
||||||
assert [query(backups[0], q) for q in DATA_QUERIES] == before
|
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 glob.glob(db + ".bak-*") == []
|
||||||
assert {"clients", "usage_history", "active_sessions", "users", "login_attempts",
|
assert {"clients", "usage_history", "active_sessions", "users", "login_attempts",
|
||||||
"stats_5min", "stats_daily", "schema_migrations"} <= table_names(db)
|
"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):
|
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 errors == []
|
||||||
assert len(glob.glob(db + ".bak-*")) == 1
|
assert len(glob.glob(db + ".bak-*")) == 1
|
||||||
assert sorted(len(r.applied) for r in reports) == [0, 1]
|
assert sorted(len(r.applied) for r in reports) == [0, len(migrations.MIGRATIONS)]
|
||||||
assert query(db, "SELECT version FROM schema_migrations") == [(1,)]
|
assert query(db, "SELECT version FROM schema_migrations") == [(1,), (2,)]
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import importlib
|
||||||
|
import sqlite3
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
FMT_SINCE = '2026-11-12 10:00:00'
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def api(tmp_path, monkeypatch):
|
||||||
|
monkeypatch.chdir(tmp_path)
|
||||||
|
monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_DB_PATH", str(tmp_path / "api.db"))
|
||||||
|
monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False)
|
||||||
|
module = importlib.import_module("openvpn_api_v3")
|
||||||
|
return module.OpenVPNAPI()
|
||||||
|
|
||||||
|
|
||||||
|
def test_stats_include_sessions(api):
|
||||||
|
conn = sqlite3.connect(api.db_manager.db_path)
|
||||||
|
for cn, status in (('alice', 'Active'), ('bob', 'Active'), ('carol', 'Disconnected')):
|
||||||
|
conn.execute("INSERT INTO clients (common_name, status, real_address) VALUES (?,?,?)",
|
||||||
|
(cn, status, '1.1.1.1:1000'))
|
||||||
|
ids = {cn: i for i, cn in conn.execute("SELECT id, common_name FROM clients")}
|
||||||
|
mb = 1024 * 1024
|
||||||
|
for cn, addr, rx, tx in (('alice', '1.1.1.1:1000', 2 * mb, mb), ('alice', '2.2.2.2:2000', 0, 0),
|
||||||
|
('bob', '3.3.3.3:3000', mb, mb)):
|
||||||
|
conn.execute("INSERT INTO active_sessions (client_id, common_name, real_address, bytes_received,"
|
||||||
|
" bytes_sent, connected_since, last_seen, session_id) VALUES (?,?,?,?,?,?,?,?)",
|
||||||
|
(ids[cn], cn, addr, rx, tx, FMT_SINCE, FMT_SINCE, None))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
by_cn = {c['common_name']: c for c in api.get_current_stats()}
|
||||||
|
assert by_cn['alice']['sessions_count'] == 2
|
||||||
|
assert {s['real_address'] for s in by_cn['alice']['sessions']} == {'1.1.1.1:1000', '2.2.2.2:2000'}
|
||||||
|
first = next(s for s in by_cn['alice']['sessions'] if s['real_address'] == '1.1.1.1:1000')
|
||||||
|
assert (first['received_mb'], first['sent_mb'], first['connected_since']) == (2.0, 1.0, FMT_SINCE)
|
||||||
|
assert by_cn['bob']['sessions_count'] == 1
|
||||||
|
assert by_cn['carol']['sessions_count'] == 0 and by_cn['carol']['sessions'] == []
|
||||||
|
# existing fields are unchanged
|
||||||
|
assert by_cn['alice']['real_address'] == '1.1.1.1:1000' and by_cn['alice']['status'] == 'Active'
|
||||||
@@ -11,7 +11,12 @@ COPY requirements.txt .
|
|||||||
RUN pip install --no-cache-dir -r requirements.txt
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
# Ensure DB directory exists
|
# Ensure DB directory exists
|
||||||
RUN mkdir -p /app/db
|
RUN mkdir -p /app/db /app/backups
|
||||||
|
|
||||||
|
# Migrations of the monitoring database (standard library only), from the build context 'core'
|
||||||
|
# (additional_contexts in docker-compose.yml). A restore migrates the package copy with them.
|
||||||
|
COPY --from=core migrations.py migrate.py db.py /opt/core/
|
||||||
|
ENV OVPMON_CORE_DIR=/opt/core
|
||||||
|
|
||||||
# Copy source code and entrypoint
|
# Copy source code and entrypoint
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|||||||
+11
-1
@@ -1,5 +1,6 @@
|
|||||||
import uvicorn
|
import uvicorn
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
import logging
|
||||||
import sys
|
import sys
|
||||||
import os
|
import os
|
||||||
|
|
||||||
@@ -9,7 +10,7 @@ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
|||||||
|
|
||||||
from database import db_path
|
from database import db_path
|
||||||
import migrations
|
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 utils.logging import setup_logging
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
@@ -20,6 +21,14 @@ setup_logging()
|
|||||||
# pending while OVPMON_AUTO_MIGRATE=0.
|
# pending while OVPMON_AUTO_MIGRATE=0.
|
||||||
migrations.startup_or_exit(db_path)
|
migrations.startup_or_exit(db_path)
|
||||||
|
|
||||||
|
# Settings, destinations and history of backup and restore (own SQLite file, see services/backup/store.py).
|
||||||
|
# A failure here must not stop the VPN management: the backup routes then report the error.
|
||||||
|
try:
|
||||||
|
from services.backup import store as backup_store
|
||||||
|
backup_store.init()
|
||||||
|
except Exception:
|
||||||
|
logging.getLogger(__name__).exception("Backup store is not available")
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="OpenVPN Profiler API",
|
title="OpenVPN Profiler API",
|
||||||
description="REST API for managing OpenVPN profiles and configuration",
|
description="REST API for managing OpenVPN profiles and configuration",
|
||||||
@@ -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(server.router, prefix="/api", tags=["Server"])
|
||||||
app.include_router(profiles.router, prefix="/api", tags=["Profiles"])
|
app.include_router(profiles.router, prefix="/api", tags=["Profiles"])
|
||||||
app.include_router(server_process.router, prefix="/api", tags=["Process Control"])
|
app.include_router(server_process.router, prefix="/api", tags=["Process Control"])
|
||||||
|
app.include_router(backup.router, prefix="/api", tags=["Backup"])
|
||||||
|
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
def read_root():
|
def read_root():
|
||||||
|
|||||||
@@ -37,6 +37,9 @@ def main(argv=None):
|
|||||||
if st.too_new:
|
if st.too_new:
|
||||||
raise migrations._too_new_error(st)
|
raise migrations._too_new_error(st)
|
||||||
print(f"Database: {db_path}" + ("" if st.exists else " (does not exist yet)"))
|
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:
|
if args.check:
|
||||||
print(f"Schema version: {st.current} (latest known: {migrations.latest_version()})")
|
print(f"Schema version: {st.current} (latest known: {migrations.latest_version()})")
|
||||||
if not st.pending:
|
if not st.pending:
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
fastapi
|
fastapi==0.143.3
|
||||||
uvicorn
|
starlette==1.8.0
|
||||||
|
uvicorn==0.54.0
|
||||||
|
pydantic==2.14.1
|
||||||
sqlalchemy
|
sqlalchemy
|
||||||
psutil
|
psutil
|
||||||
python-multipart
|
python-multipart
|
||||||
jinja2
|
jinja2
|
||||||
pyjwt
|
pyjwt
|
||||||
requests
|
requests
|
||||||
|
cryptography
|
||||||
|
minio
|
||||||
|
paramiko
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
import re
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from utils.auth import verify_token
|
||||||
|
from services.backup import BackupError, Busy, Invalid, destinations, engine, package, store
|
||||||
|
|
||||||
|
router = APIRouter(dependencies=[Depends(verify_token)])
|
||||||
|
|
||||||
|
NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9 _.-]{0,63}$")
|
||||||
|
PASSPHRASE_MIN = 8
|
||||||
|
|
||||||
|
|
||||||
|
class SettingsUpdate(BaseModel):
|
||||||
|
passphrase: Optional[str] = Field(None, max_length=256) # set or change; never returned
|
||||||
|
clear_passphrase: bool = False
|
||||||
|
default_retention: Optional[int] = Field(None, ge=1, le=1000)
|
||||||
|
server_name: Optional[str] = Field(None, max_length=63) # '' clears it (fallback names are used)
|
||||||
|
|
||||||
|
|
||||||
|
class DestinationIn(BaseModel):
|
||||||
|
name: str = Field(..., max_length=64)
|
||||||
|
type: str = Field(..., max_length=20)
|
||||||
|
enabled: bool = True
|
||||||
|
retention_count: Optional[int] = Field(None, ge=1, le=1000)
|
||||||
|
params: dict = {}
|
||||||
|
secrets: dict = {} # absent, empty or masked values keep the stored secret
|
||||||
|
|
||||||
|
|
||||||
|
class TrustIn(BaseModel):
|
||||||
|
fingerprint: str = Field(..., max_length=80) # the one shown by Test
|
||||||
|
|
||||||
|
|
||||||
|
class RunIn(BaseModel):
|
||||||
|
destination_ids: Optional[list[int]] = None
|
||||||
|
|
||||||
|
|
||||||
|
class RestoreIn(BaseModel):
|
||||||
|
destination_id: int
|
||||||
|
package: str = Field(..., max_length=200)
|
||||||
|
passphrase: Optional[str] = Field(None, max_length=256)
|
||||||
|
|
||||||
|
|
||||||
|
def _fail(e: Exception):
|
||||||
|
"""BackupError family -> HTTP error. Messages never contain secrets."""
|
||||||
|
if isinstance(e, Busy):
|
||||||
|
raise HTTPException(status_code=409, detail=str(e))
|
||||||
|
if isinstance(e, destinations.DestinationError):
|
||||||
|
raise HTTPException(status_code=502, detail=str(e))
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
|
def _types_info():
|
||||||
|
return [{"id": t, "label": cls.label, "remote": t in destinations.REMOTE_TYPES, "fields": cls.FIELDS,
|
||||||
|
"pins_host_key": bool(cls.PIN_PARAMS)}
|
||||||
|
for t, cls in destinations.DESTINATION_TYPES.items()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/backup/settings")
|
||||||
|
def get_settings():
|
||||||
|
effective, source = engine.effective_server_name()
|
||||||
|
return {
|
||||||
|
"encryption_enabled": store.has_passphrase(),
|
||||||
|
"default_retention": store.default_retention(),
|
||||||
|
"server_name": store.get_server_name(),
|
||||||
|
"effective_server_name": effective,
|
||||||
|
"server_name_source": source,
|
||||||
|
"local_root": destinations.local_root(),
|
||||||
|
"types": _types_info(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/backup/settings")
|
||||||
|
def update_settings(body: SettingsUpdate):
|
||||||
|
if engine.is_running():
|
||||||
|
raise HTTPException(status_code=409, detail="A backup or restore is running")
|
||||||
|
if body.passphrase is not None and body.clear_passphrase:
|
||||||
|
raise HTTPException(status_code=400, detail="Give a passphrase or clear it, not both")
|
||||||
|
server_name = (body.server_name or "").strip()
|
||||||
|
if server_name and not package.SERVER_NAME_RE.match(server_name):
|
||||||
|
raise HTTPException(status_code=400, detail="Server name: 1-63 letters, digits, '.' or '-', "
|
||||||
|
"starting with a letter or digit")
|
||||||
|
if body.passphrase is not None:
|
||||||
|
if len(body.passphrase) < PASSPHRASE_MIN:
|
||||||
|
raise HTTPException(status_code=400, detail=f"Passphrase must have at least {PASSPHRASE_MIN} characters")
|
||||||
|
store.set_passphrase(body.passphrase)
|
||||||
|
if body.clear_passphrase:
|
||||||
|
remote = [d["name"] for d in store.list_destinations()
|
||||||
|
if d["enabled"] and d["type"] in destinations.REMOTE_TYPES]
|
||||||
|
if remote:
|
||||||
|
raise HTTPException(status_code=400, detail="Remote destinations need a passphrase: disable or "
|
||||||
|
f"delete them first ({', '.join(remote)})")
|
||||||
|
store.set_passphrase(None)
|
||||||
|
if body.default_retention is not None:
|
||||||
|
store.set_default_retention(body.default_retention)
|
||||||
|
if body.server_name is not None:
|
||||||
|
store.set_server_name(server_name)
|
||||||
|
return get_settings()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/backup/destinations")
|
||||||
|
def list_destinations():
|
||||||
|
return store.list_destinations()
|
||||||
|
|
||||||
|
|
||||||
|
def _prepare(body: DestinationIn, previous: Optional[dict]):
|
||||||
|
cls = destinations.DESTINATION_TYPES.get(body.type)
|
||||||
|
if cls is None:
|
||||||
|
raise HTTPException(status_code=400, detail=f"Unsupported destination type: {body.type}")
|
||||||
|
name = body.name.strip()
|
||||||
|
if not NAME_RE.match(name):
|
||||||
|
raise HTTPException(status_code=400, detail="Name: 1-64 letters, digits, spaces, '.', '_' or '-'")
|
||||||
|
same_type = bool(previous and previous["type"] == body.type)
|
||||||
|
# Secrets of another type never carry over
|
||||||
|
keep = previous["secrets"] if same_type else {}
|
||||||
|
given = {k: v for k, v in body.secrets.items() if isinstance(v, str) and v and v != store.MASK}
|
||||||
|
# A pinned host key comes only from the trust call, never from the client
|
||||||
|
client_params = {k: v for k, v in body.params.items() if k not in cls.PIN_PARAMS}
|
||||||
|
try:
|
||||||
|
params, secrets = cls.validate(client_params, given, keep)
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
if same_type and cls.PIN_PARAMS:
|
||||||
|
old = previous["params"]
|
||||||
|
if all(old.get(k) == params.get(k) for k in cls.PIN_DEPENDS): # same server: the pin stays
|
||||||
|
params.update({k: old[k] for k in cls.PIN_PARAMS if old.get(k)})
|
||||||
|
retention = body.retention_count or (previous["retention_count"] if previous else store.default_retention())
|
||||||
|
return name, params, secrets, retention
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/backup/destinations", status_code=201)
|
||||||
|
def create_destination(body: DestinationIn):
|
||||||
|
name, params, secrets, retention = _prepare(body, None)
|
||||||
|
try:
|
||||||
|
dest_id = store.save_destination(None, name, body.type, body.enabled, retention, params, secrets)
|
||||||
|
except BackupError as e:
|
||||||
|
raise HTTPException(status_code=409, detail=str(e))
|
||||||
|
return store.get_destination(dest_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/backup/destinations/{dest_id}")
|
||||||
|
def update_destination(dest_id: int, body: DestinationIn):
|
||||||
|
if engine.is_running():
|
||||||
|
raise HTTPException(status_code=409, detail="A backup or restore is running")
|
||||||
|
previous = store.get_destination(dest_id, with_secrets=True)
|
||||||
|
if not previous:
|
||||||
|
raise HTTPException(status_code=404, detail="Destination not found")
|
||||||
|
name, params, secrets, retention = _prepare(body, previous)
|
||||||
|
try:
|
||||||
|
store.save_destination(dest_id, name, body.type, body.enabled, retention, params, secrets)
|
||||||
|
except BackupError as e:
|
||||||
|
raise HTTPException(status_code=409, detail=str(e))
|
||||||
|
return store.get_destination(dest_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/backup/destinations/{dest_id}")
|
||||||
|
def delete_destination(dest_id: int):
|
||||||
|
if engine.is_running():
|
||||||
|
raise HTTPException(status_code=409, detail="A backup or restore is running")
|
||||||
|
if not store.delete_destination(dest_id):
|
||||||
|
raise HTTPException(status_code=404, detail="Destination not found")
|
||||||
|
return {"message": "Destination deleted"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/backup/destinations/{dest_id}/test")
|
||||||
|
def test_destination(dest_id: int):
|
||||||
|
try:
|
||||||
|
return engine.test_destination(dest_id)
|
||||||
|
except BackupError as e:
|
||||||
|
_fail(e)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/backup/destinations/{dest_id}/trust-host-key")
|
||||||
|
def trust_host_key(dest_id: int, body: TrustIn):
|
||||||
|
if engine.is_running():
|
||||||
|
raise HTTPException(status_code=409, detail="A backup or restore is running")
|
||||||
|
try:
|
||||||
|
return engine.trust_host_key(dest_id, body.fingerprint.strip())
|
||||||
|
except BackupError as e:
|
||||||
|
_fail(e)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/backup/destinations/{dest_id}/packages")
|
||||||
|
def list_packages(dest_id: int):
|
||||||
|
try:
|
||||||
|
return {"packages": engine.list_packages(dest_id)}
|
||||||
|
except BackupError as e:
|
||||||
|
_fail(e)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/backup/run", status_code=202)
|
||||||
|
def run_backup(body: RunIn = RunIn()):
|
||||||
|
try:
|
||||||
|
engine.start_backup(body.destination_ids)
|
||||||
|
except BackupError as e:
|
||||||
|
_fail(e)
|
||||||
|
return {"state": "running"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/backup/restore", status_code=202)
|
||||||
|
def run_restore(body: RestoreIn):
|
||||||
|
try:
|
||||||
|
engine.start_restore(body.destination_id, body.package, body.passphrase)
|
||||||
|
except BackupError as e:
|
||||||
|
_fail(e)
|
||||||
|
return {"state": "running"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/backup/status")
|
||||||
|
def get_status():
|
||||||
|
return engine.status()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/backup/history")
|
||||||
|
def get_history(limit: int = Query(20, ge=1, le=100)):
|
||||||
|
return store.history_list(limit)
|
||||||
@@ -4,6 +4,7 @@ from fastapi.responses import FileResponse
|
|||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from database import get_db
|
from database import get_db
|
||||||
from utils.auth import verify_token
|
from utils.auth import verify_token
|
||||||
|
from utils.guards import forbid_during_restore
|
||||||
from models import UserProfile
|
from models import UserProfile
|
||||||
from schemas import UserProfile as UserProfileSchema, UserProfileCreate, UserProfileNoteUpdate
|
from schemas import UserProfile as UserProfileSchema, UserProfileCreate, UserProfileNoteUpdate
|
||||||
from services import pki, generator
|
from services import pki, generator
|
||||||
@@ -69,7 +70,7 @@ def list_profiles(db: Session = Depends(get_db)):
|
|||||||
|
|
||||||
return updated_profiles
|
return updated_profiles
|
||||||
|
|
||||||
@router.post("/profiles", response_model=UserProfileSchema)
|
@router.post("/profiles", response_model=UserProfileSchema, dependencies=[Depends(forbid_during_restore)])
|
||||||
def create_profile(
|
def create_profile(
|
||||||
profile_in: UserProfileCreate,
|
profile_in: UserProfileCreate,
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
@@ -123,7 +124,7 @@ def create_profile(
|
|||||||
db.refresh(new_profile)
|
db.refresh(new_profile)
|
||||||
return 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)):
|
def update_profile_note(profile_id: int, body: UserProfileNoteUpdate, db: Session = Depends(get_db)):
|
||||||
profile = db.query(UserProfile).filter(UserProfile.id == profile_id).first()
|
profile = db.query(UserProfile).filter(UserProfile.id == profile_id).first()
|
||||||
if not profile:
|
if not profile:
|
||||||
@@ -134,7 +135,7 @@ def update_profile_note(profile_id: int, body: UserProfileNoteUpdate, db: Sessio
|
|||||||
db.refresh(profile)
|
db.refresh(profile)
|
||||||
return 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)):
|
def revoke_profile(profile_id: int, db: Session = Depends(get_db)):
|
||||||
profile = db.query(UserProfile).filter(UserProfile.id == profile_id).first()
|
profile = db.query(UserProfile).filter(UserProfile.id == profile_id).first()
|
||||||
if not profile:
|
if not profile:
|
||||||
|
|||||||
@@ -4,13 +4,14 @@ from fastapi import APIRouter, Depends, HTTPException
|
|||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from database import get_db
|
from database import get_db
|
||||||
from utils.auth import verify_token
|
from utils.auth import verify_token
|
||||||
|
from utils.guards import forbid_during_restore
|
||||||
from services import generator, process, config, pki
|
from services import generator, process, config, pki
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
router = APIRouter(dependencies=[Depends(verify_token)])
|
router = APIRouter(dependencies=[Depends(verify_token)])
|
||||||
|
|
||||||
@router.post("/server/configure")
|
@router.post("/server/configure", dependencies=[Depends(forbid_during_restore)])
|
||||||
def configure_server(db: Session = Depends(get_db)):
|
def configure_server(db: Session = Depends(get_db)):
|
||||||
try:
|
try:
|
||||||
pki.require_server_ready(db)
|
pki.require_server_ready(db)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ from services import process, pki
|
|||||||
from database import get_db
|
from database import get_db
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from utils.auth import verify_token
|
from utils.auth import verify_token
|
||||||
|
from utils.guards import forbid_during_restore
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from fastapi import Depends
|
from fastapi import Depends
|
||||||
|
|
||||||
@@ -22,7 +23,7 @@ class ProcessStats(BaseModel):
|
|||||||
memory_mb: float
|
memory_mb: float
|
||||||
uptime: Optional[str] = None
|
uptime: Optional[str] = None
|
||||||
|
|
||||||
@router.post("/server/process/{action}", response_model=ProcessActionResponse)
|
@router.post("/server/process/{action}", response_model=ProcessActionResponse, dependencies=[Depends(forbid_during_restore)])
|
||||||
def manage_process(action: str, db: Session = Depends(get_db)):
|
def manage_process(action: str, db: Session = Depends(get_db)):
|
||||||
"""
|
"""
|
||||||
Control the OpenVPN server process.
|
Control the OpenVPN server process.
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
|
from typing import Literal, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from database import get_db
|
from database import get_db
|
||||||
from utils.auth import verify_token
|
from utils.auth import verify_token
|
||||||
|
from utils.guards import forbid_during_restore
|
||||||
from schemas import (
|
from schemas import (
|
||||||
ConfigResponse, SystemSettings, PKISetting,
|
ConfigResponse, SystemSettings, PKISetting,
|
||||||
SystemSettingsUpdate, PKISettingUpdate
|
SystemSettingsUpdate, PKISettingUpdate
|
||||||
@@ -12,7 +15,7 @@ router = APIRouter(dependencies=[Depends(verify_token)])
|
|||||||
|
|
||||||
@router.get("/config", response_model=ConfigResponse)
|
@router.get("/config", response_model=ConfigResponse)
|
||||||
def get_config(
|
def get_config(
|
||||||
section: str = Query(None, enum=["server", "pki"]),
|
section: Optional[Literal["server", "pki"]] = Query(None),
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
):
|
):
|
||||||
response = ConfigResponse()
|
response = ConfigResponse()
|
||||||
@@ -22,14 +25,14 @@ def get_config(
|
|||||||
response.pki = config.get_pki_settings(db)
|
response.pki = config.get_pki_settings(db)
|
||||||
return response
|
return response
|
||||||
|
|
||||||
@router.put("/config/server", response_model=SystemSettings)
|
@router.put("/config/server", response_model=SystemSettings, dependencies=[Depends(forbid_during_restore)])
|
||||||
def update_server_config(
|
def update_server_config(
|
||||||
settings: SystemSettingsUpdate,
|
settings: SystemSettingsUpdate,
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
):
|
):
|
||||||
return config.update_system_settings(db, settings)
|
return config.update_system_settings(db, settings)
|
||||||
|
|
||||||
@router.put("/config/pki", response_model=PKISetting)
|
@router.put("/config/pki", response_model=PKISetting, dependencies=[Depends(forbid_during_restore)])
|
||||||
def update_pki_config(
|
def update_pki_config(
|
||||||
settings: PKISettingUpdate,
|
settings: PKISettingUpdate,
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
@@ -48,7 +51,7 @@ def init_system_pki(db: Session = Depends(get_db)):
|
|||||||
def get_init_status(db: Session = Depends(get_db)):
|
def get_init_status(db: Session = Depends(get_db)):
|
||||||
return pki.init_status(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)):
|
def clear_system_pki(db: Session = Depends(get_db)):
|
||||||
if pki.is_init_running():
|
if pki.is_init_running():
|
||||||
raise HTTPException(status_code=409, detail="PKI initialization is running")
|
raise HTTPException(status_code=409, detail="PKI initialization is running")
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
"""Backup and restore of the application data (databases, PKI, client profiles).
|
||||||
|
|
||||||
|
Modules:
|
||||||
|
package.py package format (tar.gz + manifest), snapshots, safe extraction
|
||||||
|
crypto.py optional package encryption (AES-256-GCM, scrypt)
|
||||||
|
destinations.py where packages go: common interface, local folder and S3 (minio)
|
||||||
|
store.py settings, destinations and history in a separate SQLite file
|
||||||
|
engine.py backup job and restore engine (one background job at a time)
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class BackupError(Exception):
|
||||||
|
"""A backup or restore step failed. The message is safe to show to the user (no secrets)."""
|
||||||
|
|
||||||
|
|
||||||
|
class Invalid(BackupError):
|
||||||
|
"""The request cannot be accepted as it is (API: 400)."""
|
||||||
|
|
||||||
|
|
||||||
|
class Busy(BackupError):
|
||||||
|
"""Another backup or restore job is running (API: 409)."""
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
"""Package encryption: AES-256-GCM in chunks, key from the passphrase with scrypt.
|
||||||
|
|
||||||
|
File layout:
|
||||||
|
magic "OVPBAKE1" | log2(N) 1 byte | r 1 byte | p 1 byte | salt 16 | nonce prefix 8 (header, 35 bytes)
|
||||||
|
then chunks of CHUNK bytes of plaintext, each stored as ciphertext + 16 byte tag.
|
||||||
|
Chunk i uses the nonce prefix || i (4 bytes, big endian). The header and a "final chunk" flag
|
||||||
|
are authenticated data of every chunk, so a truncated, reordered or modified file is rejected.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import struct
|
||||||
|
|
||||||
|
from cryptography.exceptions import InvalidTag
|
||||||
|
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||||
|
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
|
||||||
|
|
||||||
|
from . import BackupError
|
||||||
|
|
||||||
|
MAGIC = b"OVPBAKE1"
|
||||||
|
HEADER_LEN = len(MAGIC) + 3 + 16 + 8
|
||||||
|
CHUNK = 1024 * 1024
|
||||||
|
TAG = 16
|
||||||
|
SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P = 15, 8, 1 # about 32 MiB of memory
|
||||||
|
# Bounds for the parameters read from a file: a crafted header must not exhaust memory or CPU
|
||||||
|
MAX_LOG_N, MAX_R, MAX_P = 20, 16, 4
|
||||||
|
|
||||||
|
|
||||||
|
class WrongPassphrase(BackupError):
|
||||||
|
"""Wrong passphrase, or the file is damaged (AES-GCM cannot tell the two apart)."""
|
||||||
|
|
||||||
|
|
||||||
|
def is_encrypted(path: str) -> bool:
|
||||||
|
try:
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
return f.read(len(MAGIC)) == MAGIC
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _derive(passphrase: str, salt: bytes, log_n: int, r: int, p: int) -> bytes:
|
||||||
|
return Scrypt(salt=salt, length=32, n=2 ** log_n, r=r, p=p).derive(passphrase.encode("utf-8"))
|
||||||
|
|
||||||
|
|
||||||
|
def _nonce(prefix: bytes, index: int) -> bytes:
|
||||||
|
return prefix + struct.pack(">I", index)
|
||||||
|
|
||||||
|
|
||||||
|
def _aad(header: bytes, final: bool) -> bytes:
|
||||||
|
return header + (b"\x01" if final else b"\x00")
|
||||||
|
|
||||||
|
|
||||||
|
def encrypt_file(src: str, dst: str, passphrase: str) -> None:
|
||||||
|
if not passphrase:
|
||||||
|
raise BackupError("Passphrase is empty")
|
||||||
|
salt, prefix = os.urandom(16), os.urandom(8)
|
||||||
|
header = MAGIC + bytes([SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P]) + salt + prefix
|
||||||
|
aes = AESGCM(_derive(passphrase, salt, SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P))
|
||||||
|
fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with open(src, "rb") as fin, os.fdopen(fd, "wb") as fout:
|
||||||
|
fout.write(header)
|
||||||
|
index = 0
|
||||||
|
block = fin.read(CHUNK)
|
||||||
|
while True:
|
||||||
|
nxt = fin.read(CHUNK)
|
||||||
|
final = not nxt
|
||||||
|
fout.write(aes.encrypt(_nonce(prefix, index), block, _aad(header, final)))
|
||||||
|
if final:
|
||||||
|
break
|
||||||
|
block, index = nxt, index + 1
|
||||||
|
|
||||||
|
|
||||||
|
def decrypt_file(src: str, dst: str, passphrase: str) -> None:
|
||||||
|
if not passphrase:
|
||||||
|
raise WrongPassphrase("Passphrase is required for an encrypted package")
|
||||||
|
with open(src, "rb") as fin:
|
||||||
|
header = fin.read(HEADER_LEN)
|
||||||
|
if len(header) != HEADER_LEN or not header.startswith(MAGIC):
|
||||||
|
raise BackupError("Not an encrypted package (bad header)")
|
||||||
|
log_n, r, p = header[8], header[9], header[10]
|
||||||
|
if not (1 <= log_n <= MAX_LOG_N and 1 <= r <= MAX_R and 1 <= p <= MAX_P):
|
||||||
|
raise BackupError("Encrypted package has unsupported key derivation parameters")
|
||||||
|
salt, prefix = header[11:27], header[27:35]
|
||||||
|
aes = AESGCM(_derive(passphrase, salt, log_n, r, p))
|
||||||
|
fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as fout:
|
||||||
|
index = 0
|
||||||
|
block = fin.read(CHUNK + TAG)
|
||||||
|
if not block:
|
||||||
|
raise BackupError("Encrypted package is truncated")
|
||||||
|
while True:
|
||||||
|
nxt = fin.read(CHUNK + TAG)
|
||||||
|
final = not nxt
|
||||||
|
try:
|
||||||
|
fout.write(aes.decrypt(_nonce(prefix, index), block, _aad(header, final)))
|
||||||
|
except InvalidTag:
|
||||||
|
raise WrongPassphrase("Wrong passphrase, or the package is damaged") from None
|
||||||
|
if final:
|
||||||
|
break
|
||||||
|
block, index = nxt, index + 1
|
||||||
@@ -0,0 +1,876 @@
|
|||||||
|
"""Backup destinations. Every type implements the same interface:
|
||||||
|
|
||||||
|
test() check the connection and the right to write and delete; returns a message
|
||||||
|
put(local_path, name) store a file under name
|
||||||
|
list() [{"name", "size", "mtime"}] of the files in the destination folder
|
||||||
|
get(name, local_path) download to a local file
|
||||||
|
delete(name) remove a file
|
||||||
|
|
||||||
|
Implemented: "local", "s3", "sftp" and "ftp". To add a type (smb): write a Destination subclass
|
||||||
|
with FIELDS, validate() and the five methods, and add it to DESTINATION_TYPES. The API accepts
|
||||||
|
exactly the types of that registry.
|
||||||
|
"""
|
||||||
|
import hmac
|
||||||
|
import hashlib
|
||||||
|
import base64
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
|
import stat
|
||||||
|
import uuid
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from . import BackupError
|
||||||
|
from .package import PACKAGE_RE
|
||||||
|
|
||||||
|
DEFAULT_LOCAL_ROOT = "/var/lib/ovpmon/backups"
|
||||||
|
SAFE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
|
||||||
|
FOLDER_SEGMENT_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
|
||||||
|
HOST_RE = re.compile(r"^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$")
|
||||||
|
BUCKET_RE = re.compile(r"^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$")
|
||||||
|
REGION_RE = re.compile(r"^[A-Za-z0-9-]{1,40}$")
|
||||||
|
|
||||||
|
|
||||||
|
class DestinationError(BackupError):
|
||||||
|
"""The destination refused or could not be reached. The message never contains secrets."""
|
||||||
|
|
||||||
|
|
||||||
|
class NeedsTrust(DestinationError):
|
||||||
|
"""The SSH host key of the server is not pinned yet (or changed). Carries what the server showed."""
|
||||||
|
|
||||||
|
def __init__(self, message: str, fingerprint: str, key_type: str, changed: bool = False):
|
||||||
|
super().__init__(message)
|
||||||
|
self.fingerprint, self.key_type, self.changed = fingerprint, key_type, changed
|
||||||
|
|
||||||
|
|
||||||
|
def local_root() -> str:
|
||||||
|
return os.environ.get("OVPMON_BACKUP_LOCAL_ROOT", "").strip() or DEFAULT_LOCAL_ROOT
|
||||||
|
|
||||||
|
|
||||||
|
def _check_name(name: str) -> str:
|
||||||
|
if not isinstance(name, str) or not SAFE_NAME_RE.match(name) or ".." in name:
|
||||||
|
raise DestinationError("Invalid file name")
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
def _short(e: Exception) -> str:
|
||||||
|
return f"{type(e).__name__}: {str(e)[:300]}"
|
||||||
|
|
||||||
|
|
||||||
|
class Destination:
|
||||||
|
type = ""
|
||||||
|
label = ""
|
||||||
|
# Field description for the UI: name, label, kind (text|number|bool|secret|secret_multiline),
|
||||||
|
# required, default, hint; optional warning + warn_if (shown while the value equals warn_if)
|
||||||
|
FIELDS: list = []
|
||||||
|
# Parameters set by pinning a host key (never accepted from the client, kept while the parameters
|
||||||
|
# of PIN_DEPENDS stay the same); empty for types without pinning
|
||||||
|
PIN_PARAMS: tuple = ()
|
||||||
|
PIN_DEPENDS: tuple = ()
|
||||||
|
|
||||||
|
def __init__(self, params: dict, secrets: dict):
|
||||||
|
self.params = params
|
||||||
|
self.secrets = secrets
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def validate(cls, params: dict, secrets: dict, previous_secrets: Optional[dict] = None):
|
||||||
|
"""Return (clean_params, clean_secrets) or raise ValueError with a message for the user."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def test(self) -> str:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def put(self, local_path: str, name: str) -> None:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def list(self) -> list:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def get(self, name: str, local_path: str) -> None:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def delete(self, name: str) -> None:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def fetch_host_key(self):
|
||||||
|
"""(fingerprint, key type) the server shows now; no credentials are sent. Pinning types only."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
|
||||||
|
def _unknown_keys(given: dict, allowed: set, what: str):
|
||||||
|
extra = sorted(set(given) - allowed)
|
||||||
|
if extra:
|
||||||
|
raise ValueError(f"Unknown {what}: {', '.join(extra)}")
|
||||||
|
|
||||||
|
|
||||||
|
# --- local folder --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class LocalDestination(Destination):
|
||||||
|
"""A sub folder inside the root OVPMON_BACKUP_LOCAL_ROOT. Paths outside the root and
|
||||||
|
symbolic links are rejected."""
|
||||||
|
type = "local"
|
||||||
|
label = "Local folder"
|
||||||
|
FIELDS = [
|
||||||
|
{"name": "folder", "label": "Folder (inside the backup root)", "kind": "text", "required": True,
|
||||||
|
"default": "default", "hint": "Sub folder of the server's backup root, for example 'daily'"},
|
||||||
|
]
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def validate(cls, params, secrets, previous_secrets=None):
|
||||||
|
_unknown_keys(params, {"folder"}, "parameters")
|
||||||
|
if secrets:
|
||||||
|
raise ValueError("A local destination has no secrets")
|
||||||
|
folder = str(params.get("folder", "")).strip().strip("/")
|
||||||
|
if not folder:
|
||||||
|
raise ValueError("Folder is required")
|
||||||
|
parts = folder.split("/")
|
||||||
|
if len(parts) > 4 or not all(FOLDER_SEGMENT_RE.match(p) and ".." not in p for p in parts):
|
||||||
|
raise ValueError("Folder must be a relative path of letters, digits, '.', '_' and '-' "
|
||||||
|
"(no '..', no leading dot, at most 4 levels)")
|
||||||
|
return {"folder": "/".join(parts)}, {}
|
||||||
|
|
||||||
|
def _root(self) -> str:
|
||||||
|
root = local_root()
|
||||||
|
try:
|
||||||
|
os.makedirs(root, mode=0o700, exist_ok=True)
|
||||||
|
except OSError as e:
|
||||||
|
raise DestinationError(f"Backup root {root} is not usable: {e.strerror or e}") from e
|
||||||
|
return os.path.realpath(root)
|
||||||
|
|
||||||
|
def _dir(self, create: bool) -> str:
|
||||||
|
root = self._root()
|
||||||
|
current = root
|
||||||
|
for part in self.params["folder"].split("/"):
|
||||||
|
current = os.path.join(current, part)
|
||||||
|
try:
|
||||||
|
st = os.lstat(current)
|
||||||
|
except FileNotFoundError:
|
||||||
|
if not create:
|
||||||
|
raise DestinationError("Folder does not exist yet") from None
|
||||||
|
try:
|
||||||
|
os.mkdir(current, 0o700)
|
||||||
|
except OSError as e:
|
||||||
|
raise DestinationError(f"Cannot create the folder: {e.strerror or e}") from e
|
||||||
|
continue
|
||||||
|
if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode):
|
||||||
|
raise DestinationError("Folder is a symbolic link or not a directory: refused")
|
||||||
|
real = os.path.realpath(current)
|
||||||
|
if real != root and not real.startswith(root + os.sep):
|
||||||
|
raise DestinationError("Folder is outside the backup root: refused")
|
||||||
|
return real
|
||||||
|
|
||||||
|
def test(self) -> str:
|
||||||
|
directory = self._dir(create=True)
|
||||||
|
probe = os.path.join(directory, f".ovpmon-test-{uuid.uuid4().hex[:8]}")
|
||||||
|
try:
|
||||||
|
with open(probe, "wb") as f:
|
||||||
|
f.write(b"ok")
|
||||||
|
os.remove(probe)
|
||||||
|
except OSError as e:
|
||||||
|
raise DestinationError(f"Cannot write to the folder: {e.strerror or e}") from e
|
||||||
|
free = shutil.disk_usage(directory).free // (1024 * 1024)
|
||||||
|
return f"Folder is writable ({free} MB free)"
|
||||||
|
|
||||||
|
def put(self, local_path, name):
|
||||||
|
_check_name(name)
|
||||||
|
directory = self._dir(create=True)
|
||||||
|
final = os.path.join(directory, name)
|
||||||
|
tmp = os.path.join(directory, f".{name}.part")
|
||||||
|
try:
|
||||||
|
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as out, open(local_path, "rb") as src:
|
||||||
|
shutil.copyfileobj(src, out, 1024 * 1024)
|
||||||
|
os.replace(tmp, final)
|
||||||
|
except OSError as e:
|
||||||
|
try:
|
||||||
|
os.remove(tmp)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
raise DestinationError(f"Cannot write the package: {e.strerror or e}") from e
|
||||||
|
|
||||||
|
def list(self):
|
||||||
|
try:
|
||||||
|
directory = self._dir(create=False)
|
||||||
|
except DestinationError as e:
|
||||||
|
if "does not exist" in str(e):
|
||||||
|
return []
|
||||||
|
raise
|
||||||
|
out = []
|
||||||
|
with os.scandir(directory) as it:
|
||||||
|
for entry in it:
|
||||||
|
try:
|
||||||
|
st = entry.stat(follow_symlinks=False)
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
if stat.S_ISREG(st.st_mode) and not entry.name.startswith("."):
|
||||||
|
out.append({"name": entry.name, "size": st.st_size, "mtime": st.st_mtime})
|
||||||
|
return out
|
||||||
|
|
||||||
|
def get(self, name, local_path):
|
||||||
|
_check_name(name)
|
||||||
|
path = os.path.join(self._dir(create=False), name)
|
||||||
|
try:
|
||||||
|
st = os.lstat(path)
|
||||||
|
if not stat.S_ISREG(st.st_mode):
|
||||||
|
raise DestinationError("Not a regular file: refused")
|
||||||
|
fd = os.open(local_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as out, open(path, "rb") as src:
|
||||||
|
shutil.copyfileobj(src, out, 1024 * 1024)
|
||||||
|
except OSError as e:
|
||||||
|
raise DestinationError(f"Cannot read the package: {e.strerror or e}") from e
|
||||||
|
|
||||||
|
def delete(self, name):
|
||||||
|
_check_name(name)
|
||||||
|
path = os.path.join(self._dir(create=False), name)
|
||||||
|
try:
|
||||||
|
if stat.S_ISREG(os.lstat(path).st_mode):
|
||||||
|
os.remove(path)
|
||||||
|
except FileNotFoundError:
|
||||||
|
pass
|
||||||
|
except OSError as e:
|
||||||
|
raise DestinationError(f"Cannot delete the package: {e.strerror or e}") from e
|
||||||
|
|
||||||
|
|
||||||
|
# --- S3 (minio client) ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
class S3Destination(Destination):
|
||||||
|
"""AWS S3 or a compatible store, through the minio Python SDK."""
|
||||||
|
type = "s3"
|
||||||
|
label = "S3 bucket"
|
||||||
|
FIELDS = [
|
||||||
|
{"name": "endpoint", "label": "Endpoint (host[:port])", "kind": "text", "required": True,
|
||||||
|
"default": "s3.amazonaws.com", "hint": "Without http:// or https://"},
|
||||||
|
{"name": "secure", "label": "Use TLS (https)", "kind": "bool", "required": False, "default": True},
|
||||||
|
{"name": "region", "label": "Region (optional)", "kind": "text", "required": False, "default": ""},
|
||||||
|
{"name": "bucket", "label": "Bucket", "kind": "text", "required": True, "default": ""},
|
||||||
|
{"name": "prefix", "label": "Prefix (optional)", "kind": "text", "required": False, "default": "",
|
||||||
|
"hint": "Folder inside the bucket, for example 'ovpmon/'"},
|
||||||
|
{"name": "access_key", "label": "Access key", "kind": "secret", "required": True},
|
||||||
|
{"name": "secret_key", "label": "Secret key", "kind": "secret", "required": True},
|
||||||
|
]
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def validate(cls, params, secrets, previous_secrets=None):
|
||||||
|
_unknown_keys(params, {"endpoint", "secure", "region", "bucket", "prefix"}, "parameters")
|
||||||
|
_unknown_keys(secrets, {"access_key", "secret_key"}, "secrets")
|
||||||
|
endpoint = str(params.get("endpoint", "")).strip()
|
||||||
|
host, _, port = endpoint.partition(":")
|
||||||
|
if not endpoint or "/" in endpoint or not HOST_RE.match(host) or (port and not (port.isdigit() and 0 < int(port) < 65536)):
|
||||||
|
raise ValueError("Endpoint must be host[:port] without http:// or a path")
|
||||||
|
bucket = str(params.get("bucket", "")).strip()
|
||||||
|
if not BUCKET_RE.match(bucket) or ".." in bucket:
|
||||||
|
raise ValueError("Bucket name is invalid (3-63 lowercase letters, digits, '.' and '-')")
|
||||||
|
region = str(params.get("region", "") or "").strip()
|
||||||
|
if region and not REGION_RE.match(region):
|
||||||
|
raise ValueError("Region is invalid")
|
||||||
|
prefix = str(params.get("prefix", "") or "").strip().strip("/")
|
||||||
|
if prefix:
|
||||||
|
parts = prefix.split("/")
|
||||||
|
if len(prefix) > 200 or not all(re.match(r"^[A-Za-z0-9][A-Za-z0-9._ -]{0,63}$", p) for p in parts) or ".." in prefix:
|
||||||
|
raise ValueError("Prefix is invalid: use folders of letters, digits, '.', '_', '-' and spaces")
|
||||||
|
prefix += "/"
|
||||||
|
clean_secrets = {}
|
||||||
|
previous = previous_secrets or {}
|
||||||
|
for key in ("access_key", "secret_key"):
|
||||||
|
value = str(secrets.get(key) or "").strip() or previous.get(key, "")
|
||||||
|
if not value:
|
||||||
|
raise ValueError(f"{'Access key' if key == 'access_key' else 'Secret key'} is required")
|
||||||
|
if len(value) > 512:
|
||||||
|
raise ValueError("Key is too long")
|
||||||
|
clean_secrets[key] = value
|
||||||
|
clean = {"endpoint": endpoint, "secure": bool(params.get("secure", True)),
|
||||||
|
"region": region, "bucket": bucket, "prefix": prefix}
|
||||||
|
return clean, clean_secrets
|
||||||
|
|
||||||
|
def _client(self):
|
||||||
|
try:
|
||||||
|
import urllib3
|
||||||
|
from minio import Minio
|
||||||
|
except ImportError as e: # the package is in requirements.txt; this is a broken installation
|
||||||
|
raise DestinationError("The 'minio' library is not installed") from e
|
||||||
|
http = urllib3.PoolManager(timeout=urllib3.Timeout(connect=10, read=120),
|
||||||
|
retries=urllib3.Retry(total=2, backoff_factor=0.5))
|
||||||
|
return Minio(self.params["endpoint"], access_key=self.secrets["access_key"],
|
||||||
|
secret_key=self.secrets["secret_key"], secure=self.params["secure"],
|
||||||
|
region=self.params["region"] or None, http_client=http)
|
||||||
|
|
||||||
|
def _call(self, fn):
|
||||||
|
from minio.error import S3Error
|
||||||
|
try:
|
||||||
|
return fn()
|
||||||
|
except DestinationError:
|
||||||
|
raise
|
||||||
|
except S3Error as e:
|
||||||
|
raise DestinationError(f"S3 error {e.code}: {str(e.message)[:200]}") from e
|
||||||
|
except Exception as e:
|
||||||
|
raise DestinationError(_short(e)) from e
|
||||||
|
|
||||||
|
def _key(self, name: str) -> str:
|
||||||
|
return self.params["prefix"] + _check_name(name)
|
||||||
|
|
||||||
|
def test(self) -> str:
|
||||||
|
client = self._client()
|
||||||
|
bucket = self.params["bucket"]
|
||||||
|
|
||||||
|
def probe():
|
||||||
|
if not client.bucket_exists(bucket):
|
||||||
|
raise DestinationError(f"Bucket '{bucket}' does not exist or is not visible to this key")
|
||||||
|
key = self.params["prefix"] + f".ovpmon-test-{uuid.uuid4().hex[:8]}"
|
||||||
|
import io
|
||||||
|
client.put_object(bucket, key, io.BytesIO(b"ok"), 2)
|
||||||
|
try:
|
||||||
|
client.remove_object(bucket, key)
|
||||||
|
except Exception:
|
||||||
|
return "Bucket is writable, but deleting objects is not allowed (rotation will not work)"
|
||||||
|
return "Bucket is reachable, write and delete work"
|
||||||
|
return self._call(probe)
|
||||||
|
|
||||||
|
def put(self, local_path, name):
|
||||||
|
client = self._client()
|
||||||
|
self._call(lambda: client.fput_object(self.params["bucket"], self._key(name), local_path,
|
||||||
|
content_type="application/octet-stream"))
|
||||||
|
|
||||||
|
def list(self):
|
||||||
|
client = self._client()
|
||||||
|
prefix = self.params["prefix"]
|
||||||
|
|
||||||
|
def run():
|
||||||
|
out = []
|
||||||
|
for obj in client.list_objects(self.params["bucket"], prefix=prefix or None, recursive=False):
|
||||||
|
if obj.is_dir or not obj.object_name.startswith(prefix):
|
||||||
|
continue
|
||||||
|
name = obj.object_name[len(prefix):]
|
||||||
|
if "/" in name or not name:
|
||||||
|
continue
|
||||||
|
mtime = obj.last_modified.timestamp() if obj.last_modified else None
|
||||||
|
out.append({"name": name, "size": obj.size or 0, "mtime": mtime})
|
||||||
|
return out
|
||||||
|
return self._call(run)
|
||||||
|
|
||||||
|
def get(self, name, local_path):
|
||||||
|
client = self._client()
|
||||||
|
|
||||||
|
def run():
|
||||||
|
resp = client.get_object(self.params["bucket"], self._key(name))
|
||||||
|
try:
|
||||||
|
fd = os.open(local_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as out:
|
||||||
|
shutil.copyfileobj(resp, out, 1024 * 1024)
|
||||||
|
finally:
|
||||||
|
resp.close()
|
||||||
|
resp.release_conn()
|
||||||
|
self._call(run)
|
||||||
|
|
||||||
|
def delete(self, name):
|
||||||
|
client = self._client()
|
||||||
|
self._call(lambda: client.remove_object(self.params["bucket"], self._key(name)))
|
||||||
|
|
||||||
|
|
||||||
|
# --- shared by SFTP and FTP ----------------------------------------------------------------
|
||||||
|
|
||||||
|
CONNECT_TIMEOUT = 15 # seconds: connection, banner, login
|
||||||
|
TRANSFER_TIMEOUT = 120 # seconds without data on an open transfer
|
||||||
|
USER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._@-]{0,127}$")
|
||||||
|
FINGERPRINT_RE = re.compile(r"^SHA256:[A-Za-z0-9+/]{43}$")
|
||||||
|
|
||||||
|
|
||||||
|
def _check_host_port(params: dict, default_port: int):
|
||||||
|
host = str(params.get("host", "")).strip()
|
||||||
|
if not host or not HOST_RE.match(host):
|
||||||
|
raise ValueError("Host must be a host name or an IPv4 address")
|
||||||
|
try:
|
||||||
|
port = int(params.get("port") or default_port)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise ValueError("Port must be a number") from None
|
||||||
|
if not 0 < port < 65536:
|
||||||
|
raise ValueError("Port must be between 1 and 65535")
|
||||||
|
return host, port
|
||||||
|
|
||||||
|
|
||||||
|
def _check_username(params: dict) -> str:
|
||||||
|
user = str(params.get("username", "")).strip()
|
||||||
|
if not USER_RE.match(user):
|
||||||
|
raise ValueError("User name is required (letters, digits, '.', '_', '-', '@')")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _check_directory(params: dict) -> str:
|
||||||
|
"""Remote directory: the same rule as the local folder (relative, no '..', at most 4 levels)."""
|
||||||
|
directory = str(params.get("directory", "")).strip().rstrip("/")
|
||||||
|
if not directory:
|
||||||
|
raise ValueError("Directory is required")
|
||||||
|
if directory.startswith("/"):
|
||||||
|
raise ValueError("Directory must be relative to the login directory of the user (no leading '/')")
|
||||||
|
parts = directory.split("/")
|
||||||
|
if len(parts) > 4 or not all(FOLDER_SEGMENT_RE.match(p) and ".." not in p for p in parts):
|
||||||
|
raise ValueError("Directory must be a relative path of letters, digits, '.', '_' and '-' "
|
||||||
|
"(no '..', no leading dot, at most 4 levels)")
|
||||||
|
return "/".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def _secret_value(secrets: dict, key: str, label: str, limit: int = 512) -> str:
|
||||||
|
value = str(secrets.get(key) or "").strip()
|
||||||
|
if len(value) > limit:
|
||||||
|
raise ValueError(f"{label} is too long")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _ssh_fingerprint(key) -> str:
|
||||||
|
return "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode("ascii").rstrip("=")
|
||||||
|
|
||||||
|
|
||||||
|
# --- SFTP (paramiko) -----------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _paramiko():
|
||||||
|
try:
|
||||||
|
import paramiko
|
||||||
|
except ImportError as e: # the package is in requirements.txt; this is a broken installation
|
||||||
|
raise DestinationError("The 'paramiko' library is not installed") from e
|
||||||
|
return paramiko
|
||||||
|
|
||||||
|
|
||||||
|
def _load_private_key(text: str, passphrase: str):
|
||||||
|
"""paramiko key object of a PEM / OpenSSH private key text. ValueError without any key material."""
|
||||||
|
paramiko = _paramiko()
|
||||||
|
for cls in (paramiko.Ed25519Key, paramiko.ECDSAKey, paramiko.RSAKey):
|
||||||
|
try:
|
||||||
|
return cls.from_private_key(io.StringIO(text), password=passphrase or None)
|
||||||
|
except Exception:
|
||||||
|
continue # not this key type, or a wrong passphrase: the message below covers both
|
||||||
|
raise ValueError("The private key cannot be read: check the key text and its passphrase "
|
||||||
|
"(supported: RSA, ECDSA, Ed25519; OpenSSH or PEM)")
|
||||||
|
|
||||||
|
|
||||||
|
class SFTPDestination(Destination):
|
||||||
|
"""SFTP server. The SSH host key is pinned by its SHA-256 fingerprint: the first Test shows it,
|
||||||
|
the administrator confirms it ('Trust'), after that every connection must present exactly that
|
||||||
|
key. Nothing is copied, listed, read or deleted while the key is not pinned."""
|
||||||
|
type = "sftp"
|
||||||
|
label = "SFTP server"
|
||||||
|
PIN_PARAMS = ("host_key", "host_key_type")
|
||||||
|
PIN_DEPENDS = ("host", "port")
|
||||||
|
FIELDS = [
|
||||||
|
{"name": "host", "label": "Host", "kind": "text", "required": True, "default": "",
|
||||||
|
"hint": "Host name or IPv4 address"},
|
||||||
|
{"name": "port", "label": "Port", "kind": "number", "required": True, "default": 22},
|
||||||
|
{"name": "username", "label": "User name", "kind": "text", "required": True, "default": ""},
|
||||||
|
{"name": "directory", "label": "Directory", "kind": "text", "required": True, "default": "ovpmon-backups",
|
||||||
|
"hint": "Relative to the login directory of the user; created if missing"},
|
||||||
|
{"name": "password", "label": "Password", "kind": "secret", "required": False,
|
||||||
|
"hint": "Password or private key: give one of them"},
|
||||||
|
{"name": "private_key", "label": "Private key (PEM / OpenSSH text)", "kind": "secret_multiline",
|
||||||
|
"required": False},
|
||||||
|
{"name": "key_passphrase", "label": "Private key passphrase (if the key is encrypted)", "kind": "secret",
|
||||||
|
"required": False},
|
||||||
|
]
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def validate(cls, params, secrets, previous_secrets=None):
|
||||||
|
_unknown_keys(params, {"host", "port", "username", "directory"}, "parameters")
|
||||||
|
_unknown_keys(secrets, {"password", "private_key", "key_passphrase"}, "secrets")
|
||||||
|
host, port = _check_host_port(params, 22)
|
||||||
|
clean = {"host": host, "port": port, "username": _check_username(params),
|
||||||
|
"directory": _check_directory(params)}
|
||||||
|
previous = previous_secrets or {}
|
||||||
|
password = _secret_value(secrets, "password", "Password")
|
||||||
|
key = _secret_value(secrets, "private_key", "Private key", 16384).replace("\r\n", "\n")
|
||||||
|
phrase = _secret_value(secrets, "key_passphrase", "Key passphrase")
|
||||||
|
if password and key:
|
||||||
|
raise ValueError("Give a password or a private key, not both")
|
||||||
|
if not password and not key:
|
||||||
|
# nothing new: keep what is stored (a new passphrase goes with the stored key)
|
||||||
|
password, key = previous.get("password", ""), previous.get("private_key", "")
|
||||||
|
phrase = phrase or previous.get("key_passphrase", "")
|
||||||
|
if not password and not key:
|
||||||
|
raise ValueError("A password or a private key is required")
|
||||||
|
if key:
|
||||||
|
if "PRIVATE KEY" not in key:
|
||||||
|
raise ValueError("The private key must be the text of the key file (-----BEGIN ... PRIVATE KEY-----)")
|
||||||
|
_load_private_key(key + "\n", phrase)
|
||||||
|
clean_secrets = {"private_key": key.strip() + "\n"}
|
||||||
|
if phrase:
|
||||||
|
clean_secrets["key_passphrase"] = phrase
|
||||||
|
else:
|
||||||
|
clean_secrets = {"password": password}
|
||||||
|
return clean, clean_secrets
|
||||||
|
|
||||||
|
# -- connection --
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _policy(pinned: Optional[str], seen: dict):
|
||||||
|
"""Host key policy: records what the server shows and accepts ONLY the pinned fingerprint.
|
||||||
|
Unknown keys are rejected (never added automatically)."""
|
||||||
|
paramiko = _paramiko()
|
||||||
|
|
||||||
|
class PinnedPolicy(paramiko.MissingHostKeyPolicy):
|
||||||
|
def missing_host_key(self, client, hostname, key):
|
||||||
|
seen["fingerprint"], seen["key_type"] = _ssh_fingerprint(key), key.get_name()
|
||||||
|
if not pinned or not hmac.compare_digest(seen["fingerprint"], pinned):
|
||||||
|
raise paramiko.SSHException("host key is not trusted")
|
||||||
|
return PinnedPolicy()
|
||||||
|
|
||||||
|
def _connect(self, allow_trust: bool = False):
|
||||||
|
"""Open the SSH connection and return the client. allow_trust: for Test and the pinning
|
||||||
|
call; a key that is unknown or changed then raises NeedsTrust with the fingerprint."""
|
||||||
|
paramiko = _paramiko()
|
||||||
|
pinned = self.params.get("host_key") or None
|
||||||
|
if not pinned and not allow_trust:
|
||||||
|
raise DestinationError("The host key of the server is not trusted yet: run Test and confirm the fingerprint")
|
||||||
|
pkey = None
|
||||||
|
if self.secrets.get("private_key"):
|
||||||
|
try:
|
||||||
|
pkey = _load_private_key(self.secrets["private_key"], self.secrets.get("key_passphrase", ""))
|
||||||
|
except ValueError as e:
|
||||||
|
raise DestinationError(str(e)) from None
|
||||||
|
seen: dict = {}
|
||||||
|
client = paramiko.SSHClient() # no known_hosts is loaded: every key goes to the policy
|
||||||
|
client.set_missing_host_key_policy(self._policy(pinned, seen))
|
||||||
|
try:
|
||||||
|
client.connect(self.params["host"], port=self.params["port"], username=self.params["username"],
|
||||||
|
password=self.secrets.get("password") or None, pkey=pkey,
|
||||||
|
timeout=CONNECT_TIMEOUT, banner_timeout=CONNECT_TIMEOUT, auth_timeout=CONNECT_TIMEOUT,
|
||||||
|
allow_agent=False, look_for_keys=False)
|
||||||
|
except Exception as e:
|
||||||
|
client.close()
|
||||||
|
fp = seen.get("fingerprint")
|
||||||
|
if fp and fp != pinned:
|
||||||
|
if allow_trust:
|
||||||
|
raise NeedsTrust(
|
||||||
|
("The host key changed: it differs from the trusted one" if pinned
|
||||||
|
else "The host key of the server is not trusted yet"),
|
||||||
|
fp, seen.get("key_type", ""), changed=bool(pinned)) from None
|
||||||
|
raise DestinationError("The host key of the server changed: connection refused. "
|
||||||
|
"Run Test to see the new fingerprint and trust it if the change is expected") from None
|
||||||
|
raise DestinationError(self._explain(e)) from None
|
||||||
|
return client
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _explain(e: Exception) -> str:
|
||||||
|
paramiko = _paramiko()
|
||||||
|
if isinstance(e, paramiko.AuthenticationException):
|
||||||
|
return "Authentication failed: check the user name and the password or key"
|
||||||
|
if isinstance(e, (socket.timeout, TimeoutError)):
|
||||||
|
return "Connection timed out"
|
||||||
|
if isinstance(e, socket.gaierror):
|
||||||
|
return "Host name cannot be resolved"
|
||||||
|
if isinstance(e, ConnectionRefusedError):
|
||||||
|
return "Connection refused"
|
||||||
|
if isinstance(e, paramiko.SSHException):
|
||||||
|
return f"SSH error: {str(e)[:200]}"
|
||||||
|
if isinstance(e, OSError):
|
||||||
|
return f"Network error: {e.strerror or type(e).__name__}"
|
||||||
|
return _short(e)
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _session(self, allow_trust: bool = False):
|
||||||
|
client = self._connect(allow_trust)
|
||||||
|
try:
|
||||||
|
sftp = client.open_sftp()
|
||||||
|
sftp.get_channel().settimeout(TRANSFER_TIMEOUT)
|
||||||
|
yield sftp
|
||||||
|
except DestinationError:
|
||||||
|
raise
|
||||||
|
except FileNotFoundError:
|
||||||
|
raise DestinationError("File or directory not found on the server") from None
|
||||||
|
except Exception as e:
|
||||||
|
raise DestinationError(self._explain(e)) from None
|
||||||
|
finally:
|
||||||
|
client.close()
|
||||||
|
|
||||||
|
def fetch_host_key(self):
|
||||||
|
try:
|
||||||
|
self._connect(allow_trust=True).close()
|
||||||
|
except NeedsTrust as n:
|
||||||
|
return n.fingerprint, n.key_type
|
||||||
|
return self.params.get("host_key", ""), self.params.get("host_key_type", "")
|
||||||
|
|
||||||
|
# -- operations --
|
||||||
|
|
||||||
|
def _dir(self, sftp, create: bool) -> str:
|
||||||
|
"""Change into the directory (creating the levels when asked). Returns the path."""
|
||||||
|
path = ""
|
||||||
|
for part in self.params["directory"].split("/"):
|
||||||
|
path = f"{path}/{part}" if path else part
|
||||||
|
try:
|
||||||
|
if not stat.S_ISDIR(sftp.stat(path).st_mode):
|
||||||
|
raise DestinationError(f"'{path}' on the server is not a directory")
|
||||||
|
except FileNotFoundError:
|
||||||
|
if not create:
|
||||||
|
raise DestinationError("Directory does not exist yet") from None
|
||||||
|
sftp.mkdir(path, 0o700)
|
||||||
|
return path
|
||||||
|
|
||||||
|
def test(self) -> str:
|
||||||
|
with self._session(allow_trust=True) as sftp:
|
||||||
|
directory = self._dir(sftp, create=True)
|
||||||
|
probe = f"{directory}/.ovpmon-test-{uuid.uuid4().hex[:8]}"
|
||||||
|
sftp.putfo(io.BytesIO(b"ok"), probe)
|
||||||
|
try:
|
||||||
|
sftp.remove(probe)
|
||||||
|
except Exception:
|
||||||
|
return "Server is writable, but deleting files is not allowed (rotation will not work)"
|
||||||
|
return "SFTP server is reachable, host key matches, write and delete work"
|
||||||
|
|
||||||
|
def put(self, local_path, name):
|
||||||
|
_check_name(name)
|
||||||
|
with self._session() as sftp:
|
||||||
|
directory = self._dir(sftp, create=True)
|
||||||
|
final, tmp = f"{directory}/{name}", f"{directory}/.{name}.part"
|
||||||
|
try:
|
||||||
|
sftp.put(local_path, tmp, confirm=True)
|
||||||
|
try:
|
||||||
|
sftp.posix_rename(tmp, final)
|
||||||
|
except OSError: # the server has no posix-rename extension
|
||||||
|
sftp.rename(tmp, final)
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
sftp.remove(tmp)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
raise
|
||||||
|
|
||||||
|
def list(self):
|
||||||
|
with self._session() as sftp:
|
||||||
|
try:
|
||||||
|
directory = self._dir(sftp, create=False)
|
||||||
|
except DestinationError as e:
|
||||||
|
if "does not exist" in str(e):
|
||||||
|
return []
|
||||||
|
raise
|
||||||
|
return [{"name": a.filename, "size": a.st_size or 0, "mtime": a.st_mtime}
|
||||||
|
for a in sftp.listdir_attr(directory)
|
||||||
|
if stat.S_ISREG(a.st_mode or 0) and PACKAGE_RE.match(a.filename)]
|
||||||
|
|
||||||
|
def get(self, name, local_path):
|
||||||
|
_check_name(name)
|
||||||
|
with self._session() as sftp:
|
||||||
|
remote = f"{self._dir(sftp, create=False)}/{name}"
|
||||||
|
fd = os.open(local_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as out:
|
||||||
|
sftp.getfo(remote, out)
|
||||||
|
|
||||||
|
def delete(self, name):
|
||||||
|
_check_name(name)
|
||||||
|
with self._session() as sftp:
|
||||||
|
try:
|
||||||
|
sftp.remove(f"{self._dir(sftp, create=False)}/{name}")
|
||||||
|
except FileNotFoundError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# --- FTP / FTPS (ftplib) -------------------------------------------------------------------
|
||||||
|
|
||||||
|
class FTPDestination(Destination):
|
||||||
|
"""FTP server; explicit FTPS (AUTH TLS) with certificate verification by default. Plain FTP and a
|
||||||
|
disabled certificate check are allowed explicitly (the UI warns)."""
|
||||||
|
type = "ftp"
|
||||||
|
label = "FTP / FTPS server"
|
||||||
|
FIELDS = [
|
||||||
|
{"name": "host", "label": "Host", "kind": "text", "required": True, "default": "",
|
||||||
|
"hint": "Host name or IPv4 address"},
|
||||||
|
{"name": "port", "label": "Port", "kind": "number", "required": True, "default": 21},
|
||||||
|
{"name": "username", "label": "User name", "kind": "text", "required": True, "default": ""},
|
||||||
|
{"name": "directory", "label": "Directory", "kind": "text", "required": True, "default": "ovpmon-backups",
|
||||||
|
"hint": "Relative to the login directory of the user; created if missing"},
|
||||||
|
{"name": "tls", "label": "Use TLS (explicit FTPS)", "kind": "bool", "required": False, "default": True,
|
||||||
|
"warning": "Without TLS the password and the packages travel in clear text. Use only inside a trusted network.",
|
||||||
|
"warn_if": False},
|
||||||
|
{"name": "verify_cert", "label": "Verify the server certificate", "kind": "bool", "required": False,
|
||||||
|
"default": True,
|
||||||
|
"warning": "Certificate verification is off: the server cannot be told from an impostor. Use only for a self-signed certificate in a trusted network.",
|
||||||
|
"warn_if": False},
|
||||||
|
{"name": "passive", "label": "Passive mode", "kind": "bool", "required": False, "default": True},
|
||||||
|
{"name": "password", "label": "Password", "kind": "secret", "required": True},
|
||||||
|
]
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def validate(cls, params, secrets, previous_secrets=None):
|
||||||
|
_unknown_keys(params, {"host", "port", "username", "directory", "tls", "verify_cert", "passive"}, "parameters")
|
||||||
|
_unknown_keys(secrets, {"password"}, "secrets")
|
||||||
|
host, port = _check_host_port(params, 21)
|
||||||
|
clean = {"host": host, "port": port, "username": _check_username(params),
|
||||||
|
"directory": _check_directory(params),
|
||||||
|
"tls": bool(params.get("tls", True)), "verify_cert": bool(params.get("verify_cert", True)),
|
||||||
|
"passive": bool(params.get("passive", True))}
|
||||||
|
password = _secret_value(secrets, "password", "Password") or (previous_secrets or {}).get("password", "")
|
||||||
|
if not password:
|
||||||
|
raise ValueError("Password is required")
|
||||||
|
return clean, {"password": password}
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _session(self, create_dir: bool = False):
|
||||||
|
import ftplib
|
||||||
|
p = self.params
|
||||||
|
try:
|
||||||
|
if p["tls"]:
|
||||||
|
ctx = ssl.create_default_context()
|
||||||
|
if not p["verify_cert"]:
|
||||||
|
ctx.check_hostname = False
|
||||||
|
ctx.verify_mode = ssl.CERT_NONE
|
||||||
|
ftp = ftplib.FTP_TLS(context=ctx, timeout=TRANSFER_TIMEOUT)
|
||||||
|
else:
|
||||||
|
ftp = ftplib.FTP(timeout=TRANSFER_TIMEOUT)
|
||||||
|
except Exception as e:
|
||||||
|
raise DestinationError(_short(e)) from None
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
ftp.connect(p["host"], p["port"], timeout=CONNECT_TIMEOUT)
|
||||||
|
ftp.login(p["username"], self.secrets["password"])
|
||||||
|
ftp.timeout = TRANSFER_TIMEOUT # transfers (data connections) wait longer than the login
|
||||||
|
ftp.sock.settimeout(TRANSFER_TIMEOUT)
|
||||||
|
if p["tls"]:
|
||||||
|
ftp.prot_p() # TLS for the data connection too
|
||||||
|
ftp.set_pasv(p["passive"])
|
||||||
|
self._cd(ftp, create_dir)
|
||||||
|
yield ftp
|
||||||
|
except DestinationError:
|
||||||
|
raise
|
||||||
|
except Exception as e:
|
||||||
|
raise DestinationError(self._explain(e)) from None
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
ftp.quit()
|
||||||
|
except Exception:
|
||||||
|
ftp.close()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _explain(e: Exception) -> str:
|
||||||
|
import ftplib
|
||||||
|
if isinstance(e, ssl.SSLCertVerificationError):
|
||||||
|
return f"TLS certificate check failed: {(e.verify_message or 'invalid certificate')[:150]}. " \
|
||||||
|
"For a self-signed certificate turn the verification off in the destination"
|
||||||
|
if isinstance(e, ssl.SSLError):
|
||||||
|
return f"TLS error: {(e.reason or type(e).__name__)}"
|
||||||
|
if isinstance(e, ftplib.error_perm):
|
||||||
|
text = str(e)[:200]
|
||||||
|
return "Login failed: check the user name and the password" if text.startswith("530") else f"Server refused: {text}"
|
||||||
|
if isinstance(e, ftplib.Error):
|
||||||
|
return f"FTP error: {str(e)[:200]}"
|
||||||
|
if isinstance(e, (socket.timeout, TimeoutError)):
|
||||||
|
return "Connection timed out"
|
||||||
|
if isinstance(e, socket.gaierror):
|
||||||
|
return "Host name cannot be resolved"
|
||||||
|
if isinstance(e, ConnectionRefusedError):
|
||||||
|
return "Connection refused"
|
||||||
|
if isinstance(e, EOFError):
|
||||||
|
return "The server closed the connection"
|
||||||
|
if isinstance(e, OSError):
|
||||||
|
return f"Network error: {e.strerror or type(e).__name__}"
|
||||||
|
return _short(e)
|
||||||
|
|
||||||
|
def _cd(self, ftp, create: bool) -> None:
|
||||||
|
import ftplib
|
||||||
|
for part in self.params["directory"].split("/"):
|
||||||
|
try:
|
||||||
|
ftp.cwd(part)
|
||||||
|
except ftplib.error_perm:
|
||||||
|
if not create:
|
||||||
|
raise DestinationError("Directory does not exist yet") from None
|
||||||
|
ftp.mkd(part)
|
||||||
|
ftp.cwd(part)
|
||||||
|
|
||||||
|
def test(self) -> str:
|
||||||
|
with self._session(create_dir=True) as ftp:
|
||||||
|
probe = f".ovpmon-test-{uuid.uuid4().hex[:8]}"
|
||||||
|
ftp.storbinary(f"STOR {probe}", io.BytesIO(b"ok"))
|
||||||
|
try:
|
||||||
|
ftp.delete(probe)
|
||||||
|
except Exception:
|
||||||
|
return "Server is writable, but deleting files is not allowed (rotation will not work)"
|
||||||
|
mode = "TLS" if self.params["tls"] else "NO TLS (clear text)"
|
||||||
|
return f"FTP server is reachable ({mode}), write and delete work"
|
||||||
|
|
||||||
|
def put(self, local_path, name):
|
||||||
|
_check_name(name)
|
||||||
|
tmp = f".{name}.part"
|
||||||
|
with self._session(create_dir=True) as ftp:
|
||||||
|
try:
|
||||||
|
with open(local_path, "rb") as src:
|
||||||
|
ftp.storbinary(f"STOR {tmp}", src, blocksize=1024 * 1024)
|
||||||
|
ftp.rename(tmp, name)
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
ftp.delete(tmp)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
raise
|
||||||
|
|
||||||
|
def list(self):
|
||||||
|
try:
|
||||||
|
with self._session() as ftp:
|
||||||
|
return self._packages(ftp)
|
||||||
|
except DestinationError as e:
|
||||||
|
if "does not exist" in str(e):
|
||||||
|
return []
|
||||||
|
raise
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _packages(ftp):
|
||||||
|
import ftplib
|
||||||
|
out = []
|
||||||
|
try:
|
||||||
|
for name, facts in ftp.mlsd(facts=["type", "size", "modify"]):
|
||||||
|
if facts.get("type") == "file" and PACKAGE_RE.match(name):
|
||||||
|
out.append({"name": name, "size": int(facts.get("size") or 0),
|
||||||
|
"mtime": FTPDestination._mtime(facts.get("modify"))})
|
||||||
|
return out
|
||||||
|
except ftplib.error_perm:
|
||||||
|
out = [] # no MLSD on this server: names first, then size and time of our packages
|
||||||
|
ftp.voidcmd("TYPE I")
|
||||||
|
for entry in ftp.nlst():
|
||||||
|
name = entry.rsplit("/", 1)[-1]
|
||||||
|
if not PACKAGE_RE.match(name):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
size = ftp.size(name) or 0
|
||||||
|
except ftplib.Error:
|
||||||
|
size = 0
|
||||||
|
try:
|
||||||
|
mtime = FTPDestination._mtime(ftp.voidcmd(f"MDTM {name}").split()[-1])
|
||||||
|
except ftplib.Error:
|
||||||
|
mtime = None
|
||||||
|
out.append({"name": name, "size": size, "mtime": mtime})
|
||||||
|
return out
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _mtime(modify):
|
||||||
|
try:
|
||||||
|
return datetime.strptime(modify[:14], "%Y%m%d%H%M%S").replace(tzinfo=timezone.utc).timestamp()
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def get(self, name, local_path):
|
||||||
|
_check_name(name)
|
||||||
|
with self._session() as ftp:
|
||||||
|
ftp.voidcmd("TYPE I")
|
||||||
|
fd = os.open(local_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as out:
|
||||||
|
ftp.retrbinary(f"RETR {name}", out.write, blocksize=1024 * 1024)
|
||||||
|
|
||||||
|
def delete(self, name):
|
||||||
|
_check_name(name)
|
||||||
|
with self._session() as ftp:
|
||||||
|
ftp.delete(name)
|
||||||
|
|
||||||
|
|
||||||
|
# Registry: the API accepts exactly these types. smb comes in a later pass.
|
||||||
|
DESTINATION_TYPES = {
|
||||||
|
LocalDestination.type: LocalDestination,
|
||||||
|
S3Destination.type: S3Destination,
|
||||||
|
SFTPDestination.type: SFTPDestination,
|
||||||
|
FTPDestination.type: FTPDestination,
|
||||||
|
}
|
||||||
|
|
||||||
|
REMOTE_TYPES = {t for t in DESTINATION_TYPES if t != "local"} # these need an encryption passphrase
|
||||||
|
|
||||||
|
|
||||||
|
def build_destination(dtype: str, params: dict, secrets: dict) -> Destination:
|
||||||
|
cls = DESTINATION_TYPES.get(dtype)
|
||||||
|
if cls is None:
|
||||||
|
raise BackupError(f"Unsupported destination type: {dtype}")
|
||||||
|
return cls(params, secrets)
|
||||||
@@ -0,0 +1,657 @@
|
|||||||
|
"""Backup job and restore engine.
|
||||||
|
|
||||||
|
One background job at a time for the whole service (a backup or a restore), like the async PKI
|
||||||
|
initialization: the state lives in memory of the single Profiler process, results go to the history
|
||||||
|
in ovpmon_backup.db.
|
||||||
|
"""
|
||||||
|
import copy
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import sqlite3
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
import migrations
|
||||||
|
from database import SessionLocal, engine as sa_engine
|
||||||
|
|
||||||
|
from . import BackupError, Busy, Invalid, crypto, destinations, package, store
|
||||||
|
from services import pki, process
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
PRE_RESTORE_FOLDER = "pre-restore"
|
||||||
|
PRE_RESTORE_KEEP = 5
|
||||||
|
|
||||||
|
_lock = threading.Lock()
|
||||||
|
_job = {"kind": None, "state": "idle", "stages": [], "results": [], "warnings": [],
|
||||||
|
"started_at": None, "finished_at": None, "message": None, "relogin": False}
|
||||||
|
|
||||||
|
|
||||||
|
# --- paths ---------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def profiler_db_path() -> str:
|
||||||
|
from database import db_path
|
||||||
|
return os.path.abspath(db_path)
|
||||||
|
|
||||||
|
|
||||||
|
def monitor_db_path() -> str:
|
||||||
|
env = os.environ.get("OVPMON_OPENVPN_MONITOR_DB_PATH", "").strip()
|
||||||
|
return os.path.abspath(env) if env else os.path.join(os.path.dirname(profiler_db_path()), "openvpn_monitor.db")
|
||||||
|
|
||||||
|
|
||||||
|
def pki_dir() -> str:
|
||||||
|
return pki.PKI_DIR
|
||||||
|
|
||||||
|
|
||||||
|
def client_dir() -> str:
|
||||||
|
return os.path.join(os.getcwd(), "client-config")
|
||||||
|
|
||||||
|
|
||||||
|
def runtime() -> str:
|
||||||
|
return "container" if process.is_container() else "host"
|
||||||
|
|
||||||
|
|
||||||
|
def _work_dir() -> str:
|
||||||
|
"""Temporary directory for a job: next to the local backups (they have room by definition),
|
||||||
|
else the system temporary directory."""
|
||||||
|
base = os.environ.get("OVPMON_BACKUP_WORK_DIR", "").strip() or os.path.join(destinations.local_root(), ".work")
|
||||||
|
try:
|
||||||
|
os.makedirs(base, mode=0o700, exist_ok=True)
|
||||||
|
except OSError:
|
||||||
|
base = None
|
||||||
|
return tempfile.mkdtemp(prefix="job-", dir=base)
|
||||||
|
|
||||||
|
|
||||||
|
# --- job state -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _now() -> str:
|
||||||
|
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||||
|
|
||||||
|
|
||||||
|
def status() -> dict:
|
||||||
|
with _lock:
|
||||||
|
return copy.deepcopy(_job)
|
||||||
|
|
||||||
|
|
||||||
|
def is_running() -> bool:
|
||||||
|
with _lock:
|
||||||
|
return _job["state"] == "running"
|
||||||
|
|
||||||
|
|
||||||
|
def _claim(kind: str, stages: list, results: list) -> None:
|
||||||
|
with _lock:
|
||||||
|
if _job["state"] == "running":
|
||||||
|
raise Busy(f"A {_job['kind']} is already running")
|
||||||
|
_job.update(kind=kind, state="running", stages=[{"name": n, "state": "pending"} for n in stages],
|
||||||
|
results=results, warnings=[], started_at=_now(), finished_at=None, message=None,
|
||||||
|
relogin=False)
|
||||||
|
|
||||||
|
|
||||||
|
def _stage(name: str, state: str = "running") -> None:
|
||||||
|
with _lock:
|
||||||
|
for s in _job["stages"]:
|
||||||
|
if s["name"] == name:
|
||||||
|
s["state"] = state
|
||||||
|
elif s["state"] == "running" and state == "running":
|
||||||
|
s["state"] = "done"
|
||||||
|
|
||||||
|
|
||||||
|
def _warn(text: str) -> None:
|
||||||
|
logger.warning(f"[BACKUP] {text}")
|
||||||
|
with _lock:
|
||||||
|
_job["warnings"].append(text)
|
||||||
|
|
||||||
|
|
||||||
|
def _finish(state: str, message: str, relogin: bool = False) -> None:
|
||||||
|
with _lock:
|
||||||
|
for s in _job["stages"]:
|
||||||
|
if s["state"] == "running":
|
||||||
|
s["state"] = "done" if state in ("done", "partial") else "error"
|
||||||
|
_job.update(state=state, message=message, finished_at=_now(), relogin=relogin)
|
||||||
|
|
||||||
|
|
||||||
|
def _result(index: int, **fields) -> None:
|
||||||
|
with _lock:
|
||||||
|
_job["results"][index].update(fields)
|
||||||
|
|
||||||
|
|
||||||
|
# --- destinations --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def build_dest(rec: dict) -> destinations.Destination:
|
||||||
|
if not rec.get("secrets_ok", True):
|
||||||
|
raise BackupError("Stored secrets of this destination cannot be decrypted "
|
||||||
|
"(the JWT secret changed). Edit the destination and enter them again.")
|
||||||
|
return destinations.build_destination(rec["type"], rec["params"], rec["secrets"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_destination(dest_id: int) -> dict:
|
||||||
|
rec = store.get_destination(dest_id, with_secrets=True)
|
||||||
|
if not rec:
|
||||||
|
raise Invalid("Destination not found")
|
||||||
|
try:
|
||||||
|
message = build_dest(rec).test()
|
||||||
|
except destinations.NeedsTrust as e:
|
||||||
|
# SFTP: the host key is not pinned (or changed): show it, the administrator decides
|
||||||
|
store.set_last_result(dest_id, False, str(e))
|
||||||
|
return {"ok": False, "message": str(e), "needs_trust": True, "fingerprint": e.fingerprint,
|
||||||
|
"key_type": e.key_type, "key_changed": e.changed}
|
||||||
|
except BackupError as e:
|
||||||
|
store.set_last_result(dest_id, False, str(e))
|
||||||
|
return {"ok": False, "message": str(e)}
|
||||||
|
except Exception as e: # a driver error that is not mapped: report it, never crash the API
|
||||||
|
logger.exception("Destination test failed")
|
||||||
|
message = f"{type(e).__name__}: {str(e)[:200]}"
|
||||||
|
store.set_last_result(dest_id, False, message)
|
||||||
|
return {"ok": False, "message": message}
|
||||||
|
store.set_last_result(dest_id, True, message)
|
||||||
|
return {"ok": True, "message": message}
|
||||||
|
|
||||||
|
|
||||||
|
def effective_server_name() -> tuple:
|
||||||
|
"""(name, source): the server name of the settings, else the public address from the VPN
|
||||||
|
settings, else the host name. The name goes into the package names."""
|
||||||
|
name = store.get_server_name()
|
||||||
|
if name and package.SERVER_NAME_RE.match(name):
|
||||||
|
return name, "setting"
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(f"file:{profiler_db_path()}?mode=ro", uri=True, timeout=5)
|
||||||
|
try:
|
||||||
|
row = conn.execute("SELECT public_ip FROM system_settings LIMIT 1").fetchone()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
name = package.sanitize_name(row[0]) if row and row[0] else ""
|
||||||
|
if name:
|
||||||
|
return name, "public_ip"
|
||||||
|
except sqlite3.Error:
|
||||||
|
pass # no settings yet (or the column is absent): fall through
|
||||||
|
return package.host_name(), "hostname"
|
||||||
|
|
||||||
|
|
||||||
|
def trust_host_key(dest_id: int, fingerprint: str) -> dict:
|
||||||
|
"""Pin the host key the server shows now, if it is the one the administrator saw (`fingerprint`)."""
|
||||||
|
rec = store.get_destination(dest_id, with_secrets=True)
|
||||||
|
if not rec:
|
||||||
|
raise Invalid("Destination not found")
|
||||||
|
cls = destinations.DESTINATION_TYPES.get(rec["type"])
|
||||||
|
if not cls or not cls.PIN_PARAMS:
|
||||||
|
raise Invalid("This destination type has no host key")
|
||||||
|
if not destinations.FINGERPRINT_RE.match(fingerprint or ""):
|
||||||
|
raise Invalid("Invalid fingerprint")
|
||||||
|
shown, key_type = build_dest(rec).fetch_host_key()
|
||||||
|
if shown != fingerprint:
|
||||||
|
raise Invalid("The server now shows a different host key than the one you saw: run Test again")
|
||||||
|
params = dict(rec["params"], host_key=shown, host_key_type=key_type)
|
||||||
|
store.save_destination(rec["id"], rec["name"], rec["type"], rec["enabled"], rec["retention_count"],
|
||||||
|
params, rec["secrets"])
|
||||||
|
store.set_last_result(rec["id"], True, f"Host key {shown} trusted")
|
||||||
|
return store.get_destination(rec["id"])
|
||||||
|
|
||||||
|
|
||||||
|
def list_packages(dest_id: int) -> list:
|
||||||
|
"""Packages of our name pattern in the destination, newest first."""
|
||||||
|
rec = store.get_destination(dest_id, with_secrets=True)
|
||||||
|
if not rec:
|
||||||
|
raise Invalid("Destination not found")
|
||||||
|
items = []
|
||||||
|
for obj in build_dest(rec).list():
|
||||||
|
meta = package.parse_package_name(obj["name"])
|
||||||
|
if meta:
|
||||||
|
items.append({"name": obj["name"], "server_name": meta["host"], "created_at": meta["created_at"],
|
||||||
|
"encrypted": meta["encrypted"], "size": obj["size"],
|
||||||
|
"_key": (meta["stamp"], meta["seq"], obj["name"])})
|
||||||
|
items.sort(key=lambda i: i["_key"], reverse=True)
|
||||||
|
for i in items:
|
||||||
|
del i["_key"]
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def put_unique(dest: destinations.Destination, path: str, base_name: str) -> str:
|
||||||
|
"""Store the package under base_name, or under -2, -3 ... when the destination already has a
|
||||||
|
package of that second. Returns the name used."""
|
||||||
|
meta = package.parse_package_name(base_name)
|
||||||
|
name = package.unique_package_name(meta["host"], meta["stamp"], meta["encrypted"],
|
||||||
|
(o["name"] for o in dest.list()))
|
||||||
|
dest.put(path, name)
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
def rotate(dest: destinations.Destination, keep: int, keep_name: str, server_name: str) -> int:
|
||||||
|
"""Delete the oldest packages of this server name beyond `keep` (never keep_name). Packages
|
||||||
|
with another name in the same folder (other servers, or made under an earlier name or by host
|
||||||
|
name) are not ours to delete. Returns the number removed."""
|
||||||
|
mine = []
|
||||||
|
for obj in dest.list():
|
||||||
|
meta = package.parse_package_name(obj["name"])
|
||||||
|
if meta and meta["host"] == server_name:
|
||||||
|
mine.append(((meta["stamp"], meta["seq"]), obj["name"]))
|
||||||
|
mine.sort(reverse=True)
|
||||||
|
removed = 0
|
||||||
|
for _key, name in mine[max(keep, 1):]:
|
||||||
|
if name != keep_name:
|
||||||
|
dest.delete(name)
|
||||||
|
removed += 1
|
||||||
|
return removed
|
||||||
|
|
||||||
|
|
||||||
|
# --- package creation ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
def create_package(work: str, passphrase: Optional[str]):
|
||||||
|
"""Build (and encrypt, if a passphrase is given) a package in `work`. Returns (path, name, manifest);
|
||||||
|
name is the plain name, a destination may add -2, -3 when that second is taken (put_unique)."""
|
||||||
|
stamp = package.utc_stamp()
|
||||||
|
server_name, _source = effective_server_name()
|
||||||
|
plain = os.path.join(work, "package.tar.gz")
|
||||||
|
manifest = package.build_package(plain, work, profiler_db_path(), monitor_db_path(),
|
||||||
|
pki_dir(), client_dir(), runtime(), server_name)
|
||||||
|
path = plain
|
||||||
|
if passphrase:
|
||||||
|
path = os.path.join(work, "package.enc")
|
||||||
|
crypto.encrypt_file(plain, path, passphrase)
|
||||||
|
os.remove(plain)
|
||||||
|
return path, package.package_name(server_name, stamp, bool(passphrase)), manifest
|
||||||
|
|
||||||
|
|
||||||
|
# --- backup job ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def start_backup(destination_ids: Optional[list] = None) -> None:
|
||||||
|
all_dests = store.list_destinations(with_secrets=True)
|
||||||
|
if destination_ids is None:
|
||||||
|
selected = [d for d in all_dests if d["enabled"]]
|
||||||
|
else:
|
||||||
|
by_id = {d["id"]: d for d in all_dests}
|
||||||
|
selected = []
|
||||||
|
for i in dict.fromkeys(destination_ids):
|
||||||
|
if i not in by_id:
|
||||||
|
raise Invalid(f"Destination {i} not found")
|
||||||
|
if not by_id[i]["enabled"]:
|
||||||
|
raise Invalid(f"Destination '{by_id[i]['name']}' is disabled")
|
||||||
|
selected.append(by_id[i])
|
||||||
|
if not selected:
|
||||||
|
raise Invalid("No destinations selected: add and enable a destination first")
|
||||||
|
if any(d["type"] in destinations.REMOTE_TYPES for d in selected) and not store.has_passphrase():
|
||||||
|
raise Invalid("A passphrase is required for remote destinations: set the encryption passphrase first")
|
||||||
|
passphrase = store.get_passphrase()
|
||||||
|
stages = ["package"] + (["encrypt"] if passphrase else []) + ["upload"]
|
||||||
|
results = [{"destination_id": d["id"], "name": d["name"], "type": d["type"], "state": "pending",
|
||||||
|
"message": None, "package": None} for d in selected]
|
||||||
|
_claim("backup", stages, results)
|
||||||
|
hist_id = store.history_start("backup")
|
||||||
|
threading.Thread(target=_backup_worker, args=(selected, passphrase, hist_id), daemon=True).start()
|
||||||
|
|
||||||
|
|
||||||
|
def _backup_worker(selected: list, passphrase: Optional[str], hist_id: int) -> None:
|
||||||
|
work = None
|
||||||
|
try:
|
||||||
|
work = _work_dir()
|
||||||
|
_stage("package")
|
||||||
|
# create_package encrypts too: show the second stage once the tar is written
|
||||||
|
path, name, manifest = create_package(work, passphrase)
|
||||||
|
if passphrase:
|
||||||
|
_stage("encrypt", "done")
|
||||||
|
_stage("upload")
|
||||||
|
size = os.path.getsize(path)
|
||||||
|
server_name = manifest["server_name"]
|
||||||
|
for i, rec in enumerate(selected):
|
||||||
|
_result(i, state="running")
|
||||||
|
try:
|
||||||
|
dest = build_dest(rec)
|
||||||
|
stored = put_unique(dest, path, name)
|
||||||
|
note = f"{stored} ({size // 1024} KB)"
|
||||||
|
try:
|
||||||
|
removed = rotate(dest, rec["retention_count"], stored, server_name)
|
||||||
|
if removed:
|
||||||
|
note += f", {removed} old removed"
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"[BACKUP] rotation failed for '{rec['name']}': {type(e).__name__}")
|
||||||
|
note += f", rotation failed: {str(e)[:150]}"
|
||||||
|
_result(i, state="ok", message=note, package=stored)
|
||||||
|
store.set_last_result(rec["id"], True, note)
|
||||||
|
except Exception as e:
|
||||||
|
msg = str(e)[:300] if isinstance(e, BackupError) else f"{type(e).__name__}: {str(e)[:200]}"
|
||||||
|
logger.error(f"[BACKUP] destination '{rec['name']}' failed: {msg}")
|
||||||
|
_result(i, state="error", message=msg)
|
||||||
|
store.set_last_result(rec["id"], False, msg)
|
||||||
|
with _lock:
|
||||||
|
results = copy.deepcopy(_job["results"])
|
||||||
|
ok = sum(1 for r in results if r["state"] == "ok")
|
||||||
|
if ok == len(results):
|
||||||
|
state, message = "done", f"Backup stored in {ok} destination(s)"
|
||||||
|
elif ok:
|
||||||
|
state, message = "partial", f"Backup stored in {ok} of {len(results)} destinations"
|
||||||
|
else:
|
||||||
|
state, message = "error", "Backup failed in every destination"
|
||||||
|
_finish(state, message)
|
||||||
|
store.history_finish(hist_id, state, message, results)
|
||||||
|
except Exception as e:
|
||||||
|
logger.exception("Backup failed")
|
||||||
|
message = str(e)[:500] if isinstance(e, BackupError) else f"Backup failed: {type(e).__name__}: {str(e)[:300]}"
|
||||||
|
for i in range(len(selected)):
|
||||||
|
_result(i, state="skipped", message="Package was not created")
|
||||||
|
_finish("error", message)
|
||||||
|
store.history_finish(hist_id, "error", message, [])
|
||||||
|
finally:
|
||||||
|
if work:
|
||||||
|
shutil.rmtree(work, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
# --- restore -------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
RESTORE_STAGES = ["download", "decrypt", "verify", "prepare", "safety_backup", "stop_openvpn",
|
||||||
|
"replace", "finalize"]
|
||||||
|
|
||||||
|
|
||||||
|
def start_restore(destination_id: int, package_name: str, passphrase: Optional[str]) -> None:
|
||||||
|
rec = store.get_destination(destination_id, with_secrets=True)
|
||||||
|
if not rec:
|
||||||
|
raise Invalid("Destination not found")
|
||||||
|
meta = package.parse_package_name(package_name)
|
||||||
|
if not meta:
|
||||||
|
raise Invalid("Invalid package name")
|
||||||
|
if meta["encrypted"] and not passphrase:
|
||||||
|
raise Invalid("The package is encrypted: enter its passphrase")
|
||||||
|
if pki.is_init_running():
|
||||||
|
raise Busy("PKI initialization is running")
|
||||||
|
if is_running():
|
||||||
|
raise Busy(f"A {status()['kind']} is already running")
|
||||||
|
# Only names from the destination's listing are restored
|
||||||
|
if package_name not in {o["name"] for o in build_dest(rec).list()}:
|
||||||
|
raise Invalid("The package is not in the destination")
|
||||||
|
stages = [s for s in RESTORE_STAGES if s != "decrypt" or meta["encrypted"]]
|
||||||
|
_claim("restore", stages, [{"destination_id": rec["id"], "name": rec["name"], "type": rec["type"],
|
||||||
|
"state": "running", "message": None, "package": package_name}])
|
||||||
|
pki.set_restore_running(True)
|
||||||
|
hist_id = store.history_start("restore")
|
||||||
|
threading.Thread(target=_restore_worker, args=(rec, package_name, meta["encrypted"], passphrase, hist_id),
|
||||||
|
daemon=True).start()
|
||||||
|
|
||||||
|
|
||||||
|
def core_dir() -> Optional[str]:
|
||||||
|
"""Directory of the monitoring component (it owns the migrations of openvpn_monitor.db):
|
||||||
|
migrate.py with migrations.py and db.py (standard library only).
|
||||||
|
OVPMON_CORE_DIR (profiler image: /opt/core), else APP_CORE next to APP_PROFILER (system
|
||||||
|
services, all-in-one container). None for an old profiler image without that directory."""
|
||||||
|
env = os.environ.get("OVPMON_CORE_DIR", "").strip()
|
||||||
|
if not env:
|
||||||
|
code = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
env = os.path.join(os.path.dirname(code), "APP_CORE")
|
||||||
|
if all(os.path.isfile(os.path.join(env, f)) for f in ("migrate.py", "migrations.py", "db.py")):
|
||||||
|
return env
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _migrate_monitor(db_file: str) -> None:
|
||||||
|
"""Bring the monitoring database of the package up to this release's schema.
|
||||||
|
|
||||||
|
The migrations live in the monitoring component, which this process cannot import (separate
|
||||||
|
virtualenv). Its own migrate.py runs on the staged copy with the interpreter of APP_CORE/venv
|
||||||
|
(or this one: the code uses the standard library only). Without the code on disk (an old
|
||||||
|
profiler image) only a package with exactly the schema of the running monitoring database is
|
||||||
|
accepted: the monitoring services would otherwise read an unmigrated database."""
|
||||||
|
version = package.schema_version(db_file)
|
||||||
|
core = core_dir()
|
||||||
|
if core:
|
||||||
|
venv_python = os.path.join(core, "venv", "bin", "python")
|
||||||
|
python = venv_python if os.path.isfile(venv_python) else sys.executable
|
||||||
|
try:
|
||||||
|
r = subprocess.run([python, "migrate.py", "--db", db_file], cwd=core, capture_output=True,
|
||||||
|
text=True, timeout=300)
|
||||||
|
except (OSError, subprocess.TimeoutExpired) as e:
|
||||||
|
raise BackupError(f"Cannot run the monitoring database migration: {e}") from e
|
||||||
|
if r.returncode != 0:
|
||||||
|
lines = [ln for ln in (r.stderr or r.stdout or "").strip().splitlines() if ln.strip()]
|
||||||
|
raise BackupError("The monitoring database of the package cannot be migrated: "
|
||||||
|
+ (lines[-1][:300] if lines else f"exit code {r.returncode}"))
|
||||||
|
return
|
||||||
|
live = package.schema_version(monitor_db_path())
|
||||||
|
if not live:
|
||||||
|
raise BackupError("The monitoring database schema cannot be checked: the monitoring component "
|
||||||
|
"is not available to this service and its database is not initialized")
|
||||||
|
if version != live:
|
||||||
|
which = "newer" if (version or 0) > live else "older"
|
||||||
|
raise BackupError(
|
||||||
|
f"The package has a {which} monitoring database schema ({version}) than this installation "
|
||||||
|
f"({live}). The migration code of the monitoring component (OVPMON_CORE_DIR) is not "
|
||||||
|
f"available to this service. Rebuild the profiler image or restore on the same release.")
|
||||||
|
|
||||||
|
|
||||||
|
def _prepare_staged(extracted: str, manifest: dict) -> None:
|
||||||
|
"""Checks and migrations on the unpacked copies: nothing of the running system is touched yet."""
|
||||||
|
prof = os.path.join(extracted, package.DB_PROFILER)
|
||||||
|
mon = os.path.join(extracted, package.DB_MONITOR)
|
||||||
|
for path in (prof, mon):
|
||||||
|
if not package.integrity_ok(path):
|
||||||
|
raise BackupError(f"{os.path.basename(path)} in the package failed the integrity check")
|
||||||
|
version, latest = package.schema_version(prof), migrations.latest_version()
|
||||||
|
if version is None or version > latest:
|
||||||
|
raise BackupError(f"The package was made by a newer release (profiler database schema {version}, "
|
||||||
|
f"this release knows up to {latest}). Update this installation first.")
|
||||||
|
try:
|
||||||
|
migrations.run(prof)
|
||||||
|
except migrations.MigrationError as e:
|
||||||
|
raise BackupError(f"The profiler database of the package cannot be migrated: {str(e)[:300]}") from e
|
||||||
|
_migrate_monitor(mon)
|
||||||
|
|
||||||
|
|
||||||
|
def _safety_backup() -> str:
|
||||||
|
"""Package of the current state in the local pre-restore folder. Raises when it cannot be made."""
|
||||||
|
try:
|
||||||
|
passphrase = store.get_passphrase()
|
||||||
|
except BackupError:
|
||||||
|
passphrase = None
|
||||||
|
_warn("The safety copy is not encrypted: the stored passphrase cannot be decrypted")
|
||||||
|
work = _work_dir()
|
||||||
|
try:
|
||||||
|
path, name, manifest = create_package(work, passphrase)
|
||||||
|
dest = destinations.LocalDestination({"folder": PRE_RESTORE_FOLDER}, {})
|
||||||
|
name = put_unique(dest, path, name)
|
||||||
|
try:
|
||||||
|
rotate(dest, PRE_RESTORE_KEEP, name, manifest["server_name"])
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"[BACKUP] pre-restore rotation failed: {type(e).__name__}")
|
||||||
|
return name
|
||||||
|
finally:
|
||||||
|
shutil.rmtree(work, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _replace_db(target: str, new_file: str, tag: str, undo: list) -> None:
|
||||||
|
"""Atomic replacement of a database file. The old file (and its -wal/-shm) is kept under a
|
||||||
|
.old-<tag> name until the whole restore succeeded."""
|
||||||
|
tmp = f"{target}.restore-{tag}"
|
||||||
|
old = f"{target}.old-{tag}"
|
||||||
|
shutil.copyfile(new_file, tmp)
|
||||||
|
os.chmod(tmp, (os.stat(target).st_mode & 0o777) if os.path.exists(target) else 0o600)
|
||||||
|
if os.path.exists(target):
|
||||||
|
try:
|
||||||
|
os.link(target, old)
|
||||||
|
except OSError:
|
||||||
|
shutil.copy2(target, old)
|
||||||
|
undo.append(("db", target, old))
|
||||||
|
# A leftover journal of the old database must never be applied to the new file
|
||||||
|
for suffix in ("-wal", "-shm"):
|
||||||
|
if os.path.exists(target + suffix):
|
||||||
|
os.replace(target + suffix, old + suffix)
|
||||||
|
else:
|
||||||
|
undo.append(("db_new", target, old))
|
||||||
|
os.replace(tmp, target)
|
||||||
|
|
||||||
|
|
||||||
|
def _swap_dir(target: str, extracted: str, tag: str, undo: list) -> None:
|
||||||
|
"""Replace the CONTENT of a directory (the directory itself may be a volume mount point):
|
||||||
|
old entries move into .restore-old-<tag>, new ones come from .restore-new-<tag>."""
|
||||||
|
os.makedirs(target, mode=0o700, exist_ok=True)
|
||||||
|
staged = os.path.join(target, f".restore-new-{tag}")
|
||||||
|
old = os.path.join(target, f".restore-old-{tag}")
|
||||||
|
if os.path.isdir(extracted):
|
||||||
|
shutil.copytree(extracted, staged)
|
||||||
|
else:
|
||||||
|
os.mkdir(staged, 0o700)
|
||||||
|
os.mkdir(old, 0o700)
|
||||||
|
undo.append(("dir", target, old, staged))
|
||||||
|
for name in os.listdir(target):
|
||||||
|
if not name.startswith(".restore-"):
|
||||||
|
os.replace(os.path.join(target, name), os.path.join(old, name))
|
||||||
|
for name in os.listdir(staged):
|
||||||
|
os.replace(os.path.join(staged, name), os.path.join(target, name))
|
||||||
|
os.rmdir(staged)
|
||||||
|
|
||||||
|
|
||||||
|
def _remove(path: str) -> None:
|
||||||
|
if os.path.isdir(path) and not os.path.islink(path):
|
||||||
|
shutil.rmtree(path, ignore_errors=True)
|
||||||
|
elif os.path.lexists(path):
|
||||||
|
os.remove(path)
|
||||||
|
|
||||||
|
|
||||||
|
def _rollback(undo: list) -> None:
|
||||||
|
for item in reversed(undo):
|
||||||
|
try:
|
||||||
|
if item[0] == "db":
|
||||||
|
_, target, old = item
|
||||||
|
for suffix in ("", "-wal", "-shm"):
|
||||||
|
if os.path.exists(old + suffix):
|
||||||
|
os.replace(old + suffix, target + suffix)
|
||||||
|
elif item[0] == "db_new":
|
||||||
|
_remove(item[1])
|
||||||
|
else:
|
||||||
|
_, target, old, staged = item
|
||||||
|
for name in os.listdir(target):
|
||||||
|
if not name.startswith(".restore-"):
|
||||||
|
_remove(os.path.join(target, name))
|
||||||
|
for name in os.listdir(old):
|
||||||
|
os.replace(os.path.join(old, name), os.path.join(target, name))
|
||||||
|
shutil.rmtree(old, ignore_errors=True)
|
||||||
|
shutil.rmtree(staged, ignore_errors=True)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("[BACKUP] rollback step failed")
|
||||||
|
|
||||||
|
|
||||||
|
def _commit(undo: list) -> None:
|
||||||
|
for item in undo:
|
||||||
|
if item[0] == "db":
|
||||||
|
for suffix in ("", "-wal", "-shm"):
|
||||||
|
if os.path.lexists(item[2] + suffix):
|
||||||
|
_remove(item[2] + suffix)
|
||||||
|
elif item[0] == "dir":
|
||||||
|
shutil.rmtree(item[2], ignore_errors=True)
|
||||||
|
shutil.rmtree(item[3], ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_server_config() -> bool:
|
||||||
|
"""Regenerate server.conf and publish the CRL through the same code as POST /server/configure."""
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from routers import server as server_router
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
server_router.configure_server(db)
|
||||||
|
return True
|
||||||
|
except HTTPException as e:
|
||||||
|
_warn(f"server.conf was not regenerated: {e.detail}")
|
||||||
|
except Exception as e:
|
||||||
|
_warn(f"server.conf was not regenerated: {type(e).__name__}: {str(e)[:200]}")
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _start_openvpn(was_running: bool) -> None:
|
||||||
|
if not was_running:
|
||||||
|
return
|
||||||
|
res = process.control_service("start")
|
||||||
|
if res.get("status") == "error":
|
||||||
|
_warn(f"OpenVPN was running before the restore, but could not be started: {res.get('message')}")
|
||||||
|
|
||||||
|
|
||||||
|
def _restore_worker(rec: dict, name: str, encrypted: bool, passphrase: Optional[str], hist_id: int) -> None:
|
||||||
|
work = None
|
||||||
|
undo = []
|
||||||
|
was_running = False
|
||||||
|
stopped = False
|
||||||
|
committed = False
|
||||||
|
try:
|
||||||
|
work = _work_dir()
|
||||||
|
downloaded = os.path.join(work, "downloaded")
|
||||||
|
_stage("download")
|
||||||
|
build_dest(rec).get(name, downloaded)
|
||||||
|
|
||||||
|
archive = downloaded
|
||||||
|
if encrypted:
|
||||||
|
_stage("decrypt")
|
||||||
|
archive = os.path.join(work, "package.tar.gz")
|
||||||
|
crypto.decrypt_file(downloaded, archive, passphrase)
|
||||||
|
os.remove(downloaded)
|
||||||
|
elif crypto.is_encrypted(downloaded):
|
||||||
|
raise BackupError("The package is encrypted but its name says it is not")
|
||||||
|
|
||||||
|
_stage("verify")
|
||||||
|
extracted = os.path.join(work, "extracted")
|
||||||
|
manifest = package.safe_extract(archive, extracted)
|
||||||
|
os.remove(archive)
|
||||||
|
|
||||||
|
_stage("prepare")
|
||||||
|
_prepare_staged(extracted, manifest)
|
||||||
|
|
||||||
|
_stage("safety_backup")
|
||||||
|
safety = _safety_backup()
|
||||||
|
|
||||||
|
_stage("stop_openvpn")
|
||||||
|
was_running = process.get_process_stats().get("status") == "running"
|
||||||
|
if was_running:
|
||||||
|
res = process.control_service("stop")
|
||||||
|
if res.get("status") == "error":
|
||||||
|
raise BackupError(f"Cannot stop OpenVPN: {res.get('message')}")
|
||||||
|
stopped = True
|
||||||
|
|
||||||
|
_stage("replace")
|
||||||
|
tag = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
|
||||||
|
try:
|
||||||
|
sa_engine.dispose()
|
||||||
|
_swap_dir(pki_dir(), os.path.join(extracted, "pki"), tag, undo)
|
||||||
|
_swap_dir(client_dir(), os.path.join(extracted, "client-config"), tag, undo)
|
||||||
|
_replace_db(monitor_db_path(), os.path.join(extracted, package.DB_MONITOR), tag, undo)
|
||||||
|
_replace_db(profiler_db_path(), os.path.join(extracted, package.DB_PROFILER), tag, undo)
|
||||||
|
marker = pki._marker_path()
|
||||||
|
if os.path.exists(marker):
|
||||||
|
os.remove(marker)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("[BACKUP] replacement failed, rolling back")
|
||||||
|
_rollback(undo)
|
||||||
|
sa_engine.dispose()
|
||||||
|
raise
|
||||||
|
_commit(undo)
|
||||||
|
committed = True
|
||||||
|
sa_engine.dispose()
|
||||||
|
|
||||||
|
_stage("finalize")
|
||||||
|
configured = _apply_server_config()
|
||||||
|
if configured:
|
||||||
|
_start_openvpn(was_running)
|
||||||
|
elif was_running:
|
||||||
|
_warn("OpenVPN was running before the restore and was not started")
|
||||||
|
message = f"Restored from {name}. The previous state is saved as {PRE_RESTORE_FOLDER}/{safety}"
|
||||||
|
_result(0, state="ok", message=message)
|
||||||
|
_finish("done", message, relogin=True)
|
||||||
|
store.history_finish(hist_id, "done", message, status()["results"])
|
||||||
|
except Exception as e:
|
||||||
|
logger.exception("Restore failed")
|
||||||
|
message = str(e)[:500] if isinstance(e, BackupError) else f"Restore failed: {type(e).__name__}: {str(e)[:300]}"
|
||||||
|
if committed:
|
||||||
|
message += ". The data was restored, but the final steps failed (see the log)."
|
||||||
|
else:
|
||||||
|
message += ". Nothing was changed." if not undo else ". The previous state was put back."
|
||||||
|
if stopped:
|
||||||
|
try:
|
||||||
|
_start_openvpn(True)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("[BACKUP] OpenVPN start after a failed restore")
|
||||||
|
_result(0, state="error", message=message)
|
||||||
|
_finish("error", message)
|
||||||
|
store.history_finish(hist_id, "error", message, status()["results"])
|
||||||
|
finally:
|
||||||
|
pki.set_restore_running(False)
|
||||||
|
if work:
|
||||||
|
shutil.rmtree(work, ignore_errors=True)
|
||||||
@@ -0,0 +1,335 @@
|
|||||||
|
"""Backup package: naming, building (snapshots), reading and safe extraction.
|
||||||
|
|
||||||
|
A package is a tar.gz named ovpmon-backup_<server-name>_<YYYYMMDDTHHMMSS>Z.ovpbak (plus .enc when
|
||||||
|
encrypted; -2, -3 after the Z when several packages are made in the same second) with this content:
|
||||||
|
db/openvpn_monitor.db, db/ovpn_profiler.db consistent online snapshots (sqlite3 backup API)
|
||||||
|
pki/... the easy-rsa PKI directory
|
||||||
|
client-config/*.ovpn issued client profiles
|
||||||
|
manifest.json format version, server name, schema versions, SHA-256 of every file
|
||||||
|
"""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import socket
|
||||||
|
import sqlite3
|
||||||
|
import stat
|
||||||
|
import tarfile
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from . import BackupError
|
||||||
|
|
||||||
|
FORMAT_NAME = "ovpmon-backup"
|
||||||
|
FORMAT_VERSION = 1
|
||||||
|
MANIFEST = "manifest.json"
|
||||||
|
DB_MONITOR = "db/openvpn_monitor.db"
|
||||||
|
DB_PROFILER = "db/ovpn_profiler.db"
|
||||||
|
TOP_LEVEL = {"db", "pki", "client-config", MANIFEST} # allowlist of top-level names
|
||||||
|
|
||||||
|
SERVER_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9.-]{0,62}$")
|
||||||
|
# Packages of the first pass carry the host name in the same place; they match too
|
||||||
|
PACKAGE_RE = re.compile(
|
||||||
|
r"^ovpmon-backup_(?P<host>[A-Za-z0-9][A-Za-z0-9.-]{0,62})_(?P<ts>\d{8}T\d{6}Z)(?:-(?P<seq>\d{1,3}))?"
|
||||||
|
r"\.ovpbak(?P<enc>\.enc)?$")
|
||||||
|
|
||||||
|
MAX_FILES = 200000
|
||||||
|
MAX_UNPACKED = int(os.environ.get("OVPMON_BACKUP_MAX_UNPACKED_BYTES", str(20 * 1024 ** 3)))
|
||||||
|
MAX_MANIFEST = 64 * 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
|
def sanitize_name(text: str) -> str:
|
||||||
|
"""Make a server name of arbitrary text (host name, address); empty when nothing is left."""
|
||||||
|
name = re.sub(r"[^A-Za-z0-9.-]", "-", text or "")[:63].strip("-.")
|
||||||
|
return name if SERVER_NAME_RE.match(name) else ""
|
||||||
|
|
||||||
|
|
||||||
|
def host_name() -> str:
|
||||||
|
return sanitize_name(socket.gethostname()) or "host"
|
||||||
|
|
||||||
|
|
||||||
|
def utc_stamp(now=None) -> str:
|
||||||
|
return (now or datetime.now(timezone.utc)).strftime("%Y%m%dT%H%M%SZ")
|
||||||
|
|
||||||
|
|
||||||
|
def package_name(server: str, stamp: str, encrypted: bool, seq: int = 1) -> str:
|
||||||
|
return (f"ovpmon-backup_{server}_{stamp}" + (f"-{seq}" if seq > 1 else "")
|
||||||
|
+ ".ovpbak" + (".enc" if encrypted else ""))
|
||||||
|
|
||||||
|
|
||||||
|
def unique_package_name(server: str, stamp: str, encrypted: bool, existing) -> str:
|
||||||
|
"""The name for a new package: the plain one, or with -2, -3 ... when the destination already
|
||||||
|
holds a package of the same second. An existing file is never overwritten."""
|
||||||
|
taken = set(existing)
|
||||||
|
for seq in range(1, 1000):
|
||||||
|
name = package_name(server, stamp, encrypted, seq)
|
||||||
|
if name not in taken:
|
||||||
|
return name
|
||||||
|
raise BackupError("Too many packages with the same time stamp in the destination")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_package_name(name: str):
|
||||||
|
"""{'host' (server name),'created_at' (ISO UTC),'encrypted','stamp','seq'} or None when the name is not ours."""
|
||||||
|
m = PACKAGE_RE.match(name or "")
|
||||||
|
if not m:
|
||||||
|
return None
|
||||||
|
ts = datetime.strptime(m.group("ts"), "%Y%m%dT%H%M%SZ").replace(tzinfo=timezone.utc)
|
||||||
|
return {"host": m.group("host"), "created_at": ts.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||||
|
"encrypted": bool(m.group("enc")), "stamp": m.group("ts"), "seq": int(m.group("seq") or 1)}
|
||||||
|
|
||||||
|
|
||||||
|
# --- SQLite helpers ------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def schema_version(db_path: str):
|
||||||
|
"""Highest applied migration of a database (0: no migrations table), None if unreadable."""
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=30)
|
||||||
|
try:
|
||||||
|
has = conn.execute(
|
||||||
|
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='schema_migrations'").fetchone()
|
||||||
|
if not has:
|
||||||
|
return 0
|
||||||
|
return conn.execute("SELECT COALESCE(MAX(version), 0) FROM schema_migrations").fetchone()[0]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
except sqlite3.Error:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def integrity_ok(db_path: str) -> bool:
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=30)
|
||||||
|
try:
|
||||||
|
return [r[0] for r in conn.execute("PRAGMA integrity_check")] == ["ok"]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
except sqlite3.Error:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def snapshot_db(src_path: str, dst_path: str) -> None:
|
||||||
|
"""Consistent copy of a live database (online backup API); the copy is a single file
|
||||||
|
(journal mode DELETE), so no -wal/-shm files belong to it."""
|
||||||
|
if not os.path.isfile(src_path):
|
||||||
|
raise BackupError(f"Database not found: {os.path.basename(src_path)}")
|
||||||
|
src = sqlite3.connect(f"file:{src_path}?mode=ro", uri=True, timeout=60)
|
||||||
|
dst = sqlite3.connect(dst_path)
|
||||||
|
try:
|
||||||
|
src.backup(dst)
|
||||||
|
dst.execute("PRAGMA journal_mode=DELETE")
|
||||||
|
dst.commit()
|
||||||
|
except sqlite3.Error as e:
|
||||||
|
raise BackupError(f"Cannot snapshot {os.path.basename(src_path)}: {e}") from e
|
||||||
|
finally:
|
||||||
|
src.close()
|
||||||
|
dst.close()
|
||||||
|
os.chmod(dst_path, 0o600)
|
||||||
|
|
||||||
|
|
||||||
|
# --- building ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _copy_tree_regular(src: str, dst: str) -> int:
|
||||||
|
"""Copy regular files and directories only (links and special files are skipped). Returns file count."""
|
||||||
|
count = 0
|
||||||
|
os.makedirs(dst, mode=0o700, exist_ok=True)
|
||||||
|
for root, dirs, files in os.walk(src, followlinks=False):
|
||||||
|
rel = os.path.relpath(root, src)
|
||||||
|
target = dst if rel == "." else os.path.join(dst, rel)
|
||||||
|
os.makedirs(target, mode=0o700, exist_ok=True)
|
||||||
|
dirs[:] = [d for d in dirs if not os.path.islink(os.path.join(root, d))]
|
||||||
|
for name in files:
|
||||||
|
path = os.path.join(root, name)
|
||||||
|
st = os.lstat(path)
|
||||||
|
if not stat.S_ISREG(st.st_mode):
|
||||||
|
continue
|
||||||
|
out = os.path.join(target, name)
|
||||||
|
shutil.copyfile(path, out)
|
||||||
|
os.chmod(out, stat.S_IMODE(st.st_mode) & 0o777)
|
||||||
|
count += 1
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
def _sha256(path: str) -> str:
|
||||||
|
h = hashlib.sha256()
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
for block in iter(lambda: f.read(1024 * 1024), b""):
|
||||||
|
h.update(block)
|
||||||
|
return h.hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def build_package(out_path: str, work_dir: str, profiler_db: str, monitor_db: str,
|
||||||
|
pki_dir: str, client_dir: str, runtime: str, server_name: str = "") -> dict:
|
||||||
|
"""Write the (not encrypted) package tar.gz to out_path. Returns the manifest."""
|
||||||
|
stage = os.path.join(work_dir, "stage")
|
||||||
|
os.makedirs(os.path.join(stage, "db"), mode=0o700)
|
||||||
|
snapshot_db(profiler_db, os.path.join(stage, DB_PROFILER))
|
||||||
|
snapshot_db(monitor_db, os.path.join(stage, DB_MONITOR))
|
||||||
|
if os.path.isdir(pki_dir):
|
||||||
|
_copy_tree_regular(pki_dir, os.path.join(stage, "pki"))
|
||||||
|
else:
|
||||||
|
os.makedirs(os.path.join(stage, "pki"), mode=0o700)
|
||||||
|
if os.path.isdir(client_dir):
|
||||||
|
for name in sorted(os.listdir(client_dir)):
|
||||||
|
path = os.path.join(client_dir, name)
|
||||||
|
if name.endswith(".ovpn") and os.path.isfile(path) and not os.path.islink(path):
|
||||||
|
os.makedirs(os.path.join(stage, "client-config"), mode=0o700, exist_ok=True)
|
||||||
|
shutil.copyfile(path, os.path.join(stage, "client-config", name))
|
||||||
|
os.makedirs(os.path.join(stage, "client-config"), mode=0o700, exist_ok=True)
|
||||||
|
|
||||||
|
files = {}
|
||||||
|
for root, _dirs, names in os.walk(stage):
|
||||||
|
for name in names:
|
||||||
|
path = os.path.join(root, name)
|
||||||
|
arc = os.path.relpath(path, stage).replace(os.sep, "/")
|
||||||
|
files[arc] = {"sha256": _sha256(path), "size": os.path.getsize(path),
|
||||||
|
"mode": stat.S_IMODE(os.stat(path).st_mode) & 0o777}
|
||||||
|
profiles = 0
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(os.path.join(stage, DB_PROFILER))
|
||||||
|
try:
|
||||||
|
profiles = conn.execute("SELECT COUNT(*) FROM user_profiles").fetchone()[0]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
except sqlite3.Error:
|
||||||
|
pass
|
||||||
|
manifest = {
|
||||||
|
"format": FORMAT_NAME,
|
||||||
|
"format_version": FORMAT_VERSION,
|
||||||
|
"created_at": datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
|
||||||
|
"server_name": server_name or host_name(),
|
||||||
|
"hostname": socket.gethostname(),
|
||||||
|
"runtime": runtime,
|
||||||
|
"schema": {"profiler": schema_version(os.path.join(stage, DB_PROFILER)),
|
||||||
|
"monitor": schema_version(os.path.join(stage, DB_MONITOR))},
|
||||||
|
"profiles": profiles,
|
||||||
|
"files": files,
|
||||||
|
}
|
||||||
|
manifest_path = os.path.join(stage, MANIFEST)
|
||||||
|
with open(manifest_path, "w") as f:
|
||||||
|
json.dump(manifest, f, indent=1, sort_keys=True)
|
||||||
|
|
||||||
|
fd = os.open(out_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as raw, tarfile.open(fileobj=raw, mode="w:gz") as tar:
|
||||||
|
# Directories first (so empty ones survive), then files; fixed owner, no time-dependent names
|
||||||
|
entries = []
|
||||||
|
for root, dirs, names in os.walk(stage):
|
||||||
|
for name in dirs + names:
|
||||||
|
path = os.path.join(root, name)
|
||||||
|
entries.append((os.path.relpath(path, stage).replace(os.sep, "/"), path))
|
||||||
|
for arc, path in sorted(entries):
|
||||||
|
info = tar.gettarinfo(path, arcname=arc)
|
||||||
|
info.uid = info.gid = 0
|
||||||
|
info.uname = info.gname = ""
|
||||||
|
if info.isdir():
|
||||||
|
tar.addfile(info)
|
||||||
|
else:
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
tar.addfile(info, f)
|
||||||
|
shutil.rmtree(stage, ignore_errors=True)
|
||||||
|
return manifest
|
||||||
|
|
||||||
|
|
||||||
|
# --- reading and safe extraction -----------------------------------------------------------
|
||||||
|
|
||||||
|
def _check_member_name(name: str):
|
||||||
|
if not name or name.startswith("/") or "\\" in name or "\x00" in name:
|
||||||
|
raise BackupError(f"Unsafe path in package: {name!r}")
|
||||||
|
parts = name.split("/")
|
||||||
|
if any(p in ("", ".", "..") for p in parts):
|
||||||
|
raise BackupError(f"Unsafe path in package: {name!r}")
|
||||||
|
if parts[0] not in TOP_LEVEL:
|
||||||
|
raise BackupError(f"Unexpected entry in package: {name!r}")
|
||||||
|
if parts[0] == MANIFEST and len(parts) != 1:
|
||||||
|
raise BackupError(f"Unexpected entry in package: {name!r}")
|
||||||
|
if parts[0] == "db" and name not in ("db", DB_MONITOR, DB_PROFILER):
|
||||||
|
raise BackupError(f"Unexpected entry in package: {name!r}")
|
||||||
|
if parts[0] == "client-config" and len(parts) > 2:
|
||||||
|
raise BackupError(f"Unexpected entry in package: {name!r}")
|
||||||
|
if parts[0] == "client-config" and len(parts) == 2 and not parts[1].endswith(".ovpn"):
|
||||||
|
raise BackupError(f"Unexpected entry in package: {name!r}")
|
||||||
|
|
||||||
|
|
||||||
|
def safe_extract(package_path: str, dest: str) -> dict:
|
||||||
|
"""Extract an unencrypted package into the empty directory dest, checking every entry.
|
||||||
|
Only regular files and directories under the allowlisted names are accepted: absolute paths,
|
||||||
|
'..', links, devices and oversized content are rejected. Returns the verified manifest."""
|
||||||
|
os.makedirs(dest, mode=0o700, exist_ok=True)
|
||||||
|
base = os.path.realpath(dest)
|
||||||
|
total, count = 0, 0
|
||||||
|
try:
|
||||||
|
tar = tarfile.open(package_path, mode="r:gz")
|
||||||
|
except (tarfile.TarError, OSError, EOFError) as e:
|
||||||
|
raise BackupError(f"Cannot read the package: {e}") from e
|
||||||
|
try:
|
||||||
|
for member in tar:
|
||||||
|
count += 1
|
||||||
|
if count > MAX_FILES:
|
||||||
|
raise BackupError("Package has too many entries")
|
||||||
|
name = member.name.rstrip("/") if member.isdir() else member.name
|
||||||
|
_check_member_name(name)
|
||||||
|
if not (member.isreg() or member.isdir()):
|
||||||
|
raise BackupError(f"Package contains a link or special file: {name!r}")
|
||||||
|
target = os.path.realpath(os.path.join(base, name))
|
||||||
|
if target != base and not target.startswith(base + os.sep):
|
||||||
|
raise BackupError(f"Unsafe path in package: {name!r}")
|
||||||
|
if member.isdir():
|
||||||
|
os.makedirs(target, mode=0o700, exist_ok=True)
|
||||||
|
continue
|
||||||
|
if member.size < 0 or total + member.size > MAX_UNPACKED:
|
||||||
|
raise BackupError("Package is larger than the allowed unpacked size")
|
||||||
|
if name == MANIFEST and member.size > MAX_MANIFEST:
|
||||||
|
raise BackupError("Manifest is too large")
|
||||||
|
total += member.size
|
||||||
|
os.makedirs(os.path.dirname(target), mode=0o700, exist_ok=True)
|
||||||
|
src = tar.extractfile(member)
|
||||||
|
fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as out:
|
||||||
|
shutil.copyfileobj(src, out)
|
||||||
|
os.chmod(target, member.mode & 0o777 & ~0o7000)
|
||||||
|
except (tarfile.TarError, OSError, EOFError) as e:
|
||||||
|
if isinstance(e, FileExistsError):
|
||||||
|
raise BackupError("Package contains duplicate entries") from e
|
||||||
|
raise BackupError(f"Package is damaged or cannot be unpacked: {e}") from e
|
||||||
|
finally:
|
||||||
|
tar.close()
|
||||||
|
return verify_extracted(dest)
|
||||||
|
|
||||||
|
|
||||||
|
def verify_extracted(dest: str) -> dict:
|
||||||
|
"""Read manifest.json and check that the extracted files are exactly the listed ones with the
|
||||||
|
listed sizes and SHA-256 sums. Returns the manifest."""
|
||||||
|
path = os.path.join(dest, MANIFEST)
|
||||||
|
if not os.path.isfile(path):
|
||||||
|
raise BackupError("Package has no manifest.json")
|
||||||
|
try:
|
||||||
|
with open(path) as f:
|
||||||
|
manifest = json.load(f)
|
||||||
|
files = manifest["files"]
|
||||||
|
fmt, version = manifest["format"], manifest["format_version"]
|
||||||
|
manifest["schema"]["profiler"], manifest["schema"]["monitor"]
|
||||||
|
except (ValueError, KeyError, TypeError) as e:
|
||||||
|
raise BackupError("Package manifest is invalid") from e
|
||||||
|
if fmt != FORMAT_NAME or not isinstance(version, int) or version > FORMAT_VERSION or version < 1:
|
||||||
|
raise BackupError(f"Unknown package format (format_version {version!r}); "
|
||||||
|
f"this release reads format {FORMAT_VERSION}")
|
||||||
|
if not isinstance(files, dict):
|
||||||
|
raise BackupError("Package manifest is invalid")
|
||||||
|
present = set()
|
||||||
|
for root, _dirs, names in os.walk(dest):
|
||||||
|
for name in names:
|
||||||
|
rel = os.path.relpath(os.path.join(root, name), dest).replace(os.sep, "/")
|
||||||
|
if rel != MANIFEST:
|
||||||
|
present.add(rel)
|
||||||
|
if present != set(files):
|
||||||
|
extra, missing = sorted(present - set(files)), sorted(set(files) - present)
|
||||||
|
raise BackupError("Package content does not match the manifest"
|
||||||
|
+ (f" (not listed: {extra[0]})" if extra else "")
|
||||||
|
+ (f" (missing: {missing[0]})" if missing else ""))
|
||||||
|
for rel, meta in files.items():
|
||||||
|
full = os.path.join(dest, rel)
|
||||||
|
if os.path.getsize(full) != meta.get("size") or _sha256(full) != meta.get("sha256"):
|
||||||
|
raise BackupError(f"Checksum mismatch: {rel}. The package is damaged")
|
||||||
|
for required in (DB_PROFILER, DB_MONITOR):
|
||||||
|
if required not in files:
|
||||||
|
raise BackupError(f"Package has no {required}")
|
||||||
|
return manifest
|
||||||
@@ -0,0 +1,252 @@
|
|||||||
|
"""Settings, destinations and history of the backup feature.
|
||||||
|
|
||||||
|
A separate SQLite file (ovpmon_backup.db) next to the profiler database. A restore replaces
|
||||||
|
ovpn_profiler.db and openvpn_monitor.db, but never this file, so the destinations survive it and
|
||||||
|
never travel inside a package. The schema is created at service start (own version table, the
|
||||||
|
migrations of the two application databases are not involved).
|
||||||
|
|
||||||
|
Secrets (destination keys, the package passphrase) are encrypted at rest with a key derived
|
||||||
|
(HKDF-SHA256) from the JWT signing key. They are never returned by the API and never logged.
|
||||||
|
If the JWT key changes they cannot be decrypted any more and have to be entered again.
|
||||||
|
"""
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import threading
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from cryptography.fernet import Fernet, InvalidToken
|
||||||
|
from cryptography.hazmat.primitives import hashes
|
||||||
|
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
||||||
|
|
||||||
|
from . import BackupError
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
SCHEMA_VERSION = 1
|
||||||
|
DEFAULT_RETENTION = 14
|
||||||
|
HISTORY_KEEP = 100
|
||||||
|
MASK = "********"
|
||||||
|
|
||||||
|
_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def db_file() -> str:
|
||||||
|
from database import db_path
|
||||||
|
return os.path.join(os.path.dirname(os.path.abspath(db_path)), "ovpmon_backup.db")
|
||||||
|
|
||||||
|
|
||||||
|
def _now() -> str:
|
||||||
|
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _conn():
|
||||||
|
conn = sqlite3.connect(db_file(), timeout=30)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
try:
|
||||||
|
yield conn
|
||||||
|
conn.commit()
|
||||||
|
except BaseException:
|
||||||
|
conn.rollback()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def init() -> None:
|
||||||
|
"""Create the schema (idempotent). Called at service start."""
|
||||||
|
path = db_file()
|
||||||
|
new = not os.path.exists(path)
|
||||||
|
with _lock, _conn() as c:
|
||||||
|
c.execute("CREATE TABLE IF NOT EXISTS backup_schema (version INTEGER NOT NULL)")
|
||||||
|
c.execute("CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT)")
|
||||||
|
c.execute("""CREATE TABLE IF NOT EXISTS destinations (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL UNIQUE,
|
||||||
|
type TEXT NOT NULL,
|
||||||
|
enabled INTEGER NOT NULL DEFAULT 1,
|
||||||
|
retention_count INTEGER NOT NULL DEFAULT 14,
|
||||||
|
params TEXT NOT NULL DEFAULT '{}',
|
||||||
|
secrets_enc TEXT NOT NULL DEFAULT '',
|
||||||
|
last_status TEXT,
|
||||||
|
last_message TEXT,
|
||||||
|
last_at TEXT,
|
||||||
|
created_at TEXT NOT NULL)""")
|
||||||
|
c.execute("""CREATE TABLE IF NOT EXISTS history (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
kind TEXT NOT NULL,
|
||||||
|
state TEXT NOT NULL,
|
||||||
|
started_at TEXT NOT NULL,
|
||||||
|
finished_at TEXT,
|
||||||
|
message TEXT,
|
||||||
|
results TEXT NOT NULL DEFAULT '[]')""")
|
||||||
|
if not c.execute("SELECT 1 FROM backup_schema").fetchone():
|
||||||
|
c.execute("INSERT INTO backup_schema (version) VALUES (?)", (SCHEMA_VERSION,))
|
||||||
|
# A job that was running when the service stopped did not finish
|
||||||
|
c.execute("UPDATE history SET state='interrupted', finished_at=? WHERE state='running'", (_now(),))
|
||||||
|
if new:
|
||||||
|
os.chmod(path, 0o600)
|
||||||
|
|
||||||
|
|
||||||
|
# --- secrets -------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _fernet() -> Fernet:
|
||||||
|
from utils.auth import SECRET_KEY
|
||||||
|
key = HKDF(algorithm=hashes.SHA256(), length=32, salt=None,
|
||||||
|
info=b"ovpmon-backup-secrets-v1").derive(SECRET_KEY.encode("utf-8"))
|
||||||
|
return Fernet(base64.urlsafe_b64encode(key))
|
||||||
|
|
||||||
|
|
||||||
|
def encrypt_text(text: str) -> str:
|
||||||
|
return _fernet().encrypt(text.encode("utf-8")).decode("ascii")
|
||||||
|
|
||||||
|
|
||||||
|
def decrypt_text(token: str) -> str:
|
||||||
|
try:
|
||||||
|
return _fernet().decrypt(token.encode("ascii")).decode("utf-8")
|
||||||
|
except (InvalidToken, ValueError):
|
||||||
|
raise BackupError("Stored secrets cannot be decrypted (the JWT secret changed). "
|
||||||
|
"Enter them again.") from None
|
||||||
|
|
||||||
|
|
||||||
|
# --- settings ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _get_setting(key):
|
||||||
|
with _conn() as c:
|
||||||
|
row = c.execute("SELECT value FROM settings WHERE key=?", (key,)).fetchone()
|
||||||
|
return row["value"] if row else None
|
||||||
|
|
||||||
|
|
||||||
|
def _set_setting(key, value):
|
||||||
|
with _lock, _conn() as c:
|
||||||
|
if value is None:
|
||||||
|
c.execute("DELETE FROM settings WHERE key=?", (key,))
|
||||||
|
else:
|
||||||
|
c.execute("INSERT INTO settings (key, value) VALUES (?, ?) "
|
||||||
|
"ON CONFLICT(key) DO UPDATE SET value=excluded.value", (key, value))
|
||||||
|
|
||||||
|
|
||||||
|
def has_passphrase() -> bool:
|
||||||
|
return bool(_get_setting("passphrase_enc"))
|
||||||
|
|
||||||
|
|
||||||
|
def get_passphrase():
|
||||||
|
"""The package passphrase, or None when none is set. Raises BackupError if it cannot be decrypted."""
|
||||||
|
token = _get_setting("passphrase_enc")
|
||||||
|
return decrypt_text(token) if token else None
|
||||||
|
|
||||||
|
|
||||||
|
def set_passphrase(value) -> None:
|
||||||
|
_set_setting("passphrase_enc", encrypt_text(value) if value else None)
|
||||||
|
|
||||||
|
|
||||||
|
def default_retention() -> int:
|
||||||
|
try:
|
||||||
|
return int(_get_setting("default_retention") or DEFAULT_RETENTION)
|
||||||
|
except ValueError:
|
||||||
|
return DEFAULT_RETENTION
|
||||||
|
|
||||||
|
|
||||||
|
def set_default_retention(n: int) -> None:
|
||||||
|
_set_setting("default_retention", str(int(n)))
|
||||||
|
|
||||||
|
|
||||||
|
def get_server_name() -> str:
|
||||||
|
"""The server name set by the administrator ('' when none). Lives here, not in the profiler
|
||||||
|
database: a restore replaces that one, and the name belongs to this server."""
|
||||||
|
return _get_setting("server_name") or ""
|
||||||
|
|
||||||
|
|
||||||
|
def set_server_name(value) -> None:
|
||||||
|
_set_setting("server_name", value or None)
|
||||||
|
|
||||||
|
|
||||||
|
# --- destinations --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _row_to_dest(row, with_secrets=False):
|
||||||
|
d = {"id": row["id"], "name": row["name"], "type": row["type"], "enabled": bool(row["enabled"]),
|
||||||
|
"retention_count": row["retention_count"], "params": json.loads(row["params"]),
|
||||||
|
"last_status": row["last_status"], "last_message": row["last_message"], "last_at": row["last_at"]}
|
||||||
|
secrets, secrets_ok = {}, True
|
||||||
|
if row["secrets_enc"]:
|
||||||
|
try:
|
||||||
|
secrets = json.loads(decrypt_text(row["secrets_enc"]))
|
||||||
|
except BackupError:
|
||||||
|
secrets_ok = False
|
||||||
|
d["secrets_ok"] = secrets_ok
|
||||||
|
if with_secrets:
|
||||||
|
d["secrets"] = secrets
|
||||||
|
else:
|
||||||
|
# Masked: the UI only learns which secrets are set
|
||||||
|
d["secrets"] = {k: MASK for k, v in secrets.items() if v}
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def list_destinations(with_secrets=False):
|
||||||
|
with _conn() as c:
|
||||||
|
rows = c.execute("SELECT * FROM destinations ORDER BY id").fetchall()
|
||||||
|
return [_row_to_dest(r, with_secrets) for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def get_destination(dest_id: int, with_secrets=False):
|
||||||
|
with _conn() as c:
|
||||||
|
row = c.execute("SELECT * FROM destinations WHERE id=?", (dest_id,)).fetchone()
|
||||||
|
return _row_to_dest(row, with_secrets) if row else None
|
||||||
|
|
||||||
|
|
||||||
|
def save_destination(dest_id, name, dtype, enabled, retention_count, params, secrets) -> int:
|
||||||
|
"""Insert (dest_id None) or update. Raises BackupError on a duplicate name."""
|
||||||
|
enc = encrypt_text(json.dumps(secrets)) if secrets else ""
|
||||||
|
try:
|
||||||
|
with _lock, _conn() as c:
|
||||||
|
if dest_id is None:
|
||||||
|
cur = c.execute(
|
||||||
|
"INSERT INTO destinations (name, type, enabled, retention_count, params, secrets_enc, created_at) "
|
||||||
|
"VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
(name, dtype, int(enabled), retention_count, json.dumps(params), enc, _now()))
|
||||||
|
return cur.lastrowid
|
||||||
|
c.execute("UPDATE destinations SET name=?, type=?, enabled=?, retention_count=?, params=?, "
|
||||||
|
"secrets_enc=? WHERE id=?",
|
||||||
|
(name, dtype, int(enabled), retention_count, json.dumps(params), enc, dest_id))
|
||||||
|
return dest_id
|
||||||
|
except sqlite3.IntegrityError:
|
||||||
|
raise BackupError(f"A destination named '{name}' already exists") from None
|
||||||
|
|
||||||
|
|
||||||
|
def delete_destination(dest_id: int) -> bool:
|
||||||
|
with _lock, _conn() as c:
|
||||||
|
return c.execute("DELETE FROM destinations WHERE id=?", (dest_id,)).rowcount > 0
|
||||||
|
|
||||||
|
|
||||||
|
def set_last_result(dest_id: int, ok: bool, message: str) -> None:
|
||||||
|
with _lock, _conn() as c:
|
||||||
|
c.execute("UPDATE destinations SET last_status=?, last_message=?, last_at=? WHERE id=?",
|
||||||
|
("ok" if ok else "error", (message or "")[:500], _now(), dest_id))
|
||||||
|
|
||||||
|
|
||||||
|
# --- history -------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def history_start(kind: str) -> int:
|
||||||
|
with _lock, _conn() as c:
|
||||||
|
return c.execute("INSERT INTO history (kind, state, started_at) VALUES (?, 'running', ?)",
|
||||||
|
(kind, _now())).lastrowid
|
||||||
|
|
||||||
|
|
||||||
|
def history_finish(hist_id: int, state: str, message: str, results: list) -> None:
|
||||||
|
with _lock, _conn() as c:
|
||||||
|
c.execute("UPDATE history SET state=?, finished_at=?, message=?, results=? WHERE id=?",
|
||||||
|
(state, _now(), (message or "")[:1000], json.dumps(results), hist_id))
|
||||||
|
c.execute("DELETE FROM history WHERE id NOT IN (SELECT id FROM history ORDER BY id DESC LIMIT ?)",
|
||||||
|
(HISTORY_KEEP,))
|
||||||
|
|
||||||
|
|
||||||
|
def history_list(limit: int = 20) -> list:
|
||||||
|
with _conn() as c:
|
||||||
|
rows = c.execute("SELECT * FROM history ORDER BY id DESC LIMIT ?", (limit,)).fetchall()
|
||||||
|
return [{"id": r["id"], "kind": r["kind"], "state": r["state"], "started_at": r["started_at"],
|
||||||
|
"finished_at": r["finished_at"], "message": r["message"], "results": json.loads(r["results"])}
|
||||||
|
for r in rows]
|
||||||
@@ -144,6 +144,19 @@ def is_init_running() -> bool:
|
|||||||
with _init_lock:
|
with _init_lock:
|
||||||
return _init_job["state"] == "running"
|
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):
|
class PkiNotReady(Exception):
|
||||||
"""An operation needs keys that are not there (PKI absent, init running or server files missing)."""
|
"""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:
|
with _init_lock:
|
||||||
if _init_job["state"] == "running":
|
if _init_job["state"] == "running":
|
||||||
raise InitConflict("PKI initialization is already running")
|
raise InitConflict("PKI initialization is already running")
|
||||||
|
if is_restore_running():
|
||||||
|
raise InitConflict(RESTORE_RUNNING_MSG)
|
||||||
if is_initialized():
|
if is_initialized():
|
||||||
raise InitConflict("PKI is already initialized")
|
raise InitConflict("PKI is already initialized")
|
||||||
# Here the PKI is absent, has no CA, or carries the marker of an interrupted run:
|
# Here the PKI is absent, has no CA, or carries the marker of an interrupted run:
|
||||||
|
|||||||
@@ -1,25 +1,19 @@
|
|||||||
client
|
client
|
||||||
dev tun
|
dev tun
|
||||||
windows-driver wintun
|
|
||||||
proto {{ protocol }}
|
proto {{ protocol }}
|
||||||
remote {{ remote_ip }} {{ port }}
|
remote {{ remote_ip }} {{ port }}
|
||||||
resolv-retry infinite
|
resolv-retry infinite
|
||||||
nobind
|
nobind
|
||||||
|
{% if protocol == 'udp' %}
|
||||||
|
explicit-exit-notify
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
{% if tun_mtu %}
|
{% if tun_mtu %}
|
||||||
tun-mtu {{ tun_mtu }}
|
tun-mtu {{ tun_mtu }}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
user nobody
|
|
||||||
group nobody
|
|
||||||
persist-key
|
persist-key
|
||||||
persist-tun
|
persist-tun
|
||||||
|
|
||||||
{% if protocol == 'tcp' %}
|
|
||||||
tls-client
|
|
||||||
{% else %}
|
|
||||||
#tls-client
|
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
mute-replay-warnings
|
mute-replay-warnings
|
||||||
|
|
||||||
remote-cert-tls server
|
remote-cert-tls server
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
dev tun
|
dev tun
|
||||||
proto {{ protocol }}
|
proto {{ protocol }}
|
||||||
{% if protocol == 'tcp' %}
|
{% if protocol != 'tcp' %}
|
||||||
tls-server
|
|
||||||
{% else %}
|
|
||||||
# explicit-exit-notify 1
|
|
||||||
explicit-exit-notify 1
|
explicit-exit-notify 1
|
||||||
{% endif %}
|
{% endif %}
|
||||||
port {{ port }}
|
port {{ port }}
|
||||||
@@ -28,7 +25,6 @@ server {{ vpn_network }} {{ vpn_netmask }}
|
|||||||
|
|
||||||
ifconfig-pool-persist /etc/openvpn/ipp.txt
|
ifconfig-pool-persist /etc/openvpn/ipp.txt
|
||||||
|
|
||||||
log /var/log/openvpn/openvpn.log
|
|
||||||
log-append /var/log/openvpn/openvpn.log
|
log-append /var/log/openvpn/openvpn.log
|
||||||
|
|
||||||
verb 3
|
verb 3
|
||||||
|
|||||||
@@ -0,0 +1,404 @@
|
|||||||
|
import io
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import tarfile
|
||||||
|
import tempfile
|
||||||
|
import types
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
# The DB path must be set before database.py is imported (via main)
|
||||||
|
_tmp = tempfile.TemporaryDirectory()
|
||||||
|
os.environ.setdefault("OVPMON_PROFILER_DB_PATH", os.path.join(_tmp.name, "test.db"))
|
||||||
|
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from main import app
|
||||||
|
import migrations
|
||||||
|
from services import pki, process
|
||||||
|
from services.backup import BackupError, crypto, destinations, engine, package, store
|
||||||
|
from utils.auth import verify_token
|
||||||
|
|
||||||
|
app.dependency_overrides[verify_token] = lambda: {"sub": "test"}
|
||||||
|
client = TestClient(app)
|
||||||
|
|
||||||
|
PASS = "correct horse battery"
|
||||||
|
|
||||||
|
|
||||||
|
class InlineThread:
|
||||||
|
"""Runs the job in the calling thread: the tests need no polling."""
|
||||||
|
def __init__(self, target, args=(), daemon=None):
|
||||||
|
self.target, self.args = target, args
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
self.target(*self.args)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def env(tmp_path, monkeypatch):
|
||||||
|
"""A complete data layout in a temporary directory, nothing of the real system is touched."""
|
||||||
|
data = tmp_path / "data"
|
||||||
|
data.mkdir()
|
||||||
|
prof, mon = str(data / "ovpn_profiler.db"), str(data / "openvpn_monitor.db")
|
||||||
|
migrations.run(prof)
|
||||||
|
conn = sqlite3.connect(mon)
|
||||||
|
conn.executescript("CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT);"
|
||||||
|
"INSERT INTO schema_migrations VALUES (2, 'x', 'now');"
|
||||||
|
"CREATE TABLE users (name TEXT); INSERT INTO users VALUES ('admin');")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
pki_dir, client_dir = tmp_path / "easy-rsa" / "pki", tmp_path / "client-config"
|
||||||
|
(pki_dir / "private").mkdir(parents=True)
|
||||||
|
(pki_dir / "ca.crt").write_text("CA")
|
||||||
|
(pki_dir / "private" / "ca.key").write_text("SECRET")
|
||||||
|
os.chmod(pki_dir / "private" / "ca.key", 0o600)
|
||||||
|
client_dir.mkdir()
|
||||||
|
(client_dir / "alice.ovpn").write_text("client config")
|
||||||
|
monkeypatch.setenv("OVPMON_BACKUP_LOCAL_ROOT", str(tmp_path / "backups"))
|
||||||
|
monkeypatch.setattr(engine, "profiler_db_path", lambda: prof)
|
||||||
|
monkeypatch.setattr(engine, "monitor_db_path", lambda: mon)
|
||||||
|
monkeypatch.setattr(engine, "client_dir", lambda: str(client_dir))
|
||||||
|
monkeypatch.setattr(engine, "core_dir", lambda: None) # the schemas are equal: no migration needed
|
||||||
|
monkeypatch.setattr(pki, "PKI_DIR", str(pki_dir))
|
||||||
|
monkeypatch.setattr(process, "get_process_stats", lambda: {"status": "stopped"})
|
||||||
|
monkeypatch.setattr(engine, "threading", types.SimpleNamespace(Thread=InlineThread))
|
||||||
|
monkeypatch.setattr(store, "db_file", lambda: str(tmp_path / "ovpmon_backup.db"))
|
||||||
|
store.init()
|
||||||
|
return types.SimpleNamespace(root=tmp_path, prof=prof, mon=mon, pki=pki_dir, clients=client_dir)
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_round_trip_and_wrong_passphrase(env, tmp_path):
|
||||||
|
work = tmp_path / "w"
|
||||||
|
work.mkdir()
|
||||||
|
path, name, manifest = engine.create_package(str(work), PASS)
|
||||||
|
assert name.endswith(".ovpbak.enc") and package.parse_package_name(name)["encrypted"]
|
||||||
|
assert crypto.is_encrypted(path) and b"SECRET" not in open(path, "rb").read()
|
||||||
|
assert manifest["schema"]["monitor"] == 2 and "pki/private/ca.key" in manifest["files"]
|
||||||
|
|
||||||
|
with pytest.raises(crypto.WrongPassphrase):
|
||||||
|
crypto.decrypt_file(path, str(tmp_path / "bad.tar.gz"), "wrong passphrase")
|
||||||
|
crypto.decrypt_file(path, str(tmp_path / "ok.tar.gz"), PASS)
|
||||||
|
out = tmp_path / "out"
|
||||||
|
package.safe_extract(str(tmp_path / "ok.tar.gz"), str(out))
|
||||||
|
assert (out / "pki" / "ca.crt").read_text() == "CA"
|
||||||
|
assert (out / "pki" / "private" / "ca.key").read_text() == "SECRET"
|
||||||
|
assert oct(os.stat(out / "pki" / "private" / "ca.key").st_mode & 0o777) == "0o600"
|
||||||
|
assert (out / "client-config" / "alice.ovpn").read_text() == "client config"
|
||||||
|
assert sqlite3.connect(out / "db" / "openvpn_monitor.db").execute("SELECT name FROM users").fetchone() == ("admin",)
|
||||||
|
assert package.integrity_ok(str(out / "db" / "ovpn_profiler.db"))
|
||||||
|
|
||||||
|
|
||||||
|
def _tar(path, members):
|
||||||
|
with tarfile.open(path, "w:gz") as tar:
|
||||||
|
for info, data in members:
|
||||||
|
tar.addfile(info, io.BytesIO(data) if data is not None else None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_safe_extraction_and_newer_schema(env, tmp_path):
|
||||||
|
def reg(name, data=b"x"):
|
||||||
|
info = tarfile.TarInfo(name)
|
||||||
|
info.size = len(data)
|
||||||
|
return info, data
|
||||||
|
|
||||||
|
link = tarfile.TarInfo("pki/link")
|
||||||
|
link.type, link.linkname = tarfile.SYMTYPE, "/etc/passwd"
|
||||||
|
for i, members in enumerate([[reg("../evil")], [reg("/abs/evil")], [reg("pki/../../evil")],
|
||||||
|
[(link, None)], [reg("other/file")], [reg("db/extra.db")]]):
|
||||||
|
bad = str(tmp_path / f"bad{i}.tar.gz")
|
||||||
|
_tar(bad, members)
|
||||||
|
with pytest.raises(BackupError):
|
||||||
|
package.safe_extract(bad, str(tmp_path / f"out{i}"))
|
||||||
|
assert not (tmp_path / "evil").exists()
|
||||||
|
|
||||||
|
# A valid package from a newer release is refused before anything is touched
|
||||||
|
work = tmp_path / "w"
|
||||||
|
work.mkdir()
|
||||||
|
path, _name, _ = engine.create_package(str(work), None)
|
||||||
|
out = tmp_path / "ok"
|
||||||
|
manifest = package.safe_extract(path, str(out))
|
||||||
|
conn = sqlite3.connect(out / "db" / "ovpn_profiler.db")
|
||||||
|
conn.execute("INSERT INTO schema_migrations VALUES (999, 'future', 'now')")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
with pytest.raises(BackupError, match="newer release"):
|
||||||
|
engine._prepare_staged(str(out), manifest)
|
||||||
|
# An unknown format version is refused too
|
||||||
|
import json
|
||||||
|
manifest["format_version"] = 99
|
||||||
|
(out / "manifest.json").write_text(json.dumps(manifest))
|
||||||
|
with pytest.raises(BackupError, match="Unknown package format"):
|
||||||
|
package.verify_extracted(str(out))
|
||||||
|
|
||||||
|
|
||||||
|
class FailingDestination(destinations.Destination):
|
||||||
|
type = "stub"
|
||||||
|
label = "Stub"
|
||||||
|
|
||||||
|
def put(self, local_path, name):
|
||||||
|
raise destinations.DestinationError("disk on fire")
|
||||||
|
|
||||||
|
def list(self):
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def test_multi_destination_backup_rotation_and_restore(env, tmp_path, monkeypatch):
|
||||||
|
monkeypatch.setitem(destinations.DESTINATION_TYPES, "stub", FailingDestination)
|
||||||
|
good = store.save_destination(None, "local-good", "local", True, 2, {"folder": "daily"}, {})
|
||||||
|
bad = store.save_destination(None, "broken", "stub", True, 14, {}, {})
|
||||||
|
stamps = iter(f"20261007T1000{i:02d}Z" for i in range(10))
|
||||||
|
monkeypatch.setattr(package, "utc_stamp", lambda now=None: next(stamps))
|
||||||
|
|
||||||
|
for _ in range(3):
|
||||||
|
engine.start_backup(None)
|
||||||
|
job = engine.status()
|
||||||
|
assert job["state"] == "partial" # one failed, the other still got the package
|
||||||
|
by_name = {r["name"]: r for r in job["results"]}
|
||||||
|
assert by_name["local-good"]["state"] == "ok" and by_name["broken"]["state"] == "error"
|
||||||
|
assert "disk on fire" in by_name["broken"]["message"]
|
||||||
|
assert store.get_destination(bad)["last_status"] == "error"
|
||||||
|
names = sorted(p["name"] for p in engine.list_packages(good))
|
||||||
|
assert len(names) == 2 and names[0].endswith("100001Z.ovpbak") # oldest of 3 rotated away
|
||||||
|
|
||||||
|
# Restore the newest package after the live data was damaged
|
||||||
|
newest = engine.list_packages(good)[0]["name"]
|
||||||
|
env.pki.joinpath("ca.crt").write_text("DAMAGED")
|
||||||
|
(env.clients / "alice.ovpn").unlink()
|
||||||
|
(env.clients / "stray.ovpn").write_text("not in the package")
|
||||||
|
sqlite3.connect(env.mon).execute("DROP TABLE users").connection.commit()
|
||||||
|
engine.start_restore(good, newest, None)
|
||||||
|
job = engine.status()
|
||||||
|
assert job["state"] == "done", job["message"]
|
||||||
|
assert job["relogin"] is True
|
||||||
|
assert env.pki.joinpath("ca.crt").read_text() == "CA"
|
||||||
|
assert (env.clients / "alice.ovpn").read_text() == "client config" and not (env.clients / "stray.ovpn").exists()
|
||||||
|
assert sqlite3.connect(env.mon).execute("SELECT name FROM users").fetchone() == ("admin",)
|
||||||
|
assert not [p for p in os.listdir(env.pki) if p.startswith(".restore-")]
|
||||||
|
# the previous state was saved first, locally
|
||||||
|
pre = destinations.LocalDestination({"folder": "pre-restore"}, {}).list()
|
||||||
|
assert len(pre) == 1 and package.parse_package_name(pre[0]["name"])
|
||||||
|
|
||||||
|
# A package that is not in the listing is not accepted
|
||||||
|
with pytest.raises(BackupError):
|
||||||
|
engine.start_restore(good, "ovpmon-backup_x_20200101T000000Z.ovpbak", None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_api_requires_jwt_masks_secrets_and_refuses_remote_without_passphrase(env):
|
||||||
|
saved = app.dependency_overrides.pop(verify_token)
|
||||||
|
try:
|
||||||
|
for method, path in [("get", "/api/backup/settings"), ("put", "/api/backup/settings"),
|
||||||
|
("get", "/api/backup/destinations"), ("post", "/api/backup/destinations"),
|
||||||
|
("put", "/api/backup/destinations/1"), ("delete", "/api/backup/destinations/1"),
|
||||||
|
("post", "/api/backup/destinations/1/test"), ("get", "/api/backup/destinations/1/packages"),
|
||||||
|
("post", "/api/backup/run"), ("post", "/api/backup/restore"),
|
||||||
|
("get", "/api/backup/status"), ("get", "/api/backup/history")]:
|
||||||
|
assert getattr(client, method)(path).status_code == 401, (method, path)
|
||||||
|
finally:
|
||||||
|
app.dependency_overrides[verify_token] = saved
|
||||||
|
|
||||||
|
s3 = {"name": "bucket", "type": "s3", "params": {"endpoint": "s3.example.com", "bucket": "my-backups"},
|
||||||
|
"secrets": {"access_key": "AKIAEXAMPLE", "secret_key": "TOPSECRETVALUE"}}
|
||||||
|
r = client.post("/api/backup/destinations", json=s3)
|
||||||
|
assert r.status_code == 201
|
||||||
|
dest = r.json()
|
||||||
|
assert "TOPSECRETVALUE" not in r.text and "AKIAEXAMPLE" not in r.text
|
||||||
|
assert dest["secrets"] == {"access_key": store.MASK, "secret_key": store.MASK}
|
||||||
|
assert "TOPSECRETVALUE" not in client.get("/api/backup/destinations").text
|
||||||
|
assert "TOPSECRETVALUE" not in open(store.db_file(), "rb").read().decode("latin-1") # encrypted at rest
|
||||||
|
|
||||||
|
# Only implemented types; updating with the mask keeps the stored secret
|
||||||
|
assert client.post("/api/backup/destinations", json={**s3, "name": "x", "type": "smb"}).status_code == 400
|
||||||
|
s3["secrets"] = {"access_key": store.MASK, "secret_key": ""}
|
||||||
|
assert client.put(f"/api/backup/destinations/{dest['id']}", json=s3).status_code == 200
|
||||||
|
assert store.get_destination(dest["id"], with_secrets=True)["secrets"]["secret_key"] == "TOPSECRETVALUE"
|
||||||
|
|
||||||
|
# Remote destination without a passphrase: no backup
|
||||||
|
r = client.post("/api/backup/run", json={})
|
||||||
|
assert r.status_code == 400 and "passphrase" in r.json()["detail"].lower()
|
||||||
|
assert client.put("/api/backup/settings", json={"passphrase": "short"}).status_code == 400
|
||||||
|
r = client.put("/api/backup/settings", json={"passphrase": PASS})
|
||||||
|
assert r.status_code == 200 and r.json()["encryption_enabled"] is True and PASS not in r.text
|
||||||
|
assert client.put("/api/backup/settings", json={"clear_passphrase": True}).status_code == 400 # remote needs it
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_name_server_name_fallback_and_unique_names(env, tmp_path, monkeypatch):
|
||||||
|
import re
|
||||||
|
import socket
|
||||||
|
monkeypatch.setattr(socket, "gethostname", lambda: "3f9a1c0b2d44")
|
||||||
|
assert engine.effective_server_name() == ("3f9a1c0b2d44", "hostname")
|
||||||
|
conn = sqlite3.connect(env.prof)
|
||||||
|
conn.execute("INSERT INTO system_settings (id, public_ip) VALUES (1, 'vpn.example.com')")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
assert engine.effective_server_name() == ("vpn.example.com", "public_ip")
|
||||||
|
|
||||||
|
# The setting wins, is validated, and can be cleared again
|
||||||
|
assert client.put("/api/backup/settings", json={"server_name": "bad name!"}).status_code == 400
|
||||||
|
r = client.put("/api/backup/settings", json={"server_name": "vpn-main"}).json()
|
||||||
|
assert (r["server_name"], r["effective_server_name"], r["server_name_source"]) == ("vpn-main", "vpn-main", "setting")
|
||||||
|
assert client.put("/api/backup/settings", json={"server_name": ""}).json()["server_name_source"] == "public_ip"
|
||||||
|
store.set_server_name("vpn-main")
|
||||||
|
|
||||||
|
# Name format, manifest, and -2 / -3 when the same second is taken (nothing is overwritten)
|
||||||
|
monkeypatch.setattr(package, "utc_stamp", lambda now=None: "20261007T101500Z")
|
||||||
|
dest = store.save_destination(None, "local-daily", "local", True, 2, {"folder": "daily"}, {})
|
||||||
|
old = "ovpmon-backup_oldhost_20200101T000000Z.ovpbak" # first-pass name: listed, never rotated
|
||||||
|
destinations.LocalDestination({"folder": "daily"}, {}).put(str(env.prof), old)
|
||||||
|
for _ in range(3):
|
||||||
|
engine.start_backup(None)
|
||||||
|
assert engine.status()["state"] == "done"
|
||||||
|
packages = engine.list_packages(dest)
|
||||||
|
assert [p["name"] for p in packages] == [
|
||||||
|
"ovpmon-backup_vpn-main_20261007T101500Z-3.ovpbak",
|
||||||
|
"ovpmon-backup_vpn-main_20261007T101500Z-2.ovpbak", old] # newest first; -1 rotated away
|
||||||
|
assert packages[0]["server_name"] == "vpn-main" and packages[2]["server_name"] == "oldhost"
|
||||||
|
work = tmp_path / "w"
|
||||||
|
work.mkdir()
|
||||||
|
_path, name, manifest = engine.create_package(str(work), None)
|
||||||
|
assert name == "ovpmon-backup_vpn-main_20261007T101500Z.ovpbak"
|
||||||
|
assert manifest["server_name"] == "vpn-main" and manifest["hostname"] == "3f9a1c0b2d44"
|
||||||
|
assert re.match(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$", manifest["created_at"])
|
||||||
|
|
||||||
|
|
||||||
|
class FakeKey:
|
||||||
|
blob = b"server-host-key-A"
|
||||||
|
|
||||||
|
def asbytes(self):
|
||||||
|
return self.blob
|
||||||
|
|
||||||
|
def get_name(self):
|
||||||
|
return "ssh-ed25519"
|
||||||
|
|
||||||
|
|
||||||
|
class FakeSFTP:
|
||||||
|
files, dirs = {}, set()
|
||||||
|
|
||||||
|
def get_channel(self):
|
||||||
|
return types.SimpleNamespace(settimeout=lambda t: None)
|
||||||
|
|
||||||
|
def stat(self, path):
|
||||||
|
if path in self.dirs:
|
||||||
|
return types.SimpleNamespace(st_mode=0o40700)
|
||||||
|
raise FileNotFoundError(path)
|
||||||
|
|
||||||
|
def mkdir(self, path, mode=0o777):
|
||||||
|
self.dirs.add(path)
|
||||||
|
|
||||||
|
def put(self, local, remote, confirm=True):
|
||||||
|
self.files[remote] = open(local, "rb").read()
|
||||||
|
|
||||||
|
def putfo(self, fh, remote):
|
||||||
|
self.files[remote] = fh.read()
|
||||||
|
|
||||||
|
def posix_rename(self, a, b):
|
||||||
|
self.files[b] = self.files.pop(a)
|
||||||
|
|
||||||
|
def remove(self, path):
|
||||||
|
del self.files[path]
|
||||||
|
|
||||||
|
def listdir_attr(self, directory):
|
||||||
|
return [types.SimpleNamespace(filename=p.rsplit("/", 1)[-1], st_mode=0o100600, st_size=len(v), st_mtime=1.0)
|
||||||
|
for p, v in self.files.items() if p.rsplit("/", 1)[0] == directory]
|
||||||
|
|
||||||
|
def getfo(self, remote, out):
|
||||||
|
out.write(self.files[remote])
|
||||||
|
|
||||||
|
|
||||||
|
class FakeSSH:
|
||||||
|
connects = []
|
||||||
|
|
||||||
|
def set_missing_host_key_policy(self, policy):
|
||||||
|
self.policy = policy
|
||||||
|
|
||||||
|
def connect(self, host, **kw):
|
||||||
|
FakeSSH.connects.append((host, kw.get("password"), kw.get("pkey")))
|
||||||
|
self.policy.missing_host_key(self, host, FakeKey()) # raises unless the key is the pinned one
|
||||||
|
|
||||||
|
def open_sftp(self):
|
||||||
|
return FakeSFTP()
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def test_sftp_ftp_validation_and_host_key_pinning(env, monkeypatch):
|
||||||
|
import paramiko
|
||||||
|
from cryptography.hazmat.primitives import serialization
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import ed25519
|
||||||
|
monkeypatch.setattr(paramiko, "SSHClient", FakeSSH)
|
||||||
|
FakeSFTP.files, FakeSFTP.dirs = {}, set()
|
||||||
|
FakeSSH.connects.clear()
|
||||||
|
sftp, ftp = destinations.SFTPDestination, destinations.FTPDestination
|
||||||
|
base = {"host": "files.example.com", "port": 22, "username": "backup", "directory": "ovpmon/daily"}
|
||||||
|
|
||||||
|
# Parameter and secret rules
|
||||||
|
for bad in ({"host": "bad host!"}, {"port": 70000}, {"username": ""}, {"directory": "../x"}, {"directory": "/etc"}):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
sftp.validate({**base, **bad}, {"password": "pw"})
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
sftp.validate(base, {}) # neither password nor key
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
sftp.validate(base, {"password": "pw", "private_key": "x"}) # both
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
sftp.validate(base, {"private_key": "-----BEGIN OPENSSH PRIVATE KEY-----\nnot a key\n"})
|
||||||
|
key = ed25519.Ed25519PrivateKey.generate().private_bytes(
|
||||||
|
serialization.Encoding.PEM, serialization.PrivateFormat.OpenSSH, serialization.NoEncryption()).decode()
|
||||||
|
assert sftp.validate(base, {"private_key": key})[1] == {"private_key": key.strip() + "\n"}
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
sftp.validate({**base, "host_key": "SHA256:x"}, {"password": "pw"}) # a pin never comes with the form
|
||||||
|
fclean, _ = ftp.validate({"host": "ftp.example.com", "username": "u", "directory": "bk"}, {"password": "pw"})
|
||||||
|
assert (fclean["port"], fclean["tls"], fclean["verify_cert"], fclean["passive"]) == (21, True, True, True)
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
ftp.validate({"host": "ftp.example.com", "username": "u", "directory": "bk"}, {}) # no password
|
||||||
|
|
||||||
|
# Not pinned: Test shows the fingerprint, nothing else works, no connection is even opened
|
||||||
|
body = {"name": "offsite", "type": "sftp", "params": base, "secrets": {"password": "pw"}}
|
||||||
|
dest = client.post("/api/backup/destinations", json=body).json()
|
||||||
|
assert dest["secrets"] == {"password": store.MASK} and "host_key" not in dest["params"]
|
||||||
|
shown = engine.test_destination(dest["id"])
|
||||||
|
assert shown["ok"] is False and shown["needs_trust"] is True and shown["key_changed"] is False
|
||||||
|
fp = shown["fingerprint"]
|
||||||
|
assert fp == destinations._ssh_fingerprint(FakeKey())
|
||||||
|
rec = store.get_destination(dest["id"], with_secrets=True)
|
||||||
|
unpinned = destinations.build_destination("sftp", rec["params"], rec["secrets"])
|
||||||
|
n = len(FakeSSH.connects)
|
||||||
|
for call in (lambda: unpinned.put(__file__, "ovpmon-backup_x_20260101T000000Z.ovpbak"), unpinned.list,
|
||||||
|
lambda: unpinned.get("ovpmon-backup_x_20260101T000000Z.ovpbak", "/dev/null"),
|
||||||
|
lambda: unpinned.delete("ovpmon-backup_x_20260101T000000Z.ovpbak")):
|
||||||
|
with pytest.raises(destinations.DestinationError, match="not trusted"):
|
||||||
|
call()
|
||||||
|
assert len(FakeSSH.connects) == n
|
||||||
|
|
||||||
|
# Trust: only the fingerprint the administrator saw is accepted
|
||||||
|
with pytest.raises(BackupError):
|
||||||
|
engine.trust_host_key(dest["id"], "SHA256:" + "A" * 43)
|
||||||
|
pinned = engine.trust_host_key(dest["id"], fp)
|
||||||
|
assert pinned["params"]["host_key"] == fp and pinned["secrets"] == {"password": store.MASK}
|
||||||
|
assert engine.test_destination(dest["id"])["ok"] is True
|
||||||
|
rec = store.get_destination(dest["id"], with_secrets=True)
|
||||||
|
d = destinations.build_destination("sftp", rec["params"], rec["secrets"])
|
||||||
|
name = "ovpmon-backup_vpn_20261007T101500Z.ovpbak"
|
||||||
|
d.put(__file__, name)
|
||||||
|
assert f"ovpmon/daily/{name}" in FakeSFTP.files and not [f for f in FakeSFTP.files if f.endswith(".part")]
|
||||||
|
FakeSFTP.files["ovpmon/daily/notes.txt"] = b"x"
|
||||||
|
assert [o["name"] for o in d.list()] == [name] # only our package names
|
||||||
|
out = os.path.join(os.path.dirname(env.prof), "got")
|
||||||
|
d.get(name, out)
|
||||||
|
assert open(out, "rb").read() == open(__file__, "rb").read()
|
||||||
|
|
||||||
|
# Pin and the form: an edit of other fields keeps the pin, a client cannot set it, a new host drops it
|
||||||
|
edit = {**body, "params": {**base, "host_key": "SHA256:" + "B" * 43, "directory": "ovpmon/other"}, "secrets": {}}
|
||||||
|
r = client.put(f"/api/backup/destinations/{dest['id']}", json=edit).json()
|
||||||
|
assert r["params"]["host_key"] == fp and r["params"]["directory"] == "ovpmon/other"
|
||||||
|
r = client.put(f"/api/backup/destinations/{dest['id']}", json={**edit, "params": {**base, "host": "other.example.com"}}).json()
|
||||||
|
assert "host_key" not in r["params"]
|
||||||
|
client.put(f"/api/backup/destinations/{dest['id']}", json={**edit, "params": base})
|
||||||
|
engine.trust_host_key(dest["id"], fp)
|
||||||
|
|
||||||
|
# A different key from the server: connection refused, Test offers the new fingerprint (changed)
|
||||||
|
FakeKey.blob = b"server-host-key-B"
|
||||||
|
try:
|
||||||
|
with pytest.raises(destinations.DestinationError, match="host key of the server changed"):
|
||||||
|
d.list()
|
||||||
|
changed = engine.test_destination(dest["id"])
|
||||||
|
assert changed["needs_trust"] is True and changed["key_changed"] is True and changed["fingerprint"] != fp
|
||||||
|
finally:
|
||||||
|
FakeKey.blob = b"server-host-key-A"
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
"""One test for the client profile template (templates/client.ovpn.j2), tcp and udp."""
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from services.generator import env
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("protocol", ["tcp", "udp"])
|
||||||
|
def test_client_template(protocol):
|
||||||
|
text = env.get_template("client.ovpn.j2").render(
|
||||||
|
protocol=protocol, remote_ip="203.0.113.1", port=1194, ca_cert="CA",
|
||||||
|
client_cert="CERT", client_key="KEY", tls_auth="TA", tun_mtu=None)
|
||||||
|
lines = [x.strip() for x in text.splitlines()]
|
||||||
|
assert f"proto {protocol}" in lines and "client" in lines
|
||||||
|
# directives that OpenVPN 2.7 rejects or that are redundant/harmful on user devices
|
||||||
|
for gone in ("windows-driver", "tls-client", "#tls-client", "user", "group"):
|
||||||
|
assert not any(x.split(" ")[0] == gone for x in lines)
|
||||||
|
assert ("explicit-exit-notify" in lines) == (protocol == "udp")
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
# The DB path must be set before database.py is imported (via main)
|
||||||
|
_tmp = tempfile.TemporaryDirectory()
|
||||||
|
os.environ["OVPMON_PROFILER_DB_PATH"] = os.path.join(_tmp.name, "test.db")
|
||||||
|
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from main import app
|
||||||
|
from utils.auth import verify_token
|
||||||
|
|
||||||
|
app.dependency_overrides[verify_token] = lambda: {"sub": "test"}
|
||||||
|
client = TestClient(app)
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_section_values():
|
||||||
|
r = client.get("/api/config", params={"section": "server"})
|
||||||
|
assert r.status_code == 200 and r.json()["server"] and not r.json().get("pki")
|
||||||
|
assert client.get("/api/config", params={"section": "pki"}).status_code == 200
|
||||||
|
assert client.get("/api/config").status_code == 200
|
||||||
|
assert client.get("/api/config", params={"section": "bogus"}).status_code == 422
|
||||||
@@ -1,33 +1,27 @@
|
|||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
# The DB path must be set before database.py is imported (via main)
|
||||||
|
_tmp = tempfile.TemporaryDirectory()
|
||||||
|
os.environ["OVPMON_PROFILER_DB_PATH"] = os.path.join(_tmp.name, "test.db")
|
||||||
|
|
||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
from main import app
|
from main import app
|
||||||
import sys
|
from utils.auth import verify_token
|
||||||
import os
|
|
||||||
|
|
||||||
# Add project root to sys.path
|
|
||||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
|
||||||
|
|
||||||
|
app.dependency_overrides[verify_token] = lambda: {"sub": "test"}
|
||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
|
|
||||||
|
|
||||||
def test_get_stats():
|
def test_get_stats():
|
||||||
response = client.get("/server/process/stats")
|
response = client.get("/api/server/process/stats")
|
||||||
print(f"Stats response status: {response.status_code}")
|
|
||||||
print(f"Stats response body: {response.json()}")
|
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
data = response.json()
|
data = response.json()
|
||||||
assert "pid" in data
|
assert "pid" in data
|
||||||
assert "cpu_percent" in data
|
assert "cpu_percent" in data
|
||||||
assert "memory_mb" in data
|
assert "memory_mb" in data
|
||||||
|
|
||||||
def test_control_invalid():
|
|
||||||
response = client.post("/server/process/invalid_action")
|
|
||||||
print(f"Invalid action response: {response.status_code}")
|
|
||||||
assert response.status_code == 400
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
def test_control_invalid():
|
||||||
print("Running API tests...")
|
response = client.post("/api/server/process/invalid_action")
|
||||||
try:
|
assert response.status_code == 400
|
||||||
test_get_stats()
|
|
||||||
test_control_invalid()
|
|
||||||
print("Tests passed!")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"Tests failed: {e}")
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
from services import pki
|
||||||
|
|
||||||
|
|
||||||
|
def forbid_during_restore():
|
||||||
|
"""Dependency of the routes that change the PKI, the profiles or the settings: 409 while a
|
||||||
|
backup restore replaces them."""
|
||||||
|
if pki.is_restore_running():
|
||||||
|
raise HTTPException(status_code=409, detail=pki.RESTORE_RUNNING_MSG)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
.vscode
|
||||||
|
.git
|
||||||
|
*.bak
|
||||||
|
*.log
|
||||||
+12
-4
@@ -2,14 +2,22 @@
|
|||||||
FROM node:20-alpine AS build-stage
|
FROM node:20-alpine AS build-stage
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
RUN npm install
|
RUN npm ci
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
# Stage 2: Serve
|
# Stage 2: Serve
|
||||||
FROM nginx:alpine
|
# nginx runs as the unprivileged user "nginx" (uid 101) and listens on 8080 (OVP_UI_PORT); docker-compose publishes
|
||||||
|
# it as the host port (OVPMON_HTTP_PORT, default 80). The image entrypoint renders the template into
|
||||||
|
# /etc/nginx/conf.d. Behind another proxy or Kubernetes: target port 8080.
|
||||||
|
FROM nginxinc/nginx-unprivileged:alpine
|
||||||
COPY --from=build-stage /app/dist /usr/share/nginx/html
|
COPY --from=build-stage /app/dist /usr/share/nginx/html
|
||||||
COPY default.conf.template /etc/nginx/templates/default.conf.template
|
COPY default.conf.template /etc/nginx/templates/default.conf.template
|
||||||
EXPOSE 80
|
# Validates OVP_CSP_CONNECT_EXTRA before the template is rendered (20-envsubst-on-templates.sh)
|
||||||
|
COPY check-csp-connect-extra.sh /docker-entrypoint.d/15-check-csp-connect-extra.sh
|
||||||
|
# envsubst replaces only variables that are defined, so the defaults must exist.
|
||||||
|
# OVP_CSP_CONNECT_EXTRA: extra connect-src origins of the CSP, separated by spaces (empty: same origin only)
|
||||||
|
ENV OVP_UI_PORT=8080 \
|
||||||
|
OVP_CSP_CONNECT_EXTRA=""
|
||||||
|
EXPOSE 8080
|
||||||
CMD ["nginx", "-g", "daemon off;"]
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
|
|
||||||
+21
-9
@@ -1,25 +1,37 @@
|
|||||||
# OpenVPN Dashboard UI (`APP_UI`)
|
# OpenVPN Controller UI (`APP_UI`)
|
||||||
|
|
||||||
A Single Page Application (SPA) built with **Vue 3** and **Vite**. It serves as the unified dashboard for monitoring and management.
|
A Single Page Application (SPA) built with **Vue 3** and **Vite**. It serves as the unified dashboard for monitoring and management.
|
||||||
|
|
||||||
## Project Structure
|
## Project Structure
|
||||||
|
|
||||||
- `src/views/`: Page components (Dashboard, Login, Profiles, etc.).
|
- `src/views/`: Pages (Analytics, Clients, Certificates, PKI and VPN configuration, Server Process, Backup and Restore, Account, Login).
|
||||||
- `src/components/`: Reusable widgets (Charts, Sidebar).
|
- `src/components/`: Reusable widgets (`BaseModal`, `ConfirmModal`, `StatusBadge`, toasts, dialogs).
|
||||||
- `src/stores/`: Pinia state management (Auth, Client Data).
|
- `src/composables/`: Shared logic: `useApi` (axios clients: monitoring API, profiler API, `/api/auth`), `useTrafficChart` (charts), `useTheme`, `useToast`, `useFormatters`, `usePkiStatus`.
|
||||||
|
- `src/utils/`: Helpers without Vue (CIDR parsing).
|
||||||
|
- `default.conf.template`: nginx configuration of the container image (security headers, one CSP, gzip, cache, API proxy).
|
||||||
|
- `Dockerfile`: build and `nginxinc/nginx-unprivileged:alpine` image (user `nginx`, port 8080); `check-csp-connect-extra.sh`: validation of `OVP_CSP_CONNECT_EXTRA`, runs at container start.
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
Runtime configuration is loaded from `/config.json` (in `public/`) to allow environment-independent builds.
|
Runtime configuration is loaded from `/config.json` (in `public/`) to allow environment-independent builds. With the container nginx the CSP allows requests to the page origin only (`connect-src 'self'`): keep the API paths proxied (`/api/v1`, `/profiles-api`). To call an API on another origin, set `OVPMON_CSP_CONNECT_EXTRA` (origins separated by spaces; see [Containers reference](../DOCS/Deployment/Containers/Reference.md)). The `app-ui` container listens on 8080 (`OVP_UI_PORT`) as the unprivileged user `nginx`; compose publishes it as `OVPMON_HTTP_PORT` (default 80).
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install
|
npm ci # exact versions from package-lock.json (npm install after changing package.json)
|
||||||
npm run dev
|
npm run dev # http://localhost:5173
|
||||||
# Access at http://localhost:5173
|
npm run build
|
||||||
|
npm test # Vitest: formatters, CIDR parsing, 401 handling
|
||||||
|
npm run lint # ESLint (minimal Vue rules)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Node 20.19 or newer is required (Vite 7).
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
- The session token is kept in `localStorage` (accepted risk, see `DOCS/General/Security_Architecture.md`).
|
||||||
|
- Confirmations use `ConfirmModal`, notices use toasts (`useToast`); the native `confirm()` and SweetAlert2 are not used.
|
||||||
|
- After changing the UI sources, refresh the committed build for system-service installs: `deploy/native/build-ui.sh --publish` (`deploy/native/check-ui.sh` shows whether it is stale).
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
See `DOCS/UI/Architecture.md` for detailed architecture notes.
|
See `DOCS/UI/Architecture.md` for detailed architecture notes.
|
||||||
|
|
||||||
Executable
+51
@@ -0,0 +1,51 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Validates OVP_CSP_CONNECT_EXTRA: extra origins for the connect-src directive of the Content-Security-Policy
|
||||||
|
# (compose: OVPMON_CSP_CONNECT_EXTRA). The value ends up in a response header, so only origins are accepted:
|
||||||
|
# empty, or https://host[:port] and http://host[:port] separated by spaces (host: letters, digits, dots, hyphens;
|
||||||
|
# no path, quotes, ; or commas). Anything else could inject another CSP directive.
|
||||||
|
#
|
||||||
|
# Runs as /docker-entrypoint.d/15-check-csp-connect-extra.sh in the app-ui image (before the template is
|
||||||
|
# rendered by 20-envsubst-on-templates.sh) and from the all-in-one entrypoint. Exit code 1 stops the container.
|
||||||
|
# The same rule is in deploy/docker/lib.sh and deploy/native/lib.sh (csp_extra_problem): keep them in step.
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
csp_extra_problem() {
|
||||||
|
local _t _rest _host _port
|
||||||
|
[ -n "$1" ] || return 0
|
||||||
|
case "$1" in
|
||||||
|
*[!A-Za-z0-9.:/\ -]*)
|
||||||
|
printf 'contains characters that are not allowed (only letters, digits, . - : / and spaces; no quotes, ; or commas)'; return 1 ;;
|
||||||
|
" "*|*" ")
|
||||||
|
printf 'starts or ends with a space'; return 1 ;;
|
||||||
|
esac
|
||||||
|
set -f
|
||||||
|
for _t in $1; do
|
||||||
|
case "$_t" in
|
||||||
|
https://*) _rest=${_t#https://} ;;
|
||||||
|
http://*) _rest=${_t#http://} ;;
|
||||||
|
*) set +f; printf "'%s' is not an origin (use https://host[:port] or http://host[:port])" "$_t"; return 1 ;;
|
||||||
|
esac
|
||||||
|
_host=${_rest%%:*}
|
||||||
|
_port=""
|
||||||
|
case "$_rest" in *:*) _port=${_rest#*:} ;; esac
|
||||||
|
case "$_host" in
|
||||||
|
""|*[!A-Za-z0-9.-]*) set +f; printf "'%s' has an invalid host (letters, digits, dots and hyphens; no path)" "$_t"; return 1 ;;
|
||||||
|
esac
|
||||||
|
if [ -n "$_port" ]; then
|
||||||
|
case "$_port" in
|
||||||
|
*[!0-9]*) set +f; printf "'%s' has an invalid port (digits only, no path)" "$_t"; return 1 ;;
|
||||||
|
esac
|
||||||
|
if [ "${#_port}" -gt 5 ] || [ "$_port" -lt 1 ] || [ "$_port" -gt 65535 ]; then
|
||||||
|
set +f; printf "'%s' has a port out of range" "$_t"; return 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
case "$_rest" in *:) set +f; printf "'%s' has an empty port" "$_t"; return 1 ;; esac
|
||||||
|
done
|
||||||
|
set +f
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
if ! _reason=$(csp_extra_problem "${OVP_CSP_CONNECT_EXTRA:-}"); then
|
||||||
|
echo "check-csp-connect-extra: OVPMON_CSP_CONNECT_EXTRA is invalid: $_reason. Use origins https://host[:port] or http://host[:port] separated by spaces, or leave it empty" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
@@ -1,21 +1,58 @@
|
|||||||
server {
|
server {
|
||||||
listen 80;
|
listen ${OVP_UI_PORT};
|
||||||
server_name localhost;
|
server_name localhost;
|
||||||
|
server_tokens off;
|
||||||
|
|
||||||
root /usr/share/nginx/html;
|
root /usr/share/nginx/html;
|
||||||
index index.html;
|
index index.html;
|
||||||
|
|
||||||
|
# Security headers. add_header in a location replaces the ones inherited from the server block,
|
||||||
|
# so the /assets/ location below repeats them. CSP: the bundle is served from this origin only;
|
||||||
|
# style-src 'unsafe-inline' is needed by Bootstrap and Chart.js (inline style attributes).
|
||||||
|
# connect-src is 'self' plus OVP_CSP_CONNECT_EXTRA (origins separated by spaces, empty by default): set it
|
||||||
|
# only when config.json points the UI to an API on another origin (the defaults /api/v1 and /profiles-api are
|
||||||
|
# proxied below, same origin). The value is validated by the deploy scripts and by the all-in-one entrypoint.
|
||||||
|
# One policy ($csp) for both places.
|
||||||
|
set $csp "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self' ${OVP_CSP_CONNECT_EXTRA}; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'";
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header X-Frame-Options "DENY" always;
|
||||||
|
add_header Referrer-Policy "no-referrer" always;
|
||||||
|
add_header Content-Security-Policy $csp always;
|
||||||
|
|
||||||
|
gzip on;
|
||||||
|
gzip_vary on;
|
||||||
|
gzip_min_length 1024;
|
||||||
|
gzip_types text/plain text/css text/javascript application/javascript application/json image/svg+xml;
|
||||||
|
|
||||||
location / {
|
location / {
|
||||||
try_files $uri $uri/ /index.html;
|
try_files $uri $uri/ /index.html;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Hashed build files never change under the same name
|
||||||
|
location /assets/ {
|
||||||
|
try_files $uri =404;
|
||||||
|
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header X-Frame-Options "DENY" always;
|
||||||
|
add_header Referrer-Policy "no-referrer" always;
|
||||||
|
add_header Content-Security-Policy $csp always;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The entry page and the runtime configuration must be revalidated after an update
|
||||||
|
# (expires -1 sends "Cache-Control: no-cache" and keeps the server-level headers)
|
||||||
|
location = /index.html {
|
||||||
|
expires -1;
|
||||||
|
}
|
||||||
|
location = /config.json {
|
||||||
|
expires -1;
|
||||||
|
}
|
||||||
|
|
||||||
# Модуль 1: Мониторинг (Flask, порт 5001)
|
# Модуль 1: Мониторинг (Flask, порт 5001)
|
||||||
location /api/ {
|
location /api/ {
|
||||||
proxy_pass http://${OVP_API_HOST}:${OVP_API_PORT};
|
proxy_pass http://${OVP_API_HOST}:${OVP_API_PORT};
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_pass_header Authorization;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# Модуль 2: Управление профилями (FastAPI, порт 8000)
|
# Модуль 2: Управление профилями (FastAPI, порт 8000)
|
||||||
@@ -34,4 +71,4 @@ server {
|
|||||||
location = /50x.html {
|
location = /50x.html {
|
||||||
root /usr/share/nginx/html;
|
root /usr/share/nginx/html;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import js from '@eslint/js';
|
||||||
|
import pluginVue from 'eslint-plugin-vue';
|
||||||
|
import globals from 'globals';
|
||||||
|
|
||||||
|
// Minimal rules: recommended JS + essential Vue (real errors only, no style rules)
|
||||||
|
export default [
|
||||||
|
{ ignores: ['dist/**', 'node_modules/**'] },
|
||||||
|
js.configs.recommended,
|
||||||
|
...pluginVue.configs['flat/essential'],
|
||||||
|
{
|
||||||
|
files: ['**/*.{js,vue}'],
|
||||||
|
languageOptions: {
|
||||||
|
globals: { ...globals.browser }
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
'vue/multi-word-component-names': 'off', // views are named after their route
|
||||||
|
'no-unused-vars': ['warn', { args: 'none', caughtErrors: 'none' }]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
files: ['**/*.test.js', 'eslint.config.js', 'vite.config.js'],
|
||||||
|
languageOptions: {
|
||||||
|
globals: { ...globals.node }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
];
|
||||||
+1
-1
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
<link rel="icon" type="image/svg+xml" href="/logo.svg" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>OpenVPN Controller</title>
|
<title>OpenVPN Controller</title>
|
||||||
</head>
|
</head>
|
||||||
|
|||||||
Generated
+1594
-16
File diff suppressed because it is too large.
Load diff
+9
-4
@@ -6,7 +6,9 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview",
|
||||||
|
"test": "vitest run",
|
||||||
|
"lint": "eslint src"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fortawesome/fontawesome-free": "^7.1.0",
|
"@fortawesome/fontawesome-free": "^7.1.0",
|
||||||
@@ -14,13 +16,16 @@
|
|||||||
"bootstrap": "^5.3.8",
|
"bootstrap": "^5.3.8",
|
||||||
"chart.js": "^4.5.1",
|
"chart.js": "^4.5.1",
|
||||||
"qrcode.vue": "^3.6.0",
|
"qrcode.vue": "^3.6.0",
|
||||||
"sass": "^1.97.2",
|
|
||||||
"sweetalert2": "^11.26.17",
|
|
||||||
"vue": "^3.5.24",
|
"vue": "^3.5.24",
|
||||||
"vue-router": "^4.6.4"
|
"vue-router": "^4.6.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^10.0.1",
|
||||||
"@vitejs/plugin-vue": "^6.0.1",
|
"@vitejs/plugin-vue": "^6.0.1",
|
||||||
"vite": "^7.2.4"
|
"eslint": "^10.12.0",
|
||||||
|
"eslint-plugin-vue": "^10.11.1",
|
||||||
|
"globals": "^17.13.0",
|
||||||
|
"vite": "^7.2.4",
|
||||||
|
"vitest": "^3.2.4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1 +0,0 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
|
||||||
|
Before Width: | Height: | Size: 1.5 KiB |
+15
-23
@@ -13,7 +13,7 @@
|
|||||||
<aside v-if="isAuthenticated" class="sidebar" :class="{ 'compact': isCompact }">
|
<aside v-if="isAuthenticated" class="sidebar" :class="{ 'compact': isCompact }">
|
||||||
<div class="sidebar-header">
|
<div class="sidebar-header">
|
||||||
<img src="./assets/logo.svg" alt="OpenVPN" class="sidebar-brand-icon">
|
<img src="./assets/logo.svg" alt="OpenVPN" class="sidebar-brand-icon">
|
||||||
<span class="brand-text">VPN Controller</span>
|
<span class="brand-text">OpenVPN Controller</span>
|
||||||
|
|
||||||
<button class="btn btn-link text-muted d-md-none ms-auto" @click="isSidebarOpen = false">
|
<button class="btn btn-link text-muted d-md-none ms-auto" @click="isSidebarOpen = false">
|
||||||
<i class="fas fa-times"></i>
|
<i class="fas fa-times"></i>
|
||||||
@@ -24,7 +24,6 @@
|
|||||||
|
|
||||||
<!-- SECTION: MONITORING -->
|
<!-- SECTION: MONITORING -->
|
||||||
<div class="nav-section-header">MONITORING</div>
|
<div class="nav-section-header">MONITORING</div>
|
||||||
<p></p>
|
|
||||||
<router-link to="/" class="nav-link" active-class="active" title="Analytics">
|
<router-link to="/" class="nav-link" active-class="active" title="Analytics">
|
||||||
<i class="fas fa-chart-line"></i> <span>Analytics</span>
|
<i class="fas fa-chart-line"></i> <span>Analytics</span>
|
||||||
</router-link>
|
</router-link>
|
||||||
@@ -34,7 +33,6 @@
|
|||||||
|
|
||||||
<!-- SECTION: CONFIGURATION -->
|
<!-- SECTION: CONFIGURATION -->
|
||||||
<div class="nav-section-header mt-3">CONFIGURATION</div>
|
<div class="nav-section-header mt-3">CONFIGURATION</div>
|
||||||
<p></p>
|
|
||||||
<router-link to="/config/pki" class="nav-link" active-class="active" title="PKI">
|
<router-link to="/config/pki" class="nav-link" active-class="active" title="PKI">
|
||||||
<i class="fas fa-fingerprint"></i> <span>PKI</span>
|
<i class="fas fa-fingerprint"></i> <span>PKI</span>
|
||||||
</router-link>
|
</router-link>
|
||||||
@@ -48,17 +46,18 @@
|
|||||||
|
|
||||||
<!-- SECTION: MANAGEMENT -->
|
<!-- SECTION: MANAGEMENT -->
|
||||||
<div class="nav-section-header mt-3">MANAGEMENT</div>
|
<div class="nav-section-header mt-3">MANAGEMENT</div>
|
||||||
<p></p>
|
|
||||||
<router-link to="/certificates" class="nav-link" active-class="active" title="Certificates">
|
<router-link to="/certificates" class="nav-link" active-class="active" title="Certificates">
|
||||||
<i class="fas fa-certificate"></i> <span>Certificates</span>
|
<i class="fas fa-certificate"></i> <span>Certificates</span>
|
||||||
</router-link>
|
</router-link>
|
||||||
<router-link to="/server" class="nav-link" active-class="active" title="Server Process">
|
<router-link to="/server" class="nav-link" active-class="active" title="Server Process">
|
||||||
<i class="fas fa-terminal"></i> <span>Server Process</span>
|
<i class="fas fa-terminal"></i> <span>Server Process</span>
|
||||||
</router-link>
|
</router-link>
|
||||||
|
<router-link to="/backup" class="nav-link" active-class="active" title="Backup and Restore">
|
||||||
|
<i class="fas fa-box-archive"></i> <span>Backup and Restore</span>
|
||||||
|
</router-link>
|
||||||
|
|
||||||
<!-- SECTION: ACCOUNT -->
|
<!-- SECTION: ACCOUNT -->
|
||||||
<div class="nav-section-header mt-3">ACCOUNT</div>
|
<div class="nav-section-header mt-3">ACCOUNT</div>
|
||||||
<p></p>
|
|
||||||
<router-link to="/account" class="nav-link" active-class="active" title="Account Settings">
|
<router-link to="/account" class="nav-link" active-class="active" title="Account Settings">
|
||||||
<i class="fas fa-user-cog"></i> <span>Account Settings</span>
|
<i class="fas fa-user-cog"></i> <span>Account Settings</span>
|
||||||
</router-link>
|
</router-link>
|
||||||
@@ -93,10 +92,10 @@
|
|||||||
<i class="fas fa-globe me-1 text-muted"></i>{{ timezoneAbbr }}
|
<i class="fas fa-globe me-1 text-muted"></i>{{ timezoneAbbr }}
|
||||||
</span>
|
</span>
|
||||||
<button class="btn-header" @click="toggleTheme" title="Toggle Theme">
|
<button class="btn-header" @click="toggleTheme" title="Toggle Theme">
|
||||||
<i class="fas" :class="isDark ? 'fa-sun' : 'fa-moon'" id="themeIcon"></i>
|
<i class="fas" :class="isDark ? 'fa-sun' : 'fa-moon'"></i>
|
||||||
</button>
|
</button>
|
||||||
<button class="btn-header me-2" @click="refreshPage" title="Refresh">
|
<button class="btn-header me-2" @click="refreshPage" title="Refresh">
|
||||||
<i class="fas fa-sync-alt" id="refreshIcon"></i>
|
<i class="fas fa-sync-alt"></i>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<div class="header-divider d-none d-md-block"></div>
|
<div class="header-divider d-none d-md-block"></div>
|
||||||
@@ -135,11 +134,12 @@ import { useRoute, useRouter } from 'vue-router';
|
|||||||
import ToastContainer from './components/ToastContainer.vue';
|
import ToastContainer from './components/ToastContainer.vue';
|
||||||
import { usePkiStatus } from './composables/usePkiStatus';
|
import { usePkiStatus } from './composables/usePkiStatus';
|
||||||
import { useToast } from './composables/useToast';
|
import { useToast } from './composables/useToast';
|
||||||
|
import { useTheme } from './composables/useTheme';
|
||||||
|
|
||||||
const { loadConfig, isLoaded } = useAppConfig();
|
const { loadConfig, isLoaded } = useAppConfig();
|
||||||
const { apiClient } = useApi();
|
const { apiClient } = useApi();
|
||||||
const timezoneAbbr = ref(new Date().toLocaleTimeString('en-us',{timeZoneName:'short'}).split(' ')[2] || 'UTC');
|
const timezoneAbbr = ref(new Date().toLocaleTimeString('en-us',{timeZoneName:'short'}).split(' ')[2] || 'UTC');
|
||||||
const isDark = ref(false);
|
const { isDark, toggleTheme } = useTheme();
|
||||||
const refreshKey = ref(0);
|
const refreshKey = ref(0);
|
||||||
const isSidebarOpen = ref(false);
|
const isSidebarOpen = ref(false);
|
||||||
const isCompact = ref(false);
|
const isCompact = ref(false);
|
||||||
@@ -148,7 +148,11 @@ const router = useRouter();
|
|||||||
const { status: pkiStatus, refresh: refreshPkiStatus } = usePkiStatus();
|
const { status: pkiStatus, refresh: refreshPkiStatus } = usePkiStatus();
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
|
|
||||||
const isAuthenticated = computed(() => route.name !== 'Login');
|
// Signed in: a stored token on a non-public page (the token is not reactive: it is re-read on every navigation)
|
||||||
|
const isAuthenticated = computed(() => {
|
||||||
|
void route.fullPath;
|
||||||
|
return !route.meta.public && !!localStorage.getItem('ovpmon_token');
|
||||||
|
});
|
||||||
const username = ref(localStorage.getItem('ovpmon_user') || '');
|
const username = ref(localStorage.getItem('ovpmon_user') || '');
|
||||||
|
|
||||||
// Keep the header name in sync with the server (login, rename, stale session)
|
// Keep the header name in sync with the server (login, rename, stale session)
|
||||||
@@ -180,13 +184,6 @@ const handleLogout = () => {
|
|||||||
router.push('/login');
|
router.push('/login');
|
||||||
};
|
};
|
||||||
|
|
||||||
const toggleTheme = () => {
|
|
||||||
isDark.value = !isDark.value;
|
|
||||||
const theme = isDark.value ? 'dark' : 'light';
|
|
||||||
document.documentElement.setAttribute('data-theme', theme);
|
|
||||||
localStorage.setItem('theme', theme);
|
|
||||||
};
|
|
||||||
|
|
||||||
const toggleSidebar = () => {
|
const toggleSidebar = () => {
|
||||||
isCompact.value = !isCompact.value;
|
isCompact.value = !isCompact.value;
|
||||||
localStorage.setItem('sidebarCompact', isCompact.value);
|
localStorage.setItem('sidebarCompact', isCompact.value);
|
||||||
@@ -199,7 +196,7 @@ const refreshPage = () => {
|
|||||||
// Close sidebar on route change
|
// Close sidebar on route change
|
||||||
watch(() => route.path, () => {
|
watch(() => route.path, () => {
|
||||||
isSidebarOpen.value = false;
|
isSidebarOpen.value = false;
|
||||||
if (route.name !== 'Login') {
|
if (isAuthenticated.value) {
|
||||||
syncUsername();
|
syncUsername();
|
||||||
refreshPkiStatus();
|
refreshPkiStatus();
|
||||||
}
|
}
|
||||||
@@ -208,15 +205,10 @@ watch(() => route.path, () => {
|
|||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
await loadConfig();
|
await loadConfig();
|
||||||
window.addEventListener('ovpmon-user-changed', onUserChanged);
|
window.addEventListener('ovpmon-user-changed', onUserChanged);
|
||||||
if (route.name !== 'Login') {
|
if (isAuthenticated.value) {
|
||||||
syncUsername();
|
syncUsername();
|
||||||
refreshPkiStatus();
|
refreshPkiStatus();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Init Theme
|
|
||||||
const savedTheme = localStorage.getItem('theme') || 'light';
|
|
||||||
isDark.value = savedTheme === 'dark';
|
|
||||||
document.documentElement.setAttribute('data-theme', savedTheme);
|
|
||||||
|
|
||||||
// Init Sidebar
|
// Init Sidebar
|
||||||
const savedCompact = localStorage.getItem('sidebarCompact');
|
const savedCompact = localStorage.getItem('sidebarCompact');
|
||||||
|
|||||||
@@ -272,6 +272,11 @@ body {
|
|||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Space between a section header and its first link (also kept when the header is hidden in compact mode) */
|
||||||
|
.nav-section-header + .nav-link {
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
/* Compact Mode Styles */
|
/* Compact Mode Styles */
|
||||||
.sidebar.compact {
|
.sidebar.compact {
|
||||||
width: 64px;
|
width: 64px;
|
||||||
@@ -1999,4 +2004,40 @@ input[type="number"].config-input {
|
|||||||
.stats-grid .stat-item.full-width {
|
.stats-grid .stat-item.full-width {
|
||||||
grid-column: span 1;
|
grid-column: span 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* --- BACKUP AND RESTORE PAGE --- */
|
||||||
|
.backup-page {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 24px;
|
||||||
|
padding: 40px 0;
|
||||||
|
background-color: var(--bg-body);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Same card as the configuration pages, wider for the tables */
|
||||||
|
.config-card.backup-card {
|
||||||
|
width: 960px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.backup-steps {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0 0 12px;
|
||||||
|
padding: 0;
|
||||||
|
color: var(--text-main);
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.backup-steps li {
|
||||||
|
padding: 3px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.backup-steps li i {
|
||||||
|
width: 22px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.backup-result {
|
||||||
|
padding: 6px 0;
|
||||||
|
border-top: 1px solid var(--border-subtle);
|
||||||
|
}
|
||||||
@@ -22,7 +22,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref, onMounted, onUnmounted } from 'vue';
|
import { ref, computed, onMounted, onUnmounted } from 'vue';
|
||||||
import { Modal } from 'bootstrap';
|
import { Modal } from 'bootstrap';
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
@@ -40,11 +40,11 @@ const props = defineProps({
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const emit = defineEmits(['close', 'opened', 'closed']);
|
const emit = defineEmits(['opened', 'closed']);
|
||||||
|
|
||||||
const modalRef = ref(null);
|
const modalRef = ref(null);
|
||||||
let bsModal = null;
|
let bsModal = null;
|
||||||
const sizeClass = props.size || '';
|
const sizeClass = computed(() => props.size || '');
|
||||||
|
|
||||||
const show = () => {
|
const show = () => {
|
||||||
bsModal?.show();
|
bsModal?.show();
|
||||||
@@ -63,7 +63,6 @@ onMounted(() => {
|
|||||||
|
|
||||||
modalRef.value.addEventListener('hidden.bs.modal', () => {
|
modalRef.value.addEventListener('hidden.bs.modal', () => {
|
||||||
emit('closed');
|
emit('closed');
|
||||||
emit('close');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<template>
|
<template>
|
||||||
<BaseModal id="confirmModal" :title="title" ref="modal">
|
<BaseModal :id="modalId" :title="title" ref="modal">
|
||||||
<template #body>
|
<template #body>
|
||||||
<p class="text-main">{{ message }}</p>
|
<p class="text-main" style="white-space: pre-line;">{{ message }}</p>
|
||||||
</template>
|
</template>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<button v-if="showCancel" type="button" class="btn-action btn-action-secondary" @click="close">Cancel</button>
|
<button v-if="showCancel" type="button" class="btn-action btn-action-secondary" @click="close">Cancel</button>
|
||||||
@@ -13,9 +13,11 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref } from 'vue';
|
import { ref, useId } from 'vue';
|
||||||
import BaseModal from './BaseModal.vue';
|
import BaseModal from './BaseModal.vue';
|
||||||
|
|
||||||
|
// Unique element id: several ConfirmModal instances may live on one page
|
||||||
|
const modalId = `confirm-${useId()}`;
|
||||||
const emit = defineEmits(['confirm']);
|
const emit = defineEmits(['confirm']);
|
||||||
const modal = ref(null);
|
const modal = ref(null);
|
||||||
|
|
||||||
|
|||||||
@@ -54,15 +54,12 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
|
import { ref, onMounted, onUnmounted } from 'vue';
|
||||||
import Chart from 'chart.js/auto';
|
|
||||||
import { useApi } from '../composables/useApi';
|
import { useApi } from '../composables/useApi';
|
||||||
import { useFormatters } from '../composables/useFormatters';
|
import { useTrafficChart } from '../composables/useTrafficChart';
|
||||||
import { Modal } from 'bootstrap';
|
import { Modal } from 'bootstrap';
|
||||||
|
|
||||||
const props = defineProps(['modelValue']); // If we wanted v-model control, but using manual open method for now
|
|
||||||
const { fetchClientHistory } = useApi();
|
const { fetchClientHistory } = useApi();
|
||||||
const { parseServerDate } = useFormatters();
|
|
||||||
|
|
||||||
const modalRef = ref(null);
|
const modalRef = ref(null);
|
||||||
const chartCanvas = ref(null);
|
const chartCanvas = ref(null);
|
||||||
@@ -71,10 +68,10 @@ const range = ref('24h');
|
|||||||
const isSpeedMode = ref(false);
|
const isSpeedMode = ref(false);
|
||||||
const loading = ref(false);
|
const loading = ref(false);
|
||||||
let bsModal = null;
|
let bsModal = null;
|
||||||
let chartInstance = null;
|
|
||||||
let cachedData = null;
|
let cachedData = null;
|
||||||
|
let requestId = 0; // the latest request wins: a slow answer for an old range or client is dropped
|
||||||
|
|
||||||
const MAX_CHART_POINTS = 48;
|
const chart = useTrafficChart(chartCanvas, { maxPoints: 48 });
|
||||||
|
|
||||||
const open = (name) => {
|
const open = (name) => {
|
||||||
clientName.value = name;
|
clientName.value = name;
|
||||||
@@ -90,159 +87,52 @@ const close = () => {
|
|||||||
|
|
||||||
const loadHistory = async () => {
|
const loadHistory = async () => {
|
||||||
if (!clientName.value) return;
|
if (!clientName.value) return;
|
||||||
|
const id = ++requestId;
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
try {
|
try {
|
||||||
const res = await fetchClientHistory(clientName.value, range.value);
|
const res = await fetchClientHistory(clientName.value, range.value);
|
||||||
|
if (id !== requestId) return;
|
||||||
if (res.success && res.data.history) {
|
if (res.success && res.data.history) {
|
||||||
cachedData = res.data.history;
|
// Map the raw fields to the point format of useTrafficChart
|
||||||
|
cachedData = res.data.history.map(p => ({
|
||||||
|
timestamp: p.timestamp,
|
||||||
|
bytes_received: p.bytes_received,
|
||||||
|
bytes_sent: p.bytes_sent,
|
||||||
|
rx_rate_mbps: p.bytes_received_rate_mbps,
|
||||||
|
tx_rate_mbps: p.bytes_sent_rate_mbps
|
||||||
|
}));
|
||||||
renderChart();
|
renderChart();
|
||||||
} else {
|
} else {
|
||||||
cachedData = [];
|
cachedData = [];
|
||||||
if (chartInstance) chartInstance.destroy();
|
chart.destroy();
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
if (id === requestId) console.error(e);
|
||||||
} finally {
|
} finally {
|
||||||
loading.value = false;
|
if (id === requestId) loading.value = false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const renderChart = () => {
|
const renderChart = () => {
|
||||||
if (!chartCanvas.value || !cachedData) return;
|
if (!cachedData) return;
|
||||||
if (chartInstance) chartInstance.destroy();
|
chart.render(cachedData, { range: range.value, speedMode: isSpeedMode.value });
|
||||||
|
|
||||||
const ctx = chartCanvas.value.getContext('2d');
|
|
||||||
const downsampled = downsampleData(cachedData, MAX_CHART_POINTS);
|
|
||||||
|
|
||||||
const labels = [];
|
|
||||||
const dataRx = [];
|
|
||||||
const dataTx = [];
|
|
||||||
|
|
||||||
downsampled.forEach(point => {
|
|
||||||
const d = parseServerDate(point.timestamp);
|
|
||||||
let label = '';
|
|
||||||
|
|
||||||
if(range.value.includes('h') || range.value === '1d') {
|
|
||||||
label = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
|
||||||
} else {
|
|
||||||
label = d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' +
|
|
||||||
d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
|
||||||
}
|
|
||||||
labels.push(label);
|
|
||||||
|
|
||||||
if (!isSpeedMode.value) {
|
|
||||||
dataRx.push(point.bytes_received / (1024 * 1024)); // MB
|
|
||||||
dataTx.push(point.bytes_sent / (1024 * 1024)); // MB
|
|
||||||
} else {
|
|
||||||
dataRx.push(point.bytes_received_rate_mbps);
|
|
||||||
dataTx.push(point.bytes_sent_rate_mbps);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
|
|
||||||
const gridColor = isDark ? 'rgba(240, 246, 252, 0.1)' : 'rgba(0,0,0,0.05)';
|
|
||||||
const textColor = isDark ? '#8b949e' : '#6c757d';
|
|
||||||
|
|
||||||
chartInstance = new Chart(ctx, {
|
|
||||||
type: 'line',
|
|
||||||
data: {
|
|
||||||
labels,
|
|
||||||
datasets: [
|
|
||||||
{
|
|
||||||
label: !isSpeedMode.value ? 'Received (MB)' : 'RX Mbps',
|
|
||||||
data: dataRx,
|
|
||||||
borderColor: '#1652B8', // OpenVPN Blue
|
|
||||||
backgroundColor: 'rgba(22, 82, 184, 0.15)',
|
|
||||||
borderWidth: 2,
|
|
||||||
fill: true,
|
|
||||||
tension: 0.3,
|
|
||||||
pointRadius: 3,
|
|
||||||
pointHoverRadius: 4
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: !isSpeedMode.value ? 'Sent (MB)' : 'TX Mbps',
|
|
||||||
data: dataTx,
|
|
||||||
borderColor: '#EC7C31', // OpenVPN Orange
|
|
||||||
backgroundColor: 'rgba(236, 124, 49, 0.15)',
|
|
||||||
borderWidth: 2,
|
|
||||||
fill: true,
|
|
||||||
tension: 0.3,
|
|
||||||
pointRadius: 3,
|
|
||||||
pointHoverRadius: 4
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
options: {
|
|
||||||
responsive: true,
|
|
||||||
maintainAspectRatio: false,
|
|
||||||
interaction: {
|
|
||||||
mode: 'index',
|
|
||||||
intersect: false,
|
|
||||||
},
|
|
||||||
plugins: {
|
|
||||||
legend: { labels: { color: textColor } }
|
|
||||||
},
|
|
||||||
scales: {
|
|
||||||
x: {
|
|
||||||
ticks: { color: textColor, maxTicksLimit: 8 },
|
|
||||||
grid: { color: gridColor }
|
|
||||||
},
|
|
||||||
y: {
|
|
||||||
beginAtZero: true,
|
|
||||||
ticks: { color: textColor },
|
|
||||||
grid: { color: gridColor }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const downsampleData = (data, maxPoints) => {
|
|
||||||
if (!data || data.length === 0) return [];
|
|
||||||
if (data.length <= maxPoints) return data;
|
|
||||||
|
|
||||||
const blockSize = Math.ceil(data.length / maxPoints);
|
|
||||||
const result = [];
|
|
||||||
|
|
||||||
for (let i = 0; i < data.length; i += blockSize) {
|
|
||||||
const chunk = data.slice(i, i + blockSize);
|
|
||||||
if (chunk.length === 0) continue;
|
|
||||||
|
|
||||||
let sumRx = 0, sumTx = 0;
|
|
||||||
let maxRxRate = 0, maxTxRate = 0;
|
|
||||||
|
|
||||||
chunk.forEach(pt => {
|
|
||||||
sumRx += (pt.bytes_received || 0);
|
|
||||||
sumTx += (pt.bytes_sent || 0);
|
|
||||||
maxRxRate = Math.max(maxRxRate, pt.bytes_received_rate_mbps || 0);
|
|
||||||
maxTxRate = Math.max(maxTxRate, pt.bytes_sent_rate_mbps || 0);
|
|
||||||
});
|
|
||||||
|
|
||||||
result.push({
|
|
||||||
timestamp: chunk[0].timestamp,
|
|
||||||
bytes_received: sumRx,
|
|
||||||
bytes_sent: sumTx,
|
|
||||||
bytes_received_rate_mbps: maxRxRate,
|
|
||||||
bytes_sent_rate_mbps: maxTxRate
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
bsModal = new Modal(modalRef.value);
|
bsModal = new Modal(modalRef.value);
|
||||||
|
|
||||||
// Clean up chart on close
|
// Clean up the chart on close and drop answers that are still on the way
|
||||||
modalRef.value.addEventListener('hidden.bs.modal', () => {
|
modalRef.value.addEventListener('hidden.bs.modal', () => {
|
||||||
if (chartInstance) {
|
requestId++;
|
||||||
chartInstance.destroy();
|
loading.value = false;
|
||||||
chartInstance = null;
|
cachedData = null;
|
||||||
}
|
chart.destroy();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
if (chartInstance) chartInstance.destroy();
|
requestId++;
|
||||||
|
bsModal?.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
defineExpose({ open, close });
|
defineExpose({ open, close });
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
<template>
|
<template>
|
||||||
<BaseModal id="newClientModal" title="Create New Client" ref="modal">
|
<BaseModal id="newClientModal" title="Create New Client" ref="modal" @opened="inputRef?.focus()">
|
||||||
<template #body>
|
<template #body>
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="clientName" class="form-label small text-muted text-uppercase fw-bold">Client Name</label>
|
<label for="clientName" class="form-label small text-muted text-uppercase fw-bold">Client Name</label>
|
||||||
<div class="input-group">
|
<div class="input-group">
|
||||||
<span class="input-group-text"><i class="fas fa-user"></i></span>
|
<span class="input-group-text"><i class="fas fa-user"></i></span>
|
||||||
<input type="text" class="form-control" id="clientName" v-model="clientName" placeholder="e.g. laptop-user" @keyup.enter="confirm" ref="inputRef">
|
<input type="text" class="form-control" :class="{ 'is-invalid': clientName && !isValid }" id="clientName"
|
||||||
|
v-model="clientName" placeholder="e.g. laptop-user" maxlength="64" autocomplete="off" @keyup.enter="confirm" ref="inputRef">
|
||||||
|
</div>
|
||||||
|
<div v-if="clientName && !isValid" class="text-danger small mt-2">
|
||||||
|
Letters, digits, dashes and underscores only; the first character must be a letter or a digit.
|
||||||
</div>
|
</div>
|
||||||
<div class="form-text mt-2 text-muted small">
|
<div class="form-text mt-2 text-muted small">
|
||||||
<i class="fas fa-info-circle me-1"></i> Use only alphanumeric characters, dashes, or underscores.
|
<i class="fas fa-info-circle me-1"></i> Use only alphanumeric characters, dashes, or underscores.
|
||||||
@@ -14,7 +18,7 @@
|
|||||||
</template>
|
</template>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<button type="button" class="btn-action btn-action-secondary" @click="close">Cancel</button>
|
<button type="button" class="btn-action btn-action-secondary" @click="close">Cancel</button>
|
||||||
<button type="button" class="btn-action btn-action-save" @click="confirm" :disabled="!clientName">
|
<button type="button" class="btn-action btn-action-save" @click="confirm" :disabled="!isValid">
|
||||||
Create Client
|
Create Client
|
||||||
</button>
|
</button>
|
||||||
</template>
|
</template>
|
||||||
@@ -22,7 +26,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref } from 'vue';
|
import { ref, computed } from 'vue';
|
||||||
import BaseModal from './BaseModal.vue';
|
import BaseModal from './BaseModal.vue';
|
||||||
|
|
||||||
const emit = defineEmits(['create']);
|
const emit = defineEmits(['create']);
|
||||||
@@ -30,10 +34,13 @@ const modal = ref(null);
|
|||||||
const clientName = ref('');
|
const clientName = ref('');
|
||||||
const inputRef = ref(null);
|
const inputRef = ref(null);
|
||||||
|
|
||||||
|
// Same rule as the profiler API (without dots): 1-64 characters, no leading dash or underscore
|
||||||
|
const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
||||||
|
const isValid = computed(() => NAME_RE.test(clientName.value));
|
||||||
|
|
||||||
const open = () => {
|
const open = () => {
|
||||||
clientName.value = '';
|
clientName.value = '';
|
||||||
modal.value.show();
|
modal.value.show(); // the input is focused on the opened event
|
||||||
setTimeout(() => inputRef.value?.focus(), 500);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const close = () => {
|
const close = () => {
|
||||||
@@ -41,7 +48,7 @@ const close = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const confirm = () => {
|
const confirm = () => {
|
||||||
if (clientName.value) {
|
if (isValid.value) {
|
||||||
emit('create', clientName.value);
|
emit('create', clientName.value);
|
||||||
close();
|
close();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<template #header>
|
<template #header>
|
||||||
<div class="d-flex align-items-center gap-2 flex-wrap">
|
<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>
|
<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>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
<template #body>
|
<template #body>
|
||||||
@@ -36,6 +36,7 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { ref, computed } from 'vue';
|
import { ref, computed } from 'vue';
|
||||||
import BaseModal from './BaseModal.vue';
|
import BaseModal from './BaseModal.vue';
|
||||||
|
import StatusBadge from './StatusBadge.vue';
|
||||||
|
|
||||||
const emit = defineEmits(['save']);
|
const emit = defineEmits(['save']);
|
||||||
const modal = ref(null);
|
const modal = ref(null);
|
||||||
@@ -44,14 +45,6 @@ const note = ref('');
|
|||||||
|
|
||||||
const dirty = computed(() => note.value !== (profile.value?.note || ''));
|
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 daysLabel = computed(() => {
|
||||||
const days = profile.value?.days_remaining;
|
const days = profile.value?.days_remaining;
|
||||||
if (days == null) return '';
|
if (days == null) return '';
|
||||||
|
|||||||
@@ -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>
|
||||||
@@ -4,13 +4,35 @@ import { useAppConfig } from './useAppConfig';
|
|||||||
// Singleton instances
|
// Singleton instances
|
||||||
const apiClient = axios.create();
|
const apiClient = axios.create();
|
||||||
const profilesApiClient = axios.create();
|
const profilesApiClient = axios.create();
|
||||||
|
// Auth endpoints (/api/auth): login, 2FA, password and username changes
|
||||||
|
const authApiClient = axios.create();
|
||||||
|
|
||||||
// Helper to get base URLs
|
// Helper to get base URLs
|
||||||
const getBaseUrl = (config) => config?.api_base_url || 'http://localhost:5001/api/v1';
|
const getBaseUrl = (config) => config?.api_base_url || 'http://localhost:5001/api/v1';
|
||||||
const getProfilesBaseUrl = (config) => config?.profiles_api_base_url || 'http://localhost:8000';
|
const getProfilesBaseUrl = (config) => config?.profiles_api_base_url || 'http://localhost:8000';
|
||||||
|
// The auth routes sit next to the API root: /api/v1 -> /api/auth
|
||||||
|
const getAuthBaseUrl = (config) => {
|
||||||
|
const base = getBaseUrl(config).replace(/\/+$/, '');
|
||||||
|
return /\/v1$/.test(base) ? base.replace(/\/v1$/, '/auth') : base + '/../auth';
|
||||||
|
};
|
||||||
|
|
||||||
// Add interceptors to handle Auth and Dynamic Base URLs
|
// 401 on a regular API request: the session is gone, clear it and go to the login page
|
||||||
const setupInterceptors = (instance, getBase) => {
|
export const handleUnauthorized = (error) => {
|
||||||
|
if (error.response && error.response.status === 401) {
|
||||||
|
localStorage.removeItem('ovpmon_token');
|
||||||
|
localStorage.removeItem('ovpmon_user');
|
||||||
|
// Redirecting using window.location for absolute refresh
|
||||||
|
if (window.location.pathname !== '/login') {
|
||||||
|
window.location.href = '/login';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Promise.reject(error);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add interceptors to handle Auth and Dynamic Base URLs.
|
||||||
|
// endSessionOn401 is false for authApiClient: /auth/* answers 401 for a wrong current password or
|
||||||
|
// 2FA code (login, change-password, change-username). That is a form error, not an expired session.
|
||||||
|
const setupInterceptors = (instance, getBase, { endSessionOn401 = true } = {}) => {
|
||||||
instance.interceptors.request.use((reqConfig) => {
|
instance.interceptors.request.use((reqConfig) => {
|
||||||
const { config } = useAppConfig();
|
const { config } = useAppConfig();
|
||||||
reqConfig.baseURL = getBase(config.value);
|
reqConfig.baseURL = getBase(config.value);
|
||||||
@@ -22,24 +44,14 @@ const setupInterceptors = (instance, getBase) => {
|
|||||||
return reqConfig;
|
return reqConfig;
|
||||||
});
|
});
|
||||||
|
|
||||||
instance.interceptors.response.use(
|
if (endSessionOn401) {
|
||||||
response => response,
|
instance.interceptors.response.use(response => response, handleUnauthorized);
|
||||||
error => {
|
}
|
||||||
if (error.response && error.response.status === 401) {
|
|
||||||
localStorage.removeItem('ovpmon_token');
|
|
||||||
localStorage.removeItem('ovpmon_user');
|
|
||||||
// Redirecting using window.location for absolute refresh
|
|
||||||
if (window.location.pathname !== '/login') {
|
|
||||||
window.location.href = '/login';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Promise.reject(error);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
setupInterceptors(apiClient, getBaseUrl);
|
setupInterceptors(apiClient, getBaseUrl);
|
||||||
setupInterceptors(profilesApiClient, getProfilesBaseUrl);
|
setupInterceptors(profilesApiClient, getProfilesBaseUrl);
|
||||||
|
setupInterceptors(authApiClient, getAuthBaseUrl, { endSessionOn401: false });
|
||||||
|
|
||||||
export function useApi() {
|
export function useApi() {
|
||||||
const fetchStats = async () => {
|
const fetchStats = async () => {
|
||||||
@@ -59,13 +71,14 @@ export function useApi() {
|
|||||||
|
|
||||||
const fetchCertificates = async () => {
|
const fetchCertificates = async () => {
|
||||||
const res = await profilesApiClient.get('/profiles');
|
const res = await profilesApiClient.get('/profiles');
|
||||||
return res.data;
|
// GET /profiles returns a plain array (not the {success, data} envelope of the monitoring API)
|
||||||
|
return Array.isArray(res.data) ? res.data : [];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
apiClient,
|
apiClient,
|
||||||
profilesApiClient,
|
profilesApiClient,
|
||||||
|
authApiClient,
|
||||||
fetchStats,
|
fetchStats,
|
||||||
fetchClientHistory,
|
fetchClientHistory,
|
||||||
fetchAnalytics,
|
fetchAnalytics,
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||||
|
import { AxiosError } from 'axios';
|
||||||
|
|
||||||
|
const store = {};
|
||||||
|
let location;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
for (const k of Object.keys(store)) delete store[k];
|
||||||
|
store.ovpmon_token = 'tok';
|
||||||
|
store.ovpmon_user = 'admin';
|
||||||
|
location = { pathname: '/account', href: '/account' };
|
||||||
|
vi.stubGlobal('localStorage', {
|
||||||
|
getItem: (k) => (k in store ? store[k] : null),
|
||||||
|
setItem: (k, v) => { store[k] = String(v); },
|
||||||
|
removeItem: (k) => { delete store[k]; }
|
||||||
|
});
|
||||||
|
vi.stubGlobal('window', { location });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Make the client answer with the given status without any network
|
||||||
|
const failWith = async (client, status, url) => {
|
||||||
|
client.defaults.adapter = (config) => Promise.reject(
|
||||||
|
new AxiosError('failed', 'ERR_BAD_REQUEST', config, null, { status, data: {}, config })
|
||||||
|
);
|
||||||
|
await client.post(url).catch(() => {});
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('401 handling', () => {
|
||||||
|
it('keeps the session on 401 from /auth/* (wrong password or 2FA code)', async () => {
|
||||||
|
const { useApi } = await import('./useApi');
|
||||||
|
await failWith(useApi().authApiClient, 401, '/change-password');
|
||||||
|
expect(store.ovpmon_token).toBe('tok');
|
||||||
|
expect(location.href).toBe('/account');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ends the session on 401 from other requests', async () => {
|
||||||
|
const { useApi } = await import('./useApi');
|
||||||
|
await failWith(useApi().apiClient, 401, '/stats');
|
||||||
|
expect(store.ovpmon_token).toBeUndefined();
|
||||||
|
expect(location.href).toBe('/login');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds the auth base URL next to the API root', async () => {
|
||||||
|
const { useApi } = await import('./useApi');
|
||||||
|
let seen;
|
||||||
|
const client = useApi().authApiClient;
|
||||||
|
client.defaults.adapter = (config) => { seen = config; return Promise.resolve({ status: 200, data: {}, config }); };
|
||||||
|
await client.post('/login');
|
||||||
|
expect(seen.baseURL).toBe('http://localhost:5001/api/auth');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores other error codes', async () => {
|
||||||
|
const { useApi } = await import('./useApi');
|
||||||
|
await failWith(useApi().profilesApiClient, 500, '/profiles');
|
||||||
|
expect(store.ovpmon_token).toBe('tok');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,15 +1,17 @@
|
|||||||
export function useFormatters() {
|
export function useFormatters() {
|
||||||
function formatBytes(bytes, decimals = 2) {
|
function formatBytes(bytes, decimals = 2) {
|
||||||
if (bytes === 0) return '0 B';
|
const value = Number(bytes);
|
||||||
|
// null, undefined, NaN and negative values are shown as zero
|
||||||
|
if (!Number.isFinite(value) || value <= 0) return '0 B';
|
||||||
const k = 1024;
|
const k = 1024;
|
||||||
const dm = decimals < 0 ? 0 : decimals;
|
const dm = decimals < 0 ? 0 : decimals;
|
||||||
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
|
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
const i = Math.min(Math.max(Math.floor(Math.log(value) / Math.log(k)), 0), sizes.length - 1);
|
||||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
|
return parseFloat((value / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatRate(rate) {
|
function formatRate(rate) {
|
||||||
return parseFloat(rate).toFixed(3) + ' Mbps';
|
return (parseFloat(rate) || 0).toFixed(3) + ' Mbps';
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseServerDate(dateStr) {
|
function parseServerDate(dateStr) {
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { useFormatters } from './useFormatters';
|
||||||
|
|
||||||
|
const { formatBytes, formatRate } = useFormatters();
|
||||||
|
|
||||||
|
describe('formatBytes', () => {
|
||||||
|
it('formats regular values', () => {
|
||||||
|
expect(formatBytes(1536)).toBe('1.5 KB');
|
||||||
|
expect(formatBytes(5 * 1024 * 1024)).toBe('5 MB');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows zero for empty, non-numeric and negative values', () => {
|
||||||
|
for (const v of [0, null, undefined, NaN, 'abc', -5, Infinity]) {
|
||||||
|
expect(formatBytes(v)).toBe('0 B');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stays inside the unit table', () => {
|
||||||
|
expect(formatBytes(0.5)).toBe('0.5 B');
|
||||||
|
expect(formatBytes(Math.pow(1024, 6))).toMatch(/ TB$/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('formatRate', () => {
|
||||||
|
it('does not produce NaN', () => {
|
||||||
|
expect(formatRate(1.23456)).toBe('1.235 Mbps');
|
||||||
|
expect(formatRate(null)).toBe('0.000 Mbps');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { ref, onMounted, onUnmounted } from 'vue';
|
||||||
|
|
||||||
|
const STORAGE_KEY = 'theme';
|
||||||
|
|
||||||
|
const isDark = ref(false);
|
||||||
|
|
||||||
|
const apply = (theme) => {
|
||||||
|
isDark.value = theme === 'dark';
|
||||||
|
document.documentElement.setAttribute('data-theme', theme);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Saved choice first, then the system setting (prefers-color-scheme) on the first visit.
|
||||||
|
// Called from main.js before the app is mounted, so the page never flashes in the wrong theme.
|
||||||
|
export const initTheme = () => {
|
||||||
|
let theme = null;
|
||||||
|
try { theme = localStorage.getItem(STORAGE_KEY); } catch (e) { /* storage blocked */ }
|
||||||
|
if (theme !== 'dark' && theme !== 'light') {
|
||||||
|
theme = window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||||
|
}
|
||||||
|
apply(theme);
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleTheme = () => {
|
||||||
|
const theme = isDark.value ? 'light' : 'dark';
|
||||||
|
apply(theme);
|
||||||
|
try { localStorage.setItem(STORAGE_KEY, theme); } catch (e) { /* storage blocked */ }
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useTheme() {
|
||||||
|
return { isDark, toggleTheme };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call `callback` whenever data-theme of <html> changes; the observer is released with the component
|
||||||
|
export function useThemeObserver(callback) {
|
||||||
|
let observer = null;
|
||||||
|
onMounted(() => {
|
||||||
|
observer = new MutationObserver((mutations) => {
|
||||||
|
if (mutations.some(m => m.attributeName === 'data-theme')) callback();
|
||||||
|
});
|
||||||
|
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
|
||||||
|
});
|
||||||
|
onUnmounted(() => observer?.disconnect());
|
||||||
|
}
|
||||||
@@ -0,0 +1,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
@@ -8,23 +8,10 @@ import 'bootstrap/dist/js/bootstrap.bundle.min.js';
|
|||||||
import '@fortawesome/fontawesome-free/css/all.min.css';
|
import '@fortawesome/fontawesome-free/css/all.min.css';
|
||||||
|
|
||||||
import './assets/main.css';
|
import './assets/main.css';
|
||||||
import axios from 'axios';
|
import { initTheme } from './composables/useTheme';
|
||||||
|
|
||||||
// Global Axios Defaults (No Base URL - handled by useApi.js)
|
// Theme is applied before mounting: no flash of the wrong theme
|
||||||
// We keep global error handling for 401s as a fallback
|
initTheme();
|
||||||
axios.interceptors.response.use(
|
|
||||||
response => response,
|
|
||||||
error => {
|
|
||||||
if (error.response && error.response.status === 401) {
|
|
||||||
localStorage.removeItem('ovpmon_token');
|
|
||||||
localStorage.removeItem('ovpmon_user');
|
|
||||||
if (window.location.pathname !== '/login') {
|
|
||||||
window.location.href = '/login';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Promise.reject(error);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
const app = createApp(App);
|
const app = createApp(App);
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { createRouter, createWebHistory } from 'vue-router';
|
import { createRouter, createWebHistory } from 'vue-router';
|
||||||
import Clients from '../views/Clients.vue';
|
|
||||||
import Login from '../views/Login.vue';
|
import Login from '../views/Login.vue';
|
||||||
import { usePkiStatus } from '../composables/usePkiStatus';
|
import { usePkiStatus } from '../composables/usePkiStatus';
|
||||||
import { useToast } from '../composables/useToast';
|
import { useToast } from '../composables/useToast';
|
||||||
@@ -13,7 +12,7 @@ const routes = [
|
|||||||
{
|
{
|
||||||
path: '/clients',
|
path: '/clients',
|
||||||
name: 'Clients',
|
name: 'Clients',
|
||||||
component: Clients
|
component: () => import('../views/Clients.vue')
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: '/certificates',
|
path: '/certificates',
|
||||||
@@ -37,6 +36,11 @@ const routes = [
|
|||||||
name: 'ServerManagement',
|
name: 'ServerManagement',
|
||||||
component: () => import('../views/ServerManagement.vue')
|
component: () => import('../views/ServerManagement.vue')
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: '/backup',
|
||||||
|
name: 'BackupRestore',
|
||||||
|
component: () => import('../views/BackupRestore.vue')
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: '/account',
|
path: '/account',
|
||||||
name: 'Account',
|
name: 'Account',
|
||||||
@@ -47,6 +51,11 @@ const routes = [
|
|||||||
name: 'Login',
|
name: 'Login',
|
||||||
component: Login,
|
component: Login,
|
||||||
meta: { public: true }
|
meta: { public: true }
|
||||||
|
},
|
||||||
|
// Unknown address: back to the start page (the guard sends guests to the login page)
|
||||||
|
{
|
||||||
|
path: '/:pathMatch(.*)*',
|
||||||
|
redirect: '/'
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
// IPv4 helpers for the VPN subnet field: "a.b.c.d/nn" <-> network address + dotted netmask.
|
||||||
|
|
||||||
|
const IPV4 = /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;
|
||||||
|
|
||||||
|
// 24 -> '255.255.255.0'; null for a value outside 0..32
|
||||||
|
export function cidrToMask(bits) {
|
||||||
|
const n = Number(bits);
|
||||||
|
if (bits === '' || bits === null || !Number.isInteger(n) || n < 0 || n > 32) return null;
|
||||||
|
const mask = n === 0 ? 0 : (0xFFFFFFFF << (32 - n)) >>> 0;
|
||||||
|
return [24, 16, 8, 0].map(shift => (mask >>> shift) & 255).join('.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// '255.255.255.0' -> 24; null for a malformed or non-contiguous mask
|
||||||
|
export function maskToCidr(mask) {
|
||||||
|
if (typeof mask !== 'string' || !IPV4.test(mask)) return null;
|
||||||
|
const value = mask.split('.').reduce((acc, p) => ((acc << 8) | Number(p)) >>> 0, 0);
|
||||||
|
let bits = 0;
|
||||||
|
while (bits < 32 && (value & (0x80000000 >>> bits))) bits++;
|
||||||
|
// The rest must be zeros, otherwise the mask is not contiguous
|
||||||
|
const expected = bits === 0 ? 0 : (0xFFFFFFFF << (32 - bits)) >>> 0;
|
||||||
|
return value === expected ? bits : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// '172.20.1.0/24' -> { network: '172.20.1.0', netmask: '255.255.255.0' }
|
||||||
|
// '172.20.1.0' -> { network: '172.20.1.0', netmask: null } (no suffix: the caller keeps the current mask)
|
||||||
|
// anything else -> null
|
||||||
|
export function parseCidr(value) {
|
||||||
|
const text = String(value ?? '').trim();
|
||||||
|
const [network, suffix, ...rest] = text.split('/');
|
||||||
|
if (rest.length || !IPV4.test(network)) return null;
|
||||||
|
if (suffix === undefined) return { network, netmask: null };
|
||||||
|
const netmask = cidrToMask(suffix);
|
||||||
|
return netmask ? { network, netmask } : null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { cidrToMask, maskToCidr, parseCidr } from './cidr';
|
||||||
|
|
||||||
|
describe('cidrToMask / maskToCidr', () => {
|
||||||
|
it('converts a suffix to a netmask and back', () => {
|
||||||
|
for (const [bits, mask] of [[8, '255.0.0.0'], [22, '255.255.252.0'], [24, '255.255.255.0'], [30, '255.255.255.252']]) {
|
||||||
|
expect(cidrToMask(bits)).toBe(mask);
|
||||||
|
expect(maskToCidr(mask)).toBe(bits);
|
||||||
|
}
|
||||||
|
expect(cidrToMask(0)).toBe('0.0.0.0');
|
||||||
|
expect(cidrToMask(32)).toBe('255.255.255.255');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects out-of-range suffixes and non-contiguous masks', () => {
|
||||||
|
for (const v of [-1, 33, 'x', '', null]) expect(cidrToMask(v)).toBeNull();
|
||||||
|
expect(maskToCidr('255.0.255.0')).toBeNull();
|
||||||
|
expect(maskToCidr('255.255.255')).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('parseCidr', () => {
|
||||||
|
it('splits the address and the mask', () => {
|
||||||
|
expect(parseCidr('172.20.1.0/24')).toEqual({ network: '172.20.1.0', netmask: '255.255.255.0' });
|
||||||
|
expect(parseCidr(' 10.8.0.0/22 ')).toEqual({ network: '10.8.0.0', netmask: '255.255.252.0' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the mask empty when there is no suffix', () => {
|
||||||
|
expect(parseCidr('10.8.0.0')).toEqual({ network: '10.8.0.0', netmask: null });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects malformed input', () => {
|
||||||
|
for (const v of ['', 'abc', '10.8.0.0/', '10.8.0.0/33', '10.8.0/24', '300.1.1.1/24', '10.8.0.0/24/1']) {
|
||||||
|
expect(parseCidr(v)).toBeNull();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
// Multi-session helpers for the Clients page
|
||||||
|
|
||||||
|
// Badge "xN" is shown only when a client has more than one session
|
||||||
|
export const sessionsBadge = (c) => (c.sessions_count > 1 ? `×${c.sessions_count}` : null);
|
||||||
|
|
||||||
|
// Toggle a client in the set of expanded rows (returns a new array)
|
||||||
|
export const toggleExpanded = (expanded, name) =>
|
||||||
|
expanded.includes(name) ? expanded.filter(n => n !== name) : [...expanded, name];
|
||||||
|
|
||||||
|
// Sessions to render under a client row: only when expanded and there is more than one
|
||||||
|
export const visibleSessions = (c, expanded) =>
|
||||||
|
(c.sessions_count > 1 && expanded.includes(c.common_name)) ? (c.sessions || []) : [];
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { sessionsBadge, toggleExpanded, visibleSessions } from './sessions';
|
||||||
|
|
||||||
|
describe('multi-session display', () => {
|
||||||
|
const multi = { common_name: 'alice', sessions_count: 2, sessions: [{ real_address: 'a' }, { real_address: 'b' }] };
|
||||||
|
const single = { common_name: 'bob', sessions_count: 1, sessions: [{ real_address: 'c' }] };
|
||||||
|
|
||||||
|
it('shows the badge only for more than one session', () => {
|
||||||
|
expect(sessionsBadge(multi)).toBe('×2');
|
||||||
|
expect(sessionsBadge(single)).toBeNull();
|
||||||
|
expect(sessionsBadge({ common_name: 'old' })).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('expands and collapses the session list on click', () => {
|
||||||
|
expect(visibleSessions(multi, [])).toEqual([]);
|
||||||
|
const open = toggleExpanded([], 'alice');
|
||||||
|
expect(visibleSessions(multi, open)).toHaveLength(2);
|
||||||
|
expect(visibleSessions(multi, toggleExpanded(open, 'alice'))).toEqual([]);
|
||||||
|
expect(visibleSessions(single, ['bob'])).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -50,7 +50,7 @@
|
|||||||
<h4 class="m-0 text-heading">Secure Your Account</h4>
|
<h4 class="m-0 text-heading">Secure Your Account</h4>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-interior-description">
|
<div class="card-interior-description">
|
||||||
<p class="text-muted m-0">Protect your OpenVPN Monitor dashboard with second-layer security using Google Authenticator or any TOTP app.</p>
|
<p class="text-muted m-0">Protect your OpenVPN Controller dashboard with second-layer security using Google Authenticator or any TOTP app.</p>
|
||||||
</div>
|
</div>
|
||||||
<button class="btn btn-action btn-action-primary py-2 fw-bold btn-account-action" @click="initSetup" :disabled="loading">
|
<button class="btn btn-action btn-action-primary py-2 fw-bold btn-account-action" @click="initSetup" :disabled="loading">
|
||||||
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
||||||
@@ -87,6 +87,9 @@
|
|||||||
v-model="otp"
|
v-model="otp"
|
||||||
placeholder="000000"
|
placeholder="000000"
|
||||||
maxlength="6"
|
maxlength="6"
|
||||||
|
inputmode="numeric"
|
||||||
|
autocomplete="one-time-code"
|
||||||
|
aria-label="6-digit authentication code"
|
||||||
>
|
>
|
||||||
<button class="btn btn-action btn-action-primary px-4 fw-bold" @click="verifyAndEnable" :disabled="loading">
|
<button class="btn btn-action btn-action-primary px-4 fw-bold" @click="verifyAndEnable" :disabled="loading">
|
||||||
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
||||||
@@ -117,10 +120,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Alerts/Notifications Modal -->
|
<!-- Confirmation before 2FA is disabled; results are shown as toasts -->
|
||||||
<ConfirmModal ref="confirmModal" />
|
|
||||||
|
|
||||||
<!-- Action Confirmations Modal -->
|
|
||||||
<ConfirmModal ref="disable2FAModal" @confirm="handleDisable2FA" />
|
<ConfirmModal ref="disable2FAModal" @confirm="handleDisable2FA" />
|
||||||
|
|
||||||
<!-- Password Change Modal -->
|
<!-- Password Change Modal -->
|
||||||
@@ -134,6 +134,7 @@
|
|||||||
class="form-control"
|
class="form-control"
|
||||||
v-model="passwordForm.current_password"
|
v-model="passwordForm.current_password"
|
||||||
placeholder="Enter current password"
|
placeholder="Enter current password"
|
||||||
|
autocomplete="current-password"
|
||||||
required
|
required
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
@@ -144,6 +145,7 @@
|
|||||||
class="form-control"
|
class="form-control"
|
||||||
v-model="passwordForm.new_password"
|
v-model="passwordForm.new_password"
|
||||||
placeholder="Min. 8 characters"
|
placeholder="Min. 8 characters"
|
||||||
|
autocomplete="new-password"
|
||||||
required
|
required
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
@@ -154,6 +156,7 @@
|
|||||||
class="form-control"
|
class="form-control"
|
||||||
v-model="passwordForm.confirm_password"
|
v-model="passwordForm.confirm_password"
|
||||||
placeholder="Confirm new password"
|
placeholder="Confirm new password"
|
||||||
|
autocomplete="new-password"
|
||||||
required
|
required
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
@@ -191,6 +194,7 @@
|
|||||||
class="form-control"
|
class="form-control"
|
||||||
v-model="usernameForm.current_password"
|
v-model="usernameForm.current_password"
|
||||||
placeholder="Enter current password"
|
placeholder="Enter current password"
|
||||||
|
autocomplete="current-password"
|
||||||
required
|
required
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
@@ -223,16 +227,16 @@
|
|||||||
import { ref, onMounted, reactive } from 'vue';
|
import { ref, onMounted, reactive } from 'vue';
|
||||||
import { useApi } from '../composables/useApi';
|
import { useApi } from '../composables/useApi';
|
||||||
import QrcodeVue from 'qrcode.vue';
|
import QrcodeVue from 'qrcode.vue';
|
||||||
import Swal from 'sweetalert2';
|
|
||||||
import BaseModal from '../components/BaseModal.vue';
|
import BaseModal from '../components/BaseModal.vue';
|
||||||
import ConfirmModal from '../components/ConfirmModal.vue';
|
import ConfirmModal from '../components/ConfirmModal.vue';
|
||||||
|
import { useToast } from '../composables/useToast';
|
||||||
|
|
||||||
const { apiClient } = useApi();
|
const { apiClient, authApiClient } = useApi();
|
||||||
|
const toast = useToast();
|
||||||
|
|
||||||
// UI Refs
|
// UI Refs
|
||||||
const pwModal = ref(null);
|
const pwModal = ref(null);
|
||||||
const userModal = ref(null);
|
const userModal = ref(null);
|
||||||
const confirmModal = ref(null);
|
|
||||||
const disable2FAModal = ref(null);
|
const disable2FAModal = ref(null);
|
||||||
|
|
||||||
// Password Logic
|
// Password Logic
|
||||||
@@ -252,36 +256,21 @@ const showPwModal = () => {
|
|||||||
|
|
||||||
const handleChangePassword = async () => {
|
const handleChangePassword = async () => {
|
||||||
if (passwordForm.new_password !== passwordForm.confirm_password) {
|
if (passwordForm.new_password !== passwordForm.confirm_password) {
|
||||||
Swal.fire({
|
toast.show('New passwords do not match', 'error');
|
||||||
title: 'Error!',
|
|
||||||
text: 'New passwords do not match',
|
|
||||||
icon: 'error',
|
|
||||||
confirmButtonColor: '#EC7C31'
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
pwLoading.value = true;
|
pwLoading.value = true;
|
||||||
try {
|
try {
|
||||||
await apiClient.post('../auth/change-password', {
|
await authApiClient.post('/change-password', {
|
||||||
current_password: passwordForm.current_password,
|
current_password: passwordForm.current_password,
|
||||||
new_password: passwordForm.new_password
|
new_password: passwordForm.new_password
|
||||||
});
|
});
|
||||||
|
|
||||||
pwModal.value.hide();
|
pwModal.value.hide();
|
||||||
Swal.fire({
|
toast.show('Password updated successfully.', 'success');
|
||||||
title: 'Success!',
|
|
||||||
text: 'Password updated successfully.',
|
|
||||||
icon: 'success',
|
|
||||||
confirmButtonColor: '#1652B8'
|
|
||||||
});
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
Swal.fire({
|
toast.show(err.response?.data?.error || 'Failed to update password', 'error');
|
||||||
title: 'Failed',
|
|
||||||
text: err.response?.data?.error || 'Failed to update password',
|
|
||||||
icon: 'error',
|
|
||||||
confirmButtonColor: '#cf222e'
|
|
||||||
});
|
|
||||||
} finally {
|
} finally {
|
||||||
pwLoading.value = false;
|
pwLoading.value = false;
|
||||||
}
|
}
|
||||||
@@ -300,18 +289,13 @@ const showUserModal = () => {
|
|||||||
|
|
||||||
const handleChangeUsername = async () => {
|
const handleChangeUsername = async () => {
|
||||||
if (!/^[A-Za-z][A-Za-z0-9_.-]{2,31}$/.test(usernameForm.new_username)) {
|
if (!/^[A-Za-z][A-Za-z0-9_.-]{2,31}$/.test(usernameForm.new_username)) {
|
||||||
Swal.fire({
|
toast.show('Username must be 3-32 chars, start with a letter, and contain only letters, digits, . _ -', 'error');
|
||||||
title: 'Error!',
|
|
||||||
text: 'Username must be 3-32 chars, start with a letter, and contain only letters, digits, . _ -',
|
|
||||||
icon: 'error',
|
|
||||||
confirmButtonColor: '#EC7C31'
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
userLoading.value = true;
|
userLoading.value = true;
|
||||||
try {
|
try {
|
||||||
const res = await apiClient.post('../auth/change-username', {
|
const res = await authApiClient.post('/change-username', {
|
||||||
new_username: usernameForm.new_username,
|
new_username: usernameForm.new_username,
|
||||||
current_password: usernameForm.current_password,
|
current_password: usernameForm.current_password,
|
||||||
otp: usernameForm.otp || undefined
|
otp: usernameForm.otp || undefined
|
||||||
@@ -320,19 +304,9 @@ const handleChangeUsername = async () => {
|
|||||||
try { localStorage.setItem('ovpmon_user', res.data.username); } catch (e) { /* ignore */ }
|
try { localStorage.setItem('ovpmon_user', res.data.username); } catch (e) { /* ignore */ }
|
||||||
window.dispatchEvent(new Event('ovpmon-user-changed'));
|
window.dispatchEvent(new Event('ovpmon-user-changed'));
|
||||||
userModal.value.hide();
|
userModal.value.hide();
|
||||||
Swal.fire({
|
toast.show('Username updated. Use the new username the next time you sign in.', 'success');
|
||||||
title: 'Success!',
|
|
||||||
text: 'Username updated. Use the new username the next time you sign in.',
|
|
||||||
icon: 'success',
|
|
||||||
confirmButtonColor: '#1652B8'
|
|
||||||
});
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
Swal.fire({
|
toast.show(err.response?.data?.error || 'Failed to update username', 'error');
|
||||||
title: 'Failed',
|
|
||||||
text: err.response?.data?.error || 'Failed to update username',
|
|
||||||
icon: 'error',
|
|
||||||
confirmButtonColor: '#cf222e'
|
|
||||||
});
|
|
||||||
} finally {
|
} finally {
|
||||||
userLoading.value = false;
|
userLoading.value = false;
|
||||||
}
|
}
|
||||||
@@ -344,7 +318,6 @@ const step2 = ref(false);
|
|||||||
const loading = ref(false);
|
const loading = ref(false);
|
||||||
const otp = ref('');
|
const otp = ref('');
|
||||||
const setupData = ref({ secret: '', uri: '' });
|
const setupData = ref({ secret: '', uri: '' });
|
||||||
const isDark = ref(document.documentElement.getAttribute('data-theme') === 'dark');
|
|
||||||
|
|
||||||
const fetchUserStatus = async () => {
|
const fetchUserStatus = async () => {
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
@@ -358,27 +331,16 @@ const fetchUserStatus = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(fetchUserStatus);
|
||||||
fetchUserStatus();
|
|
||||||
|
|
||||||
const observer = new MutationObserver((mutations) => {
|
|
||||||
mutations.forEach((mutation) => {
|
|
||||||
if (mutation.attributeName === 'data-theme') {
|
|
||||||
isDark.value = document.documentElement.getAttribute('data-theme') === 'dark';
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
observer.observe(document.documentElement, { attributes: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
const initSetup = async () => {
|
const initSetup = async () => {
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
try {
|
try {
|
||||||
const res = await apiClient.post('../auth/setup-2fa');
|
const res = await authApiClient.post('/setup-2fa');
|
||||||
setupData.value = res.data;
|
setupData.value = res.data;
|
||||||
step2.value = true;
|
step2.value = true;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
Swal.fire('Error', 'Failed to initialize 2FA setup.', 'error');
|
toast.show(err.response?.data?.error || 'Failed to initialize 2FA setup.', 'error');
|
||||||
} finally {
|
} finally {
|
||||||
loading.value = false;
|
loading.value = false;
|
||||||
}
|
}
|
||||||
@@ -388,26 +350,14 @@ const verifyAndEnable = async () => {
|
|||||||
if (!otp.value || otp.value.length !== 6) return;
|
if (!otp.value || otp.value.length !== 6) return;
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
try {
|
try {
|
||||||
await apiClient.post('../auth/enable-2fa', {
|
await authApiClient.post('/enable-2fa', {
|
||||||
secret: setupData.value.secret,
|
secret: setupData.value.secret,
|
||||||
otp: otp.value
|
otp: otp.value
|
||||||
});
|
});
|
||||||
isEnabled.value = true;
|
isEnabled.value = true;
|
||||||
confirmModal.value.open({
|
toast.show('Two-factor authentication has been enabled. Your dashboard is now more secure.', 'success');
|
||||||
title: 'Success!',
|
|
||||||
message: 'Two-factor authentication has been enabled successfully. Your dashboard is now more secure.',
|
|
||||||
confirmText: 'Great!',
|
|
||||||
confirmBtnClass: 'btn-action-save',
|
|
||||||
showCancel: false
|
|
||||||
});
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
confirmModal.value.open({
|
toast.show(err.response?.data?.error || 'The code you entered is invalid. Please check your authenticator app and try again.', 'error');
|
||||||
title: 'Verification Failed',
|
|
||||||
message: err.response?.data?.error || 'The code you entered is invalid. Please check your authenticator app and try again.',
|
|
||||||
confirmText: 'Try Again',
|
|
||||||
confirmBtnClass: 'btn-action-danger',
|
|
||||||
showCancel: false
|
|
||||||
});
|
|
||||||
} finally {
|
} finally {
|
||||||
loading.value = false;
|
loading.value = false;
|
||||||
}
|
}
|
||||||
@@ -424,25 +374,13 @@ const disableConfirm = () => {
|
|||||||
|
|
||||||
const handleDisable2FA = async () => {
|
const handleDisable2FA = async () => {
|
||||||
try {
|
try {
|
||||||
await apiClient.post('../auth/disable-2fa');
|
await authApiClient.post('/disable-2fa');
|
||||||
|
|
||||||
isEnabled.value = false;
|
isEnabled.value = false;
|
||||||
step2.value = false;
|
step2.value = false;
|
||||||
confirmModal.value.open({
|
toast.show('Two-factor authentication has been disabled. Your account is now using standard password protection.', 'warning');
|
||||||
title: '2FA Disabled',
|
|
||||||
message: 'Two-factor authentication has been disabled. Your account is now using standard password protection.',
|
|
||||||
confirmText: 'OK',
|
|
||||||
confirmBtnClass: 'btn-action-primary',
|
|
||||||
showCancel: false
|
|
||||||
});
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
confirmModal.value.open({
|
toast.show(err.response?.data?.error || 'Failed to disable two-factor authentication. Please try again.', 'error');
|
||||||
title: 'Error',
|
|
||||||
message: err.response?.data?.error || 'Failed to disable two-factor authentication. Please try again.',
|
|
||||||
confirmText: 'OK',
|
|
||||||
confirmBtnClass: 'btn-action-danger',
|
|
||||||
showCancel: false
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
+34
-151
@@ -151,16 +151,18 @@ import Chart from 'chart.js/auto';
|
|||||||
import { useApi } from '../composables/useApi';
|
import { useApi } from '../composables/useApi';
|
||||||
import { useFormatters } from '../composables/useFormatters';
|
import { useFormatters } from '../composables/useFormatters';
|
||||||
import { useAppConfig } from '../composables/useAppConfig';
|
import { useAppConfig } from '../composables/useAppConfig';
|
||||||
|
import { useThemeObserver } from '../composables/useTheme';
|
||||||
|
import { useTrafficChart, getThemeColors, COLOR_RX, COLOR_TX } from '../composables/useTrafficChart';
|
||||||
|
|
||||||
const { fetchAnalytics, fetchCertificates } = useApi();
|
const { fetchAnalytics, fetchCertificates } = useApi();
|
||||||
const { formatBytes, parseServerDate } = useFormatters();
|
const { formatBytes } = useFormatters();
|
||||||
const { config } = useAppConfig();
|
const { config } = useAppConfig();
|
||||||
|
|
||||||
// Refs
|
// Refs
|
||||||
const mainChartRef = ref(null);
|
const mainChartRef = ref(null);
|
||||||
const pieChartRef = ref(null);
|
const pieChartRef = ref(null);
|
||||||
let mainChartInstance = null;
|
|
||||||
let pieChartInstance = null;
|
let pieChartInstance = null;
|
||||||
|
const mainChart = useTrafficChart(mainChartRef, { maxPoints: 96 });
|
||||||
|
|
||||||
// State
|
// State
|
||||||
const loading = reactive({ analytics: true, certs: true });
|
const loading = reactive({ analytics: true, certs: true });
|
||||||
@@ -179,17 +181,14 @@ const kpi = reactive({
|
|||||||
|
|
||||||
const topClients = ref([]);
|
const topClients = ref([]);
|
||||||
const expiringCertsList = ref([]);
|
const expiringCertsList = ref([]);
|
||||||
let cachedHistory = null;
|
let cachedHistory = [];
|
||||||
|
|
||||||
// Helpers
|
|
||||||
const MAX_CHART_POINTS = 96;
|
|
||||||
|
|
||||||
const loadAnalytics = async () => {
|
const loadAnalytics = async () => {
|
||||||
loading.analytics = true;
|
loading.analytics = true;
|
||||||
try {
|
try {
|
||||||
const res = await fetchAnalytics(range.value);
|
const res = await fetchAnalytics(range.value);
|
||||||
if (res.success) {
|
if (res.success) {
|
||||||
proccessData(res.data);
|
processData(res.data);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
@@ -201,17 +200,16 @@ const loadAnalytics = async () => {
|
|||||||
const loadCerts = async () => {
|
const loadCerts = async () => {
|
||||||
loading.certs = true;
|
loading.certs = true;
|
||||||
try {
|
try {
|
||||||
const res = await fetchCertificates();
|
// fetchCertificates returns the plain array of profiles
|
||||||
if(res.success && Array.isArray(res.data)) {
|
const profiles = await fetchCertificates();
|
||||||
const list = res.data.filter(cert => {
|
const list = profiles.filter(cert => {
|
||||||
// Only active, non-revoked, and expiring soon (within 45 days)
|
// Only active, non-revoked, and expiring soon (within 45 days)
|
||||||
return !cert.is_revoked && !cert.is_expired &&
|
return !cert.is_revoked && !cert.is_expired &&
|
||||||
cert.days_remaining !== null && cert.days_remaining <= 45;
|
cert.days_remaining != null && cert.days_remaining <= 45;
|
||||||
});
|
});
|
||||||
|
|
||||||
kpi.expiringCerts = list.length;
|
kpi.expiringCerts = list.length;
|
||||||
expiringCertsList.value = list.sort((a,b) => (a.days_remaining || 0) - (b.days_remaining || 0));
|
expiringCertsList.value = list.sort((a, b) => a.days_remaining - b.days_remaining);
|
||||||
}
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -219,7 +217,7 @@ const loadCerts = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const proccessData = (data) => {
|
const processData = (data) => {
|
||||||
kpi.concurrentUsers = data.max_concurrent_24h || 0;
|
kpi.concurrentUsers = data.max_concurrent_24h || 0;
|
||||||
|
|
||||||
// Traffic Distribution
|
// Traffic Distribution
|
||||||
@@ -238,87 +236,21 @@ const proccessData = (data) => {
|
|||||||
percent: kpi.totalTraffic > 0 ? ((Number(c.total_traffic) / kpi.totalTraffic) * 100).toFixed(1) : 0
|
percent: kpi.totalTraffic > 0 ? ((Number(c.total_traffic) / kpi.totalTraffic) * 100).toFixed(1) : 0
|
||||||
}));
|
}));
|
||||||
|
|
||||||
cachedHistory = data.global_history_24h || [];
|
// Map the raw fields to the point format of useTrafficChart
|
||||||
|
cachedHistory = (data.global_history_24h || []).map(p => ({
|
||||||
|
timestamp: p.timestamp,
|
||||||
|
bytes_received: p.total_rx,
|
||||||
|
bytes_sent: p.total_tx,
|
||||||
|
rx_rate_mbps: p.total_rx_rate,
|
||||||
|
tx_rate_mbps: p.total_tx_rate
|
||||||
|
}));
|
||||||
|
|
||||||
renderMainChart();
|
renderMainChart();
|
||||||
renderPieChart();
|
renderPieChart();
|
||||||
};
|
};
|
||||||
|
|
||||||
const renderMainChart = () => {
|
const renderMainChart = () => {
|
||||||
if (!mainChartRef.value) return;
|
mainChart.render(cachedHistory, { range: range.value, speedMode: isSpeedMode.value });
|
||||||
if (mainChartInstance) mainChartInstance.destroy();
|
|
||||||
|
|
||||||
const downsampled = downsampleData(cachedHistory, MAX_CHART_POINTS);
|
|
||||||
const labels = [];
|
|
||||||
const dataRx = [];
|
|
||||||
const dataTx = [];
|
|
||||||
|
|
||||||
downsampled.forEach(point => {
|
|
||||||
const d = parseServerDate(point.timestamp);
|
|
||||||
let label = '';
|
|
||||||
if(range.value.includes('h') || range.value === '1d') {
|
|
||||||
label = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
|
||||||
} else {
|
|
||||||
label = d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' +
|
|
||||||
d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
|
||||||
}
|
|
||||||
labels.push(label);
|
|
||||||
|
|
||||||
if (!isSpeedMode.value) {
|
|
||||||
dataRx.push(point.bytes_received / (1024 * 1024)); // MB
|
|
||||||
dataTx.push(point.bytes_sent / (1024 * 1024)); // MB
|
|
||||||
} else {
|
|
||||||
dataRx.push(point.rx_rate_mbps || 0);
|
|
||||||
dataTx.push(point.tx_rate_mbps || 0);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
|
|
||||||
const gridColor = isDark ? 'rgba(240, 246, 252, 0.1)' : 'rgba(0,0,0,0.05)';
|
|
||||||
const textColor = isDark ? '#8b949e' : '#6c757d';
|
|
||||||
|
|
||||||
const ctx = mainChartRef.value.getContext('2d');
|
|
||||||
mainChartInstance = new Chart(ctx, {
|
|
||||||
type: 'line',
|
|
||||||
data: {
|
|
||||||
labels,
|
|
||||||
datasets: [
|
|
||||||
|
|
||||||
{
|
|
||||||
label: !isSpeedMode.value ? 'Received (MB)' : 'RX Mbps',
|
|
||||||
data: dataRx,
|
|
||||||
borderColor: '#1652B8', // OpenVPN Blue
|
|
||||||
backgroundColor: 'rgba(22, 82, 184, 0.15)',
|
|
||||||
borderWidth: 2,
|
|
||||||
fill: true,
|
|
||||||
tension: 0.3,
|
|
||||||
pointRadius: 3,
|
|
||||||
pointHoverRadius: 4
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: !isSpeedMode.value ? 'Sent (MB)' : 'TX Mbps',
|
|
||||||
data: dataTx,
|
|
||||||
borderColor: '#EC7C31', // Brand Orange
|
|
||||||
backgroundColor: 'rgba(236, 124, 49, 0.15)',
|
|
||||||
borderWidth: 2,
|
|
||||||
fill: true,
|
|
||||||
tension: 0.3,
|
|
||||||
pointRadius: 3,
|
|
||||||
pointHoverRadius: 4
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
options: {
|
|
||||||
responsive: true,
|
|
||||||
maintainAspectRatio: false,
|
|
||||||
interaction: { mode: 'index', intersect: false },
|
|
||||||
plugins: { legend: { labels: { color: textColor } } },
|
|
||||||
scales: {
|
|
||||||
x: { ticks: { color: textColor, maxTicksLimit: 8 }, grid: { color: gridColor } },
|
|
||||||
y: { beginAtZero: true, ticks: { color: textColor }, grid: { color: gridColor } }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const renderPieChart = () => {
|
const renderPieChart = () => {
|
||||||
@@ -326,8 +258,7 @@ const renderPieChart = () => {
|
|||||||
if (pieChartInstance) pieChartInstance.destroy();
|
if (pieChartInstance) pieChartInstance.destroy();
|
||||||
|
|
||||||
const ctx = pieChartRef.value.getContext('2d');
|
const ctx = pieChartRef.value.getContext('2d');
|
||||||
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
|
const bgColor = getThemeColors().isDark ? '#161b22' : '#ffffff';
|
||||||
const bgColor = isDark ? '#161b22' : '#ffffff';
|
|
||||||
|
|
||||||
pieChartInstance = new Chart(ctx, {
|
pieChartInstance = new Chart(ctx, {
|
||||||
type: 'doughnut',
|
type: 'doughnut',
|
||||||
@@ -335,7 +266,7 @@ const renderPieChart = () => {
|
|||||||
labels: ['Received', 'Sent'],
|
labels: ['Received', 'Sent'],
|
||||||
datasets: [{
|
datasets: [{
|
||||||
data: [kpi.totalReceived, kpi.totalSent],
|
data: [kpi.totalReceived, kpi.totalSent],
|
||||||
backgroundColor: ['#1652B8', '#EC7C31'],
|
backgroundColor: [COLOR_RX, COLOR_TX],
|
||||||
borderColor: bgColor,
|
borderColor: bgColor,
|
||||||
borderWidth: 2,
|
borderWidth: 2,
|
||||||
hoverOffset: 4
|
hoverOffset: 4
|
||||||
@@ -350,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
|
// Lifecycle
|
||||||
let intervalId;
|
let intervalId;
|
||||||
|
|
||||||
|
// Redraw the charts when the theme is toggled
|
||||||
|
useThemeObserver(() => {
|
||||||
|
renderMainChart();
|
||||||
|
renderPieChart();
|
||||||
|
});
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
loadAnalytics();
|
loadAnalytics();
|
||||||
loadCerts();
|
loadCerts();
|
||||||
|
|
||||||
// Support Theme Toggle re-render like in Clients
|
|
||||||
// We observe the attribute on html
|
|
||||||
const observer = new MutationObserver((mutations) => {
|
|
||||||
mutations.forEach((mutation) => {
|
|
||||||
if (mutation.type === 'attributes' && mutation.attributeName === 'data-theme') {
|
|
||||||
renderMainChart();
|
|
||||||
renderPieChart();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
observer.observe(document.documentElement, { attributes: true });
|
|
||||||
|
|
||||||
const refreshTime = config.value?.refresh_interval || 30000;
|
const refreshTime = config.value?.refresh_interval || 30000;
|
||||||
intervalId = setInterval(() => {
|
intervalId = setInterval(() => {
|
||||||
@@ -419,7 +303,6 @@ onMounted(() => {
|
|||||||
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
if (intervalId) clearInterval(intervalId);
|
if (intervalId) clearInterval(intervalId);
|
||||||
if (mainChartInstance) mainChartInstance.destroy();
|
|
||||||
if (pieChartInstance) pieChartInstance.destroy();
|
if (pieChartInstance) pieChartInstance.destroy();
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
@@ -0,0 +1,803 @@
|
|||||||
|
<template>
|
||||||
|
<div class="backup-page">
|
||||||
|
|
||||||
|
<!-- DESTINATIONS -->
|
||||||
|
<div class="config-card backup-card">
|
||||||
|
<div class="config-header">
|
||||||
|
<h1>Backup Destinations</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
|
||||||
|
<span class="text-muted small">Where backup packages are stored. A backup goes to every selected destination.</span>
|
||||||
|
<button type="button" class="btn-action btn-action-save btn-sm" @click="openAdd" :disabled="!settings.types.length">
|
||||||
|
<i class="fas fa-plus"></i> Add destination
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-hover mb-0">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Name</th>
|
||||||
|
<th>Type</th>
|
||||||
|
<th>Status</th>
|
||||||
|
<th>Last result</th>
|
||||||
|
<th>Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-if="loading">
|
||||||
|
<td colspan="5" class="text-center py-4">
|
||||||
|
<div class="spinner-border spinner-border-sm text-primary" role="status">
|
||||||
|
<span class="visually-hidden">Loading...</span>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr v-else-if="destinations.length === 0">
|
||||||
|
<td colspan="5" class="empty-state text-center py-4">
|
||||||
|
<i class="fas fa-box-archive fa-2x mb-3 text-muted"></i>
|
||||||
|
<p class="text-muted mb-0">No destinations yet. Add one to start making backups.</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr v-for="d in destinations" :key="d.id">
|
||||||
|
<td class="align-top">
|
||||||
|
<div class="fw-semibold" style="color: var(--text-heading);">{{ d.name }}</div>
|
||||||
|
<div class="text-muted small">{{ destinationSummary(d) }}</div>
|
||||||
|
<div v-if="typeInfo(d.type)?.pins_host_key" class="small mt-1">
|
||||||
|
<span v-if="d.params.host_key" class="status-badge status-valid" :title="d.params.host_key">
|
||||||
|
<i class="fas fa-fingerprint me-1"></i>Host key trusted
|
||||||
|
</span>
|
||||||
|
<span v-else class="status-badge status-warning">
|
||||||
|
<i class="fas fa-triangle-exclamation me-1"></i>Host key not trusted: press Test and confirm it
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="plainFtp(d)" class="small mt-1">
|
||||||
|
<span class="status-badge status-warning"><i class="fas fa-triangle-exclamation me-1"></i>No TLS: clear text</span>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td class="align-top"><span class="status-badge status-client">{{ typeLabel(d.type) }}</span></td>
|
||||||
|
<td class="align-top">
|
||||||
|
<span :class="['status-badge', d.enabled ? 'status-valid' : 'status-secondary']">
|
||||||
|
{{ d.enabled ? 'Enabled' : 'Disabled' }}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td class="align-top">
|
||||||
|
<span v-if="d.last_status" :class="['status-badge', d.last_status === 'ok' ? 'status-valid' : 'status-expired']"
|
||||||
|
:title="d.last_message">
|
||||||
|
{{ d.last_status === 'ok' ? 'OK' : 'Failed' }}
|
||||||
|
</span>
|
||||||
|
<span v-else class="text-muted small">never used</span>
|
||||||
|
<div v-if="d.last_at" class="text-muted small">{{ formatTime(d.last_at) }}</div>
|
||||||
|
</td>
|
||||||
|
<td class="align-top">
|
||||||
|
<button class="btn btn-sm btn-link text-primary p-0 me-2" title="Test connection"
|
||||||
|
@click="testDestination(d)" :disabled="testingId === d.id">
|
||||||
|
<i v-if="testingId === d.id" class="fas fa-spinner fa-spin"></i>
|
||||||
|
<i v-else class="fas fa-plug"></i>
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-sm btn-link text-warning p-0 me-2" title="Edit" @click="openEdit(d)" :disabled="isRunning">
|
||||||
|
<i class="fas fa-pen"></i>
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-sm btn-link text-danger p-0" title="Delete" @click="askDelete(d)" :disabled="isRunning">
|
||||||
|
<i class="fas fa-trash"></i>
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- BACKUP -->
|
||||||
|
<div class="config-card backup-card">
|
||||||
|
<div class="config-header">
|
||||||
|
<h1>Backup</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-2">
|
||||||
|
<div>
|
||||||
|
<span v-if="settings.encryption_enabled" class="status-badge status-valid">
|
||||||
|
<i class="fas fa-lock me-1"></i>Packages are encrypted
|
||||||
|
</span>
|
||||||
|
<span v-else class="status-badge status-warning">
|
||||||
|
<i class="fas fa-triangle-exclamation me-1"></i>Packages are NOT encrypted
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="btn-action btn-action-secondary btn-sm" @click="openPassphrase" :disabled="isRunning">
|
||||||
|
<i class="fas fa-key"></i> {{ settings.encryption_enabled ? 'Change passphrase' : 'Set passphrase' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p class="text-muted small mb-3">
|
||||||
|
A package contains the CA private key, the certificates and the password hashes of the administrators.
|
||||||
|
<template v-if="!settings.encryption_enabled">Remote destinations need an encryption passphrase; a local folder can be used without it.</template>
|
||||||
|
<template v-else>Keep the passphrase: a package cannot be restored without it, and it is not stored in the package.</template>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="config-divider"></div>
|
||||||
|
|
||||||
|
<label class="config-label">Server name</label>
|
||||||
|
<div class="config-input-group">
|
||||||
|
<input type="text" class="config-input" v-model="serverNameInput" maxlength="63" autocomplete="off"
|
||||||
|
placeholder="e.g. vpn-main" :disabled="isRunning" @keyup.enter="saveServerName">
|
||||||
|
<button type="button" class="btn-action btn-action-secondary btn-sm" @click="saveServerName"
|
||||||
|
:disabled="isRunning || saving || serverNameInput.trim() === settings.server_name">
|
||||||
|
<i class="fas fa-floppy-disk"></i> Save
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p class="text-muted small mt-2 mb-0">
|
||||||
|
Package names will start with <strong class="text-main">{{ settings.effective_server_name }}</strong>
|
||||||
|
<span v-if="settings.server_name_source === 'public_ip'">(the server address from the VPN settings: no name is set)</span>
|
||||||
|
<span v-else-if="settings.server_name_source === 'hostname'">(the host name, in a container a random identifier: set a name)</span>.
|
||||||
|
Letters, digits, '.' and '-'. Only packages with the same name in the same folder count for "copies to keep".
|
||||||
|
The name is not part of a package: set it again on a new server.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="config-divider"></div>
|
||||||
|
|
||||||
|
<label class="config-label">Destinations for this backup</label>
|
||||||
|
<div v-if="enabledDestinations.length === 0" class="text-muted small mb-3">
|
||||||
|
No enabled destinations. Add or enable one above.
|
||||||
|
</div>
|
||||||
|
<div v-else class="mb-3">
|
||||||
|
<div v-for="d in enabledDestinations" :key="d.id" class="form-check mb-1">
|
||||||
|
<input class="form-check-input" type="checkbox" :id="'bk-dest-' + d.id" :value="d.id"
|
||||||
|
v-model="selectedIds" :disabled="needsPassphrase(d)">
|
||||||
|
<label class="form-check-label text-main" :for="'bk-dest-' + d.id">
|
||||||
|
{{ d.name }} <span class="text-muted small">({{ typeLabel(d.type) }})</span>
|
||||||
|
<span v-if="needsPassphrase(d)" class="text-muted small"> - set a passphrase first</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="btn-action-group justify-content-center mt-3">
|
||||||
|
<button type="button" class="btn-action btn-action-primary" @click="runBackup"
|
||||||
|
:disabled="isRunning || selectedIds.length === 0">
|
||||||
|
<i v-if="isRunning && job.kind === 'backup'" class="fas fa-spinner fa-spin"></i>
|
||||||
|
<i v-else class="fas fa-box-archive"></i>
|
||||||
|
Backup now
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Progress and result of the last backup -->
|
||||||
|
<div v-if="job.kind === 'backup' && job.state !== 'idle'" class="nested-box fade-in mt-4">
|
||||||
|
<label class="nested-label d-flex justify-content-between">
|
||||||
|
<span>{{ job.state === 'running' ? 'Backup in progress' : 'Last backup' }}</span>
|
||||||
|
<span v-if="job.state !== 'running'" :class="['status-badge', jobBadge(job.state)]">{{ jobLabel(job.state) }}</span>
|
||||||
|
</label>
|
||||||
|
<ul class="backup-steps">
|
||||||
|
<li v-for="s in job.stages" :key="s.name">
|
||||||
|
<i :class="stageIcon(s.state)"></i> {{ stageLabel(s.name) }}
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<div v-for="r in job.results" :key="r.destination_id" class="backup-result">
|
||||||
|
<span :class="['status-badge', resultBadge(r.state)]">
|
||||||
|
<i v-if="r.state === 'running'" class="fas fa-spinner fa-spin me-1"></i>{{ resultLabel(r.state) }}
|
||||||
|
</span>
|
||||||
|
<span class="fw-semibold ms-2" style="color: var(--text-heading);">{{ r.name }}</span>
|
||||||
|
<div v-if="r.message" class="text-muted small ms-1 mt-1">{{ r.message }}</div>
|
||||||
|
</div>
|
||||||
|
<div v-if="job.state !== 'running' && job.message" class="text-muted small mt-2">{{ job.message }}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- History -->
|
||||||
|
<div v-if="history.length" class="mt-4">
|
||||||
|
<label class="config-label">History</label>
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-hover mb-0">
|
||||||
|
<thead>
|
||||||
|
<tr><th>Time</th><th>Action</th><th>Result</th><th>Details</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="h in history" :key="h.id">
|
||||||
|
<td>{{ formatTime(h.started_at) }}</td>
|
||||||
|
<td class="text-capitalize">{{ h.kind }}</td>
|
||||||
|
<td><span :class="['status-badge', jobBadge(h.state)]">{{ jobLabel(h.state) }}</span></td>
|
||||||
|
<td class="small text-muted">{{ h.message }}</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- RESTORE -->
|
||||||
|
<div class="config-card backup-card">
|
||||||
|
<div class="config-header">
|
||||||
|
<h1>Restore</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="text-muted small mb-3">
|
||||||
|
Restores the databases, the PKI and the client profiles from a package, also one made on another server.
|
||||||
|
The current state is saved to a local safety copy first.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="config-row">
|
||||||
|
<div class="config-col">
|
||||||
|
<label class="config-label">Source</label>
|
||||||
|
<div class="select-container">
|
||||||
|
<select class="config-select" v-model="restore.sourceId" :disabled="isRunning">
|
||||||
|
<option :value="null" disabled>Select a destination</option>
|
||||||
|
<option v-for="d in destinations" :key="d.id" :value="d.id">{{ d.name }} ({{ typeLabel(d.type) }})</option>
|
||||||
|
</select>
|
||||||
|
<div class="select-arrow"><i class="fas fa-chevron-down"></i></div>
|
||||||
|
</div>
|
||||||
|
<div v-if="restore.checking" class="text-muted small mt-2">
|
||||||
|
<i class="fas fa-spinner fa-spin me-1"></i>Checking the source...
|
||||||
|
</div>
|
||||||
|
<div v-else-if="restore.sourceError" class="mt-2">
|
||||||
|
<span class="status-badge status-expired"><i class="fas fa-times-circle me-1"></i>Source check failed</span>
|
||||||
|
<div class="text-muted small mt-1">{{ restore.sourceError }}</div>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="restore.sourceId !== null" class="mt-2">
|
||||||
|
<span class="status-badge status-valid"><i class="fas fa-check-circle me-1"></i>Source reachable</span>
|
||||||
|
<span class="text-muted small ms-2">{{ restore.packages.length }} package(s) found</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="config-row">
|
||||||
|
<div class="config-col">
|
||||||
|
<label class="config-label">Package (newest first)</label>
|
||||||
|
<div class="select-container">
|
||||||
|
<select class="config-select" v-model="restore.packageName"
|
||||||
|
:disabled="isRunning || restore.checking || restore.packages.length === 0">
|
||||||
|
<option :value="''" disabled>{{ restore.packages.length ? 'Select a package' : 'No packages' }}</option>
|
||||||
|
<option v-for="p in restore.packages" :key="p.name" :value="p.name">{{ packageLabel(p) }}</option>
|
||||||
|
</select>
|
||||||
|
<div class="select-arrow"><i class="fas fa-chevron-down"></i></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="selectedPackage && selectedPackage.encrypted" class="config-row">
|
||||||
|
<div class="config-col">
|
||||||
|
<label class="config-label">Package passphrase</label>
|
||||||
|
<input type="password" class="config-input" v-model="restore.passphrase" autocomplete="off"
|
||||||
|
placeholder="Passphrase used when the package was made">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="btn-action-group justify-content-center">
|
||||||
|
<button type="button" class="btn-action btn-action-danger" @click="askRestore" :disabled="!canRestore">
|
||||||
|
<i v-if="isRunning && job.kind === 'restore'" class="fas fa-spinner fa-spin"></i>
|
||||||
|
<i v-else class="fas fa-rotate-left"></i>
|
||||||
|
Restore
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Progress and result of the restore -->
|
||||||
|
<div v-if="job.kind === 'restore' && job.state !== 'idle'" class="nested-box fade-in mt-4">
|
||||||
|
<label class="nested-label d-flex justify-content-between">
|
||||||
|
<span>{{ job.state === 'running' ? 'Restore in progress. Do not close the server.' : 'Last restore' }}</span>
|
||||||
|
<span v-if="job.state !== 'running'" :class="['status-badge', jobBadge(job.state)]">{{ jobLabel(job.state) }}</span>
|
||||||
|
</label>
|
||||||
|
<ul class="backup-steps">
|
||||||
|
<li v-for="s in job.stages" :key="s.name">
|
||||||
|
<i :class="stageIcon(s.state)"></i> {{ stageLabel(s.name) }}
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<div v-if="job.state !== 'running' && job.message" class="small mt-2" :class="job.state === 'done' ? 'text-main' : 'text-danger'">
|
||||||
|
{{ job.message }}
|
||||||
|
</div>
|
||||||
|
<div v-for="(w, i) in job.warnings" :key="i" class="small mt-1">
|
||||||
|
<span class="status-badge status-warning"><i class="fas fa-triangle-exclamation me-1"></i>{{ w }}</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="restoreFinishedHere && job.relogin" class="mt-3">
|
||||||
|
<p class="text-main small mb-2">
|
||||||
|
The accounts now come from the package. Log in again with the account of the restored server.
|
||||||
|
Check the server address in the VPN settings if the package comes from another server.
|
||||||
|
</p>
|
||||||
|
<button type="button" class="btn-action btn-action-primary btn-sm" @click="logInAgain">
|
||||||
|
<i class="fas fa-sign-in-alt"></i> Log in again
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Add / edit destination -->
|
||||||
|
<BaseModal id="destinationModal" :title="destForm.id ? 'Edit Destination' : 'Add Destination'" ref="destModal">
|
||||||
|
<template #body>
|
||||||
|
<form @submit.prevent="saveDestination" id="destForm" autocomplete="off">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">Name</label>
|
||||||
|
<input type="text" class="form-control" v-model="destForm.name" maxlength="64" required placeholder="e.g. offsite-bucket">
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">Type</label>
|
||||||
|
<div class="select-container">
|
||||||
|
<select class="config-select" v-model="destForm.type" @change="onTypeChange">
|
||||||
|
<option v-for="t in settings.types" :key="t.id" :value="t.id">{{ t.label }}</option>
|
||||||
|
</select>
|
||||||
|
<div class="select-arrow"><i class="fas fa-chevron-down"></i></div>
|
||||||
|
</div>
|
||||||
|
<div v-if="currentType && currentType.remote && !settings.encryption_enabled" class="form-text mt-2 small text-warning">
|
||||||
|
<i class="fas fa-triangle-exclamation me-1"></i>Backups to this type need an encryption passphrase.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-for="f in currentFields" :key="f.name" class="mb-3">
|
||||||
|
<template v-if="f.kind === 'bool'">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase d-block">{{ f.label }}</label>
|
||||||
|
<div class="toggle-wrapper">
|
||||||
|
<label class="toggle-switch">
|
||||||
|
<input type="checkbox" v-model="destForm.params[f.name]">
|
||||||
|
<span class="toggle-slider"></span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template v-else-if="f.kind === 'secret'">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">{{ f.label }}</label>
|
||||||
|
<input type="password" class="form-control" v-model="destForm.secrets[f.name]"
|
||||||
|
autocomplete="new-password"
|
||||||
|
:placeholder="secretIsSet(f.name) ? '(unchanged)' : ''">
|
||||||
|
<div v-if="f.hint" class="form-text mt-1 text-muted small">{{ f.hint }}</div>
|
||||||
|
</template>
|
||||||
|
<template v-else-if="f.kind === 'secret_multiline'">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">{{ f.label }}</label>
|
||||||
|
<textarea class="form-control" rows="5" v-model="destForm.secrets[f.name]" spellcheck="false"
|
||||||
|
autocomplete="off" style="font-family: monospace; font-size: 12px;"
|
||||||
|
:placeholder="secretIsSet(f.name) ? '(unchanged: paste a new key to replace it)' : '-----BEGIN OPENSSH PRIVATE KEY-----'"></textarea>
|
||||||
|
</template>
|
||||||
|
<template v-else-if="f.kind === 'number'">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">{{ f.label }}</label>
|
||||||
|
<input type="number" class="form-control" v-model.number="destForm.params[f.name]" min="1" max="65535">
|
||||||
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">{{ f.label }}</label>
|
||||||
|
<input type="text" class="form-control" v-model="destForm.params[f.name]" :placeholder="f.default || ''">
|
||||||
|
<div v-if="f.hint" class="form-text mt-1 text-muted small">{{ f.hint }}</div>
|
||||||
|
</template>
|
||||||
|
<div v-if="f.warning && destForm.params[f.name] === f.warn_if" class="form-text mt-2 small text-warning">
|
||||||
|
<i class="fas fa-triangle-exclamation me-1"></i>{{ f.warning }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="currentType && currentType.pins_host_key" class="mb-3">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">Server host key (SHA-256)</label>
|
||||||
|
<div v-if="destForm.params.host_key" class="small text-main" style="word-break: break-all;">
|
||||||
|
{{ destForm.params.host_key }}
|
||||||
|
</div>
|
||||||
|
<div v-else class="form-text small text-warning">
|
||||||
|
<i class="fas fa-triangle-exclamation me-1"></i>Not trusted yet. Save the destination, press Test and confirm the fingerprint. Nothing is copied before that.
|
||||||
|
</div>
|
||||||
|
<div class="form-text mt-1 text-muted small">Changing the host or the port clears the trusted key.</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">Copies to keep</label>
|
||||||
|
<input type="number" class="form-control" v-model.number="destForm.retention_count" min="1" max="1000">
|
||||||
|
<div class="form-text mt-1 text-muted small">The oldest packages of this server beyond this number are deleted after a successful backup.</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mb-1 d-flex align-items-center">
|
||||||
|
<div class="toggle-wrapper me-2">
|
||||||
|
<label class="toggle-switch">
|
||||||
|
<input type="checkbox" v-model="destForm.enabled" id="destEnabled">
|
||||||
|
<span class="toggle-slider"></span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<label class="user-select-none text-muted" for="destEnabled" style="cursor: pointer;">Enabled</label>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</template>
|
||||||
|
<template #footer>
|
||||||
|
<button type="button" class="btn-action btn-action-secondary" @click="destModal.hide()">Cancel</button>
|
||||||
|
<button type="submit" form="destForm" class="btn-action btn-action-save" :disabled="saving">
|
||||||
|
<span v-if="saving" class="spinner-border spinner-border-sm me-2"></span>
|
||||||
|
{{ destForm.id ? 'Save' : 'Add' }}
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
</BaseModal>
|
||||||
|
|
||||||
|
<!-- Passphrase -->
|
||||||
|
<BaseModal id="passphraseModal" title="Encryption Passphrase" ref="passModal">
|
||||||
|
<template #body>
|
||||||
|
<form @submit.prevent="savePassphrase" id="passForm" autocomplete="off">
|
||||||
|
<p class="text-main small">
|
||||||
|
Packages made after this change are encrypted with the new passphrase. Older packages keep the
|
||||||
|
passphrase they were made with: keep it as long as you need them.
|
||||||
|
</p>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">New passphrase</label>
|
||||||
|
<input type="password" class="form-control" v-model="passForm.value" autocomplete="new-password"
|
||||||
|
placeholder="Min. 8 characters" required>
|
||||||
|
</div>
|
||||||
|
<div class="mb-2">
|
||||||
|
<label class="form-label small fw-bold text-muted text-uppercase">Confirm passphrase</label>
|
||||||
|
<input type="password" class="form-control" v-model="passForm.confirm" autocomplete="new-password" required>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</template>
|
||||||
|
<template #footer>
|
||||||
|
<button v-if="settings.encryption_enabled" type="button" class="btn-action btn-action-danger me-auto" @click="removePassphrase" :disabled="saving">
|
||||||
|
Remove passphrase
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn-action btn-action-secondary" @click="passModal.hide()">Cancel</button>
|
||||||
|
<button type="submit" form="passForm" class="btn-action btn-action-save" :disabled="saving">
|
||||||
|
<span v-if="saving" class="spinner-border spinner-border-sm me-2"></span>
|
||||||
|
Save
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
</BaseModal>
|
||||||
|
|
||||||
|
<ConfirmModal ref="deleteModal" @confirm="confirmDelete" />
|
||||||
|
<ConfirmModal ref="restoreModal" @confirm="confirmRestore" />
|
||||||
|
<ConfirmModal ref="trustModal" @confirm="confirmTrust" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, reactive, computed, watch, onMounted, onUnmounted } from 'vue';
|
||||||
|
import { useApi } from '../composables/useApi';
|
||||||
|
import { useToast } from '../composables/useToast';
|
||||||
|
import { useFormatters } from '../composables/useFormatters';
|
||||||
|
import BaseModal from '../components/BaseModal.vue';
|
||||||
|
import ConfirmModal from '../components/ConfirmModal.vue';
|
||||||
|
|
||||||
|
const { profilesApiClient } = useApi();
|
||||||
|
const toast = useToast();
|
||||||
|
const { formatBytes } = useFormatters();
|
||||||
|
|
||||||
|
const loading = ref(true);
|
||||||
|
const saving = ref(false);
|
||||||
|
const testingId = ref(null);
|
||||||
|
const settings = reactive({ encryption_enabled: false, default_retention: 14, local_root: '', types: [],
|
||||||
|
server_name: '', effective_server_name: '', server_name_source: 'hostname' });
|
||||||
|
const serverNameInput = ref('');
|
||||||
|
const destinations = ref([]);
|
||||||
|
const history = ref([]);
|
||||||
|
const selectedIds = ref([]);
|
||||||
|
const job = reactive({ kind: null, state: 'idle', stages: [], results: [], warnings: [], message: null, relogin: false });
|
||||||
|
const restoreFinishedHere = ref(false);
|
||||||
|
|
||||||
|
const destModal = ref(null);
|
||||||
|
const passModal = ref(null);
|
||||||
|
const deleteModal = ref(null);
|
||||||
|
const restoreModal = ref(null);
|
||||||
|
const trustModal = ref(null);
|
||||||
|
|
||||||
|
const destForm = reactive({ id: null, name: '', type: 'local', enabled: true, retention_count: 14, params: {}, secrets: {} });
|
||||||
|
const existingSecrets = ref({});
|
||||||
|
const passForm = reactive({ value: '', confirm: '' });
|
||||||
|
const restore = reactive({ sourceId: null, checking: false, sourceError: '', packages: [], packageName: '', passphrase: '' });
|
||||||
|
|
||||||
|
let pollTimer = null;
|
||||||
|
|
||||||
|
const errText = (e) => e.response?.data?.detail || e.message;
|
||||||
|
const isRunning = computed(() => job.state === 'running');
|
||||||
|
const enabledDestinations = computed(() => destinations.value.filter((d) => d.enabled));
|
||||||
|
const typeInfo = (id) => settings.types.find((t) => t.id === id);
|
||||||
|
const typeLabel = (id) => typeInfo(id)?.label || id;
|
||||||
|
const currentType = computed(() => typeInfo(destForm.type));
|
||||||
|
const currentFields = computed(() => currentType.value?.fields || []);
|
||||||
|
const needsPassphrase = (d) => !!typeInfo(d.type)?.remote && !settings.encryption_enabled;
|
||||||
|
const selectedPackage = computed(() => restore.packages.find((p) => p.name === restore.packageName) || null);
|
||||||
|
const canRestore = computed(() => !isRunning.value && !!selectedPackage.value
|
||||||
|
&& (!selectedPackage.value.encrypted || restore.passphrase.length > 0));
|
||||||
|
|
||||||
|
// --- formatting ---
|
||||||
|
const formatTime = (iso) => {
|
||||||
|
if (!iso) return '';
|
||||||
|
const d = new Date(iso);
|
||||||
|
return isNaN(d) ? iso : d.toLocaleString();
|
||||||
|
};
|
||||||
|
// Package time: UTC (as in the file name) and the browser's local time
|
||||||
|
const utcTime = (iso) => (iso ? iso.replace('T', ' ').replace(/(\.\d+)?Z$/, '') + ' UTC' : '');
|
||||||
|
const packageLabel = (p) => `${p.server_name} - ${utcTime(p.created_at)} (${formatTime(p.created_at)} local) - ${formatBytes(p.size)} - ${p.encrypted ? 'encrypted' : 'not encrypted'}`;
|
||||||
|
const destinationSummary = (d) => {
|
||||||
|
const p = d.params || {};
|
||||||
|
if (d.type === 'local') return `${settings.local_root || ''}/${p.folder || ''}`.replace('//', '/');
|
||||||
|
if (d.type === 's3') return `${p.bucket}${p.prefix ? '/' + p.prefix : ''} @ ${p.endpoint}`;
|
||||||
|
if (d.type === 'sftp') return `sftp://${p.username}@${p.host}:${p.port}/${p.directory}`;
|
||||||
|
if (d.type === 'ftp') return `${p.tls ? 'ftps' : 'ftp'}://${p.username}@${p.host}:${p.port}/${p.directory}`;
|
||||||
|
return '';
|
||||||
|
};
|
||||||
|
const plainFtp = (d) => d.type === 'ftp' && d.params && d.params.tls === false;
|
||||||
|
const STAGES = {
|
||||||
|
package: 'Create package', encrypt: 'Encrypt', upload: 'Send to destinations',
|
||||||
|
download: 'Download package', decrypt: 'Decrypt', verify: 'Verify and unpack',
|
||||||
|
prepare: 'Check and migrate databases', safety_backup: 'Save current state (safety copy)',
|
||||||
|
stop_openvpn: 'Stop OpenVPN if running', replace: 'Replace data', finalize: 'Regenerate server config, start OpenVPN'
|
||||||
|
};
|
||||||
|
const stageLabel = (n) => STAGES[n] || n;
|
||||||
|
const stageIcon = (s) => ({
|
||||||
|
pending: 'far fa-circle text-muted', running: 'fas fa-spinner fa-spin text-primary',
|
||||||
|
done: 'fas fa-check-circle text-success', error: 'fas fa-times-circle text-danger'
|
||||||
|
}[s] || 'far fa-circle text-muted');
|
||||||
|
const jobBadge = (s) => ({ done: 'status-valid', partial: 'status-warning', error: 'status-expired', interrupted: 'status-expired', running: 'status-warning' }[s] || 'status-secondary');
|
||||||
|
const jobLabel = (s) => ({ done: 'Success', partial: 'Partial', error: 'Failed', interrupted: 'Interrupted', running: 'Running' }[s] || s);
|
||||||
|
const resultBadge = (s) => ({ ok: 'status-valid', error: 'status-expired', running: 'status-warning' }[s] || 'status-secondary');
|
||||||
|
const resultLabel = (s) => ({ ok: 'Stored', error: 'Failed', running: 'Sending', pending: 'Waiting', skipped: 'Skipped' }[s] || s);
|
||||||
|
|
||||||
|
// --- loading ---
|
||||||
|
const loadSettings = async () => {
|
||||||
|
const res = await profilesApiClient.get('/backup/settings');
|
||||||
|
Object.assign(settings, res.data);
|
||||||
|
serverNameInput.value = settings.server_name || '';
|
||||||
|
};
|
||||||
|
const loadDestinations = async () => {
|
||||||
|
const res = await profilesApiClient.get('/backup/destinations');
|
||||||
|
destinations.value = res.data;
|
||||||
|
// Keep the choice of the user, drop what no longer exists or is not usable
|
||||||
|
const usable = new Set(enabledDestinations.value.filter((d) => !needsPassphrase(d)).map((d) => d.id));
|
||||||
|
selectedIds.value = selectedIds.value.filter((id) => usable.has(id));
|
||||||
|
};
|
||||||
|
const loadHistory = async () => {
|
||||||
|
const res = await profilesApiClient.get('/backup/history', { params: { limit: 10 } });
|
||||||
|
history.value = res.data;
|
||||||
|
};
|
||||||
|
const selectAllUsable = () => {
|
||||||
|
selectedIds.value = enabledDestinations.value.filter((d) => !needsPassphrase(d)).map((d) => d.id);
|
||||||
|
};
|
||||||
|
|
||||||
|
const stopPolling = () => {
|
||||||
|
if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
|
||||||
|
};
|
||||||
|
const startPolling = () => {
|
||||||
|
if (!pollTimer) pollTimer = setInterval(loadStatus, 2000);
|
||||||
|
};
|
||||||
|
const loadStatus = async () => {
|
||||||
|
const wasRunning = job.state === 'running';
|
||||||
|
try {
|
||||||
|
const res = await profilesApiClient.get('/backup/status');
|
||||||
|
Object.assign(job, res.data);
|
||||||
|
} catch (e) {
|
||||||
|
return; // keep polling, the next tick may succeed
|
||||||
|
}
|
||||||
|
if (job.state === 'running') {
|
||||||
|
startPolling();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
stopPolling();
|
||||||
|
if (wasRunning) await onJobFinished();
|
||||||
|
};
|
||||||
|
|
||||||
|
const onJobFinished = async () => {
|
||||||
|
if (job.kind === 'restore') {
|
||||||
|
restoreFinishedHere.value = true;
|
||||||
|
toast.show(job.message || 'Restore finished', job.state === 'done' ? 'success' : 'error');
|
||||||
|
} else {
|
||||||
|
toast.show(job.message || 'Backup finished', job.state === 'done' ? 'success' : (job.state === 'partial' ? 'warning' : 'error'));
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await Promise.all([loadDestinations(), loadHistory()]);
|
||||||
|
} catch (e) { /* the session may be gone after a restore: the interceptor redirects */ }
|
||||||
|
if (job.kind === 'restore') await checkSource();
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- destinations ---
|
||||||
|
const defaultsFor = (typeId) => {
|
||||||
|
const params = {};
|
||||||
|
(typeInfo(typeId)?.fields || []).forEach((f) => {
|
||||||
|
if (!f.kind.startsWith('secret')) params[f.name] = f.default ?? (f.kind === 'bool' ? false : '');
|
||||||
|
});
|
||||||
|
return params;
|
||||||
|
};
|
||||||
|
const secretIsSet = (name) => !!existingSecrets.value[name];
|
||||||
|
|
||||||
|
const openAdd = () => {
|
||||||
|
const type = settings.types[0]?.id || 'local';
|
||||||
|
Object.assign(destForm, { id: null, name: '', type, enabled: true, retention_count: settings.default_retention,
|
||||||
|
params: defaultsFor(type), secrets: {} });
|
||||||
|
existingSecrets.value = {};
|
||||||
|
destModal.value.show();
|
||||||
|
};
|
||||||
|
const openEdit = (d) => {
|
||||||
|
Object.assign(destForm, { id: d.id, name: d.name, type: d.type, enabled: d.enabled,
|
||||||
|
retention_count: d.retention_count, params: { ...defaultsFor(d.type), ...d.params }, secrets: {} });
|
||||||
|
existingSecrets.value = { ...d.secrets };
|
||||||
|
destModal.value.show();
|
||||||
|
};
|
||||||
|
const onTypeChange = () => {
|
||||||
|
destForm.params = defaultsFor(destForm.type);
|
||||||
|
destForm.secrets = {};
|
||||||
|
existingSecrets.value = {};
|
||||||
|
};
|
||||||
|
const saveDestination = async () => {
|
||||||
|
saving.value = true;
|
||||||
|
const body = { name: destForm.name, type: destForm.type, enabled: destForm.enabled,
|
||||||
|
retention_count: destForm.retention_count, params: destForm.params, secrets: destForm.secrets };
|
||||||
|
try {
|
||||||
|
if (destForm.id) await profilesApiClient.put(`/backup/destinations/${destForm.id}`, body);
|
||||||
|
else await profilesApiClient.post('/backup/destinations', body);
|
||||||
|
toast.show('Destination saved.', 'success');
|
||||||
|
destModal.value.hide();
|
||||||
|
await loadDestinations();
|
||||||
|
if (!destForm.id) selectAllUsable();
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(errText(e), 'error');
|
||||||
|
} finally {
|
||||||
|
saving.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const testDestination = async (d) => {
|
||||||
|
testingId.value = d.id;
|
||||||
|
try {
|
||||||
|
const res = await profilesApiClient.post(`/backup/destinations/${d.id}/test`);
|
||||||
|
if (res.data.needs_trust) askTrust(d, res.data);
|
||||||
|
else toast.show(res.data.message, res.data.ok ? 'success' : 'error');
|
||||||
|
await loadDestinations();
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(errText(e), 'error');
|
||||||
|
} finally {
|
||||||
|
testingId.value = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// SFTP: the server shows its host key; the administrator compares the fingerprint and trusts it
|
||||||
|
const askTrust = (d, r) => {
|
||||||
|
trustModal.value.open({
|
||||||
|
title: r.key_changed ? 'Host Key Changed' : 'Trust This Server?',
|
||||||
|
message:
|
||||||
|
(r.key_changed
|
||||||
|
? 'WARNING: the server now shows a different host key than the trusted one. This happens after a reinstall of the server, but also during an attack.\n\n'
|
||||||
|
: `The server of "${d.name}" showed this host key. Compare it with the fingerprint you know (ssh-keygen -lf on the server) before you trust it.\n\n`) +
|
||||||
|
`Type: ${r.key_type}\nSHA-256: ${r.fingerprint}\n\n` +
|
||||||
|
'Packages are sent only to a server with exactly this key.',
|
||||||
|
confirmText: r.key_changed ? 'Trust the new key' : 'Trust',
|
||||||
|
confirmBtnClass: r.key_changed ? 'btn-action-danger' : 'btn-action-primary',
|
||||||
|
data: { id: d.id, name: d.name, fingerprint: r.fingerprint }
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const confirmTrust = async (t) => {
|
||||||
|
try {
|
||||||
|
await profilesApiClient.post(`/backup/destinations/${t.id}/trust-host-key`, { fingerprint: t.fingerprint });
|
||||||
|
toast.show(`Host key of ${t.name} trusted. Press Test to check the connection.`, 'success');
|
||||||
|
await loadDestinations();
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(errText(e), 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const askDelete = (d) => {
|
||||||
|
deleteModal.value.open({
|
||||||
|
title: 'Delete Destination?',
|
||||||
|
message: `Delete "${d.name}"? Packages already stored there are not deleted.`,
|
||||||
|
confirmText: 'Yes, Delete',
|
||||||
|
data: d
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const confirmDelete = async (d) => {
|
||||||
|
try {
|
||||||
|
await profilesApiClient.delete(`/backup/destinations/${d.id}`);
|
||||||
|
toast.show(`${d.name} deleted.`, 'success');
|
||||||
|
if (restore.sourceId === d.id) restore.sourceId = null;
|
||||||
|
await loadDestinations();
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(errText(e), 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- passphrase ---
|
||||||
|
const openPassphrase = () => {
|
||||||
|
passForm.value = '';
|
||||||
|
passForm.confirm = '';
|
||||||
|
passModal.value.show();
|
||||||
|
};
|
||||||
|
const savePassphrase = async () => {
|
||||||
|
if (passForm.value !== passForm.confirm) {
|
||||||
|
toast.show('Passphrases do not match.', 'error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await updateSettings({ passphrase: passForm.value }, 'Passphrase saved.');
|
||||||
|
};
|
||||||
|
const removePassphrase = async () => {
|
||||||
|
await updateSettings({ clear_passphrase: true }, 'Passphrase removed. New packages are not encrypted.');
|
||||||
|
};
|
||||||
|
const saveServerName = async () => {
|
||||||
|
const value = serverNameInput.value.trim();
|
||||||
|
if (value === (settings.server_name || '')) return;
|
||||||
|
saving.value = true;
|
||||||
|
try {
|
||||||
|
const res = await profilesApiClient.put('/backup/settings', { server_name: value });
|
||||||
|
Object.assign(settings, res.data);
|
||||||
|
serverNameInput.value = settings.server_name || '';
|
||||||
|
toast.show(value ? 'Server name saved.' : 'Server name cleared.', 'success');
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(errText(e), 'error');
|
||||||
|
} finally {
|
||||||
|
saving.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const updateSettings = async (body, okText) => {
|
||||||
|
saving.value = true;
|
||||||
|
try {
|
||||||
|
const res = await profilesApiClient.put('/backup/settings', body);
|
||||||
|
Object.assign(settings, res.data);
|
||||||
|
toast.show(okText, 'success');
|
||||||
|
passModal.value.hide();
|
||||||
|
await loadDestinations();
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(errText(e), 'error');
|
||||||
|
} finally {
|
||||||
|
saving.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- backup ---
|
||||||
|
const runBackup = async () => {
|
||||||
|
try {
|
||||||
|
await profilesApiClient.post('/backup/run', { destination_ids: selectedIds.value });
|
||||||
|
restoreFinishedHere.value = false;
|
||||||
|
job.kind = 'backup';
|
||||||
|
job.state = 'running';
|
||||||
|
await loadStatus();
|
||||||
|
startPolling();
|
||||||
|
} catch (e) {
|
||||||
|
if (e.response?.status === 409) await loadStatus();
|
||||||
|
toast.show(errText(e), 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- restore ---
|
||||||
|
const checkSource = async () => {
|
||||||
|
restore.packages = [];
|
||||||
|
restore.packageName = '';
|
||||||
|
restore.passphrase = '';
|
||||||
|
restore.sourceError = '';
|
||||||
|
if (restore.sourceId === null) return;
|
||||||
|
restore.checking = true;
|
||||||
|
try {
|
||||||
|
const res = await profilesApiClient.get(`/backup/destinations/${restore.sourceId}/packages`);
|
||||||
|
restore.packages = res.data.packages;
|
||||||
|
} catch (e) {
|
||||||
|
restore.sourceError = errText(e);
|
||||||
|
} finally {
|
||||||
|
restore.checking = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
watch(() => restore.sourceId, checkSource);
|
||||||
|
|
||||||
|
const askRestore = () => {
|
||||||
|
const p = selectedPackage.value;
|
||||||
|
restoreModal.value.open({
|
||||||
|
title: 'Restore from Backup?',
|
||||||
|
message:
|
||||||
|
`Package: ${p.server_name}, ${utcTime(p.created_at)} (${formatTime(p.created_at)} local)\n\n` +
|
||||||
|
'This replaces:\n' +
|
||||||
|
'- the monitoring database (statistics, administrator accounts, 2FA),\n' +
|
||||||
|
'- the profiler database and the server settings,\n' +
|
||||||
|
'- the PKI (CA, keys, certificates) and the client profiles.\n\n' +
|
||||||
|
'OpenVPN is stopped and started again; connected clients are disconnected. ' +
|
||||||
|
'The current state is saved to a local safety copy first. You will have to log in again.',
|
||||||
|
confirmText: 'Yes, Restore',
|
||||||
|
confirmBtnClass: 'btn-action-danger',
|
||||||
|
data: p
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const confirmRestore = async (p) => {
|
||||||
|
try {
|
||||||
|
await profilesApiClient.post('/backup/restore', {
|
||||||
|
destination_id: restore.sourceId,
|
||||||
|
package: p.name,
|
||||||
|
passphrase: p.encrypted ? restore.passphrase : null
|
||||||
|
});
|
||||||
|
restoreFinishedHere.value = false;
|
||||||
|
restore.passphrase = '';
|
||||||
|
job.kind = 'restore';
|
||||||
|
job.state = 'running';
|
||||||
|
await loadStatus();
|
||||||
|
startPolling();
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(errText(e), 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const logInAgain = () => {
|
||||||
|
localStorage.removeItem('ovpmon_token');
|
||||||
|
localStorage.removeItem('ovpmon_user');
|
||||||
|
window.location.href = '/login';
|
||||||
|
};
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
try {
|
||||||
|
await loadSettings();
|
||||||
|
await loadDestinations();
|
||||||
|
selectAllUsable();
|
||||||
|
await Promise.all([loadHistory(), loadStatus()]);
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(`Failed to load backup settings: ${errText(e)}`, 'error');
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
onUnmounted(stopPolling);
|
||||||
|
</script>
|
||||||
@@ -89,7 +89,7 @@
|
|||||||
<tr v-if="activeCerts.length > 0" class="section-divider">
|
<tr v-if="activeCerts.length > 0" class="section-divider">
|
||||||
<td colspan="6">Active Certificates ({{ activeCerts.length }})</td>
|
<td colspan="6">Active Certificates ({{ activeCerts.length }})</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr v-for="cert in activeCerts" :key="cert.id + '_active'" 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">
|
<td v-note-tooltip="cert.note">
|
||||||
<div class="fw-semibold" style="color: var(--text-heading);">
|
<div class="fw-semibold" style="color: var(--text-heading);">
|
||||||
{{ cert.username }}
|
{{ cert.username }}
|
||||||
@@ -102,7 +102,7 @@
|
|||||||
<td class="fw-semibold" :class="getDaysClass(cert.days_remaining)">
|
<td class="fw-semibold" :class="getDaysClass(cert.days_remaining)">
|
||||||
{{ cert.days_remaining }}
|
{{ cert.days_remaining }}
|
||||||
</td>
|
</td>
|
||||||
<td v-html="getStatusBadgeHTML(cert)"></td>
|
<td><StatusBadge :profile="cert" /></td>
|
||||||
<td>
|
<td>
|
||||||
<button class="btn btn-sm btn-link text-warning p-0 me-2" title="Download Config" @click.stop="downloadConfig(cert)">
|
<button class="btn btn-sm btn-link text-warning p-0 me-2" title="Download Config" @click.stop="downloadConfig(cert)">
|
||||||
<i class="fas fa-download"></i>
|
<i class="fas fa-download"></i>
|
||||||
@@ -118,7 +118,7 @@
|
|||||||
<tr class="section-divider">
|
<tr class="section-divider">
|
||||||
<td colspan="6">Expired / Revoked ({{ expiredCerts.length }})</td>
|
<td colspan="6">Expired / Revoked ({{ expiredCerts.length }})</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr v-for="cert in expiredCerts" :key="cert.id + '_expired'" 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">
|
<td v-note-tooltip="cert.note">
|
||||||
<div class="fw-semibold" style="color: var(--text-heading);">
|
<div class="fw-semibold" style="color: var(--text-heading);">
|
||||||
{{ cert.username }}
|
{{ cert.username }}
|
||||||
@@ -131,7 +131,7 @@
|
|||||||
<td class="fw-semibold text-muted">
|
<td class="fw-semibold text-muted">
|
||||||
{{ cert.days_remaining }}
|
{{ cert.days_remaining }}
|
||||||
</td>
|
</td>
|
||||||
<td v-html="getStatusBadgeHTML(cert)"></td>
|
<td><StatusBadge :profile="cert" /></td>
|
||||||
<td>
|
<td>
|
||||||
<button class="btn btn-sm btn-link text-danger p-0" title="Revoke" @click.stop="revokeClient(cert)" :disabled="cert.is_revoked">
|
<button class="btn btn-sm btn-link text-danger p-0" title="Revoke" @click.stop="revokeClient(cert)" :disabled="cert.is_revoked">
|
||||||
<i class="fas fa-ban"></i>
|
<i class="fas fa-ban"></i>
|
||||||
@@ -156,6 +156,7 @@ import { useApi } from '../composables/useApi';
|
|||||||
import NewClientModal from '../components/NewClientModal.vue';
|
import NewClientModal from '../components/NewClientModal.vue';
|
||||||
import ConfirmModal from '../components/ConfirmModal.vue';
|
import ConfirmModal from '../components/ConfirmModal.vue';
|
||||||
import ProfileDetailsModal from '../components/ProfileDetailsModal.vue';
|
import ProfileDetailsModal from '../components/ProfileDetailsModal.vue';
|
||||||
|
import StatusBadge from '../components/StatusBadge.vue';
|
||||||
import vNoteTooltip from '../directives/noteTooltip';
|
import vNoteTooltip from '../directives/noteTooltip';
|
||||||
import { useToast } from '../composables/useToast';
|
import { useToast } from '../composables/useToast';
|
||||||
import { usePkiStatus } from '../composables/usePkiStatus';
|
import { usePkiStatus } from '../composables/usePkiStatus';
|
||||||
@@ -190,23 +191,6 @@ const getDaysClass = (days) => {
|
|||||||
return 'text-success';
|
return 'text-success';
|
||||||
};
|
};
|
||||||
|
|
||||||
const getStatusBadgeHTML = (cert) => {
|
|
||||||
if (cert.is_revoked) {
|
|
||||||
return '<span class="status-badge status-expired"><i class="fas fa-ban me-1"></i>Revoked</span>';
|
|
||||||
}
|
|
||||||
if (cert.is_expired) {
|
|
||||||
return '<span class="status-badge status-expired"><i class="fas fa-times-circle me-1"></i>Expired</span>';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Days check logic for expiring soon warning
|
|
||||||
if (cert.days_remaining !== null && cert.days_remaining <= 30) {
|
|
||||||
return '<span class="status-badge status-warning"><i class="fas fa-exclamation-triangle me-1"></i>Expiring Soon</span>';
|
|
||||||
}
|
|
||||||
|
|
||||||
return '<span class="status-badge status-valid"><i class="fas fa-check-circle me-1"></i>Active</span>';
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
// Data Processing
|
// Data Processing
|
||||||
const filteredData = computed(() => {
|
const filteredData = computed(() => {
|
||||||
let data = allProfiles.value;
|
let data = allProfiles.value;
|
||||||
@@ -234,8 +218,8 @@ const categorized = computed(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Sort logic
|
// Sort logic
|
||||||
active.sort((a,b) => (a.days_remaining || 9999) - (b.days_remaining || 9999));
|
active.sort((a,b) => (a.days_remaining ?? 9999) - (b.days_remaining ?? 9999));
|
||||||
expired.sort((a,b) => (b.days_remaining || -9999) - (a.days_remaining || -9999));
|
expired.sort((a,b) => (b.days_remaining ?? -9999) - (a.days_remaining ?? -9999));
|
||||||
|
|
||||||
return { active, expired };
|
return { active, expired };
|
||||||
});
|
});
|
||||||
@@ -312,6 +296,8 @@ const downloadConfig = async (cert) => {
|
|||||||
document.body.appendChild(link);
|
document.body.appendChild(link);
|
||||||
link.click();
|
link.click();
|
||||||
document.body.removeChild(link);
|
document.body.removeChild(link);
|
||||||
|
// Release the blob after the browser has started the download
|
||||||
|
setTimeout(() => window.URL.revokeObjectURL(url), 1000);
|
||||||
} catch(e) {
|
} catch(e) {
|
||||||
showToast('Could not download config: ' + (e.response?.data?.detail || e.message), 'error');
|
showToast('Could not download config: ' + (e.response?.data?.detail || e.message), 'error');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,10 @@
|
|||||||
<div class="stat-value">{{ stats.activeClients }}</div>
|
<div class="stat-value">{{ stats.activeClients }}</div>
|
||||||
<div class="stat-label">Active Clients</div>
|
<div class="stat-label">Active Clients</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="stat-item">
|
||||||
|
<div class="stat-value">{{ stats.totalSessions }}</div>
|
||||||
|
<div class="stat-label">Active Sessions</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-3">
|
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-3">
|
||||||
@@ -52,10 +56,10 @@
|
|||||||
<th>Client Name</th>
|
<th>Client Name</th>
|
||||||
<th>Real Address</th>
|
<th>Real Address</th>
|
||||||
<th>Status</th>
|
<th>Status</th>
|
||||||
<th @click="currentSort = 'received'" class="cursor-pointer" :class="{'active-sort': currentSort === 'received'}">
|
<th @click="currentSort = 'received'" @keydown.enter="currentSort = 'received'" tabindex="0" class="cursor-pointer" :class="{'active-sort': currentSort === 'received'}">
|
||||||
Received <i v-if="currentSort === 'received'" class="fas fa-sort-down ms-1"></i>
|
Received <i v-if="currentSort === 'received'" class="fas fa-sort-down ms-1"></i>
|
||||||
</th>
|
</th>
|
||||||
<th @click="currentSort = 'sent'" class="cursor-pointer" :class="{'active-sort': currentSort === 'sent'}">
|
<th @click="currentSort = 'sent'" @keydown.enter="currentSort = 'sent'" tabindex="0" class="cursor-pointer" :class="{'active-sort': currentSort === 'sent'}">
|
||||||
Sent <i v-if="currentSort === 'sent'" class="fas fa-sort-down ms-1"></i>
|
Sent <i v-if="currentSort === 'sent'" class="fas fa-sort-down ms-1"></i>
|
||||||
</th>
|
</th>
|
||||||
<th>Down Speed</th>
|
<th>Down Speed</th>
|
||||||
@@ -78,17 +82,24 @@
|
|||||||
{{ group.status }} Clients
|
{{ group.status }} Clients
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr v-for="c in group.items" :key="c.common_name">
|
<template v-for="c in group.items" :key="c.common_name">
|
||||||
|
<tr>
|
||||||
<td>
|
<td>
|
||||||
<a @click="openHistory(c.common_name)" class="client-link">
|
<a href="#" @click.prevent="openHistory(c.common_name)" class="client-link">
|
||||||
{{ c.common_name }} <i class="fas fa-chart-area ms-1 small opacity-50"></i>
|
{{ c.common_name }} <i class="fas fa-chart-area ms-1 small opacity-50"></i>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td class="small text-muted">{{ c.real_address || '-' }}</td>
|
<td class="small text-muted">{{ c.sessions_count > 1 ? `${c.sessions_count} devices` : (c.real_address || '-') }}</td>
|
||||||
<td>
|
<td>
|
||||||
<span class="status-badge" :class="c.status === 'Active' ? 'status-active' : 'status-disconnected'">
|
<span class="status-badge" :class="c.status === 'Active' ? 'status-active' : 'status-disconnected'">
|
||||||
{{ c.status }}
|
{{ c.status }}
|
||||||
</span>
|
</span>
|
||||||
|
<button v-if="sessionsBadge(c)" type="button" class="btn btn-sm btn-outline-secondary ms-2 py-0 px-1"
|
||||||
|
:aria-expanded="expanded.includes(c.common_name)" :title="'Show sessions'"
|
||||||
|
@click="expanded = toggleExpanded(expanded, c.common_name)">
|
||||||
|
{{ sessionsBadge(c) }}
|
||||||
|
<i class="fas ms-1 small" :class="expanded.includes(c.common_name) ? 'fa-chevron-up' : 'fa-chevron-down'"></i>
|
||||||
|
</button>
|
||||||
</td>
|
</td>
|
||||||
<td class="font-monospace small">{{ formatBytes(c.total_bytes_received) }}</td>
|
<td class="font-monospace small">{{ formatBytes(c.total_bytes_received) }}</td>
|
||||||
<td class="font-monospace small">{{ formatBytes(c.total_bytes_sent) }}</td>
|
<td class="font-monospace small">{{ formatBytes(c.total_bytes_sent) }}</td>
|
||||||
@@ -109,6 +120,15 @@
|
|||||||
|
|
||||||
<td class="small text-muted">{{ formatDate(c.last_activity) }}</td>
|
<td class="small text-muted">{{ formatDate(c.last_activity) }}</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
<tr v-for="(sess, i) in visibleSessions(c, expanded)" :key="`${c.common_name}-s${i}`" class="session-row">
|
||||||
|
<td class="small text-muted ps-4"><i class="fas fa-level-up-alt fa-rotate-90 me-2 opacity-50"></i>Session {{ i + 1 }}</td>
|
||||||
|
<td class="small text-muted">{{ sess.real_address || '-' }}</td>
|
||||||
|
<td class="small text-muted" colspan="2">Since {{ formatDate(sess.connected_since) }}</td>
|
||||||
|
<td class="font-monospace small">Down {{ sess.received_mb }} MB</td>
|
||||||
|
<td class="font-monospace small">Up {{ sess.sent_mb }} MB</td>
|
||||||
|
<td colspan="2"></td>
|
||||||
|
</tr>
|
||||||
|
</template>
|
||||||
</template>
|
</template>
|
||||||
</template>
|
</template>
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -125,8 +145,9 @@ import { useApi } from '../composables/useApi';
|
|||||||
import { useFormatters } from '../composables/useFormatters';
|
import { useFormatters } from '../composables/useFormatters';
|
||||||
import HistoryModal from '../components/HistoryModal.vue';
|
import HistoryModal from '../components/HistoryModal.vue';
|
||||||
import { useAppConfig } from '../composables/useAppConfig';
|
import { useAppConfig } from '../composables/useAppConfig';
|
||||||
|
import { sessionsBadge, toggleExpanded, visibleSessions } from '../utils/sessions';
|
||||||
|
|
||||||
const { fetchStats, apiClient } = useApi();
|
const { fetchStats } = useApi();
|
||||||
const { formatBytes, formatRate, parseServerDate } = useFormatters();
|
const { formatBytes, formatRate, parseServerDate } = useFormatters();
|
||||||
const { config } = useAppConfig();
|
const { config } = useAppConfig();
|
||||||
|
|
||||||
@@ -137,6 +158,7 @@ const searchQuery = ref('');
|
|||||||
const hideDisconnected = ref(false);
|
const hideDisconnected = ref(false);
|
||||||
const currentSort = ref('sent');
|
const currentSort = ref('sent');
|
||||||
const historyModal = ref(null);
|
const historyModal = ref(null);
|
||||||
|
const expanded = ref([]); // CNs with an open session list; survives auto-refresh
|
||||||
|
|
||||||
let intervalId = null;
|
let intervalId = null;
|
||||||
|
|
||||||
@@ -144,14 +166,16 @@ const stats = computed(() => {
|
|||||||
let totalReceived = 0;
|
let totalReceived = 0;
|
||||||
let totalSent = 0;
|
let totalSent = 0;
|
||||||
let activeClients = 0;
|
let activeClients = 0;
|
||||||
|
let totalSessions = 0;
|
||||||
|
|
||||||
clients.value.forEach(c => {
|
clients.value.forEach(c => {
|
||||||
totalReceived += c.total_bytes_received || 0;
|
totalReceived += c.total_bytes_received || 0;
|
||||||
totalSent += c.total_bytes_sent || 0;
|
totalSent += c.total_bytes_sent || 0;
|
||||||
if (c.status === 'Active') activeClients++;
|
if (c.status === 'Active') activeClients++;
|
||||||
|
totalSessions += c.sessions_count || 0;
|
||||||
});
|
});
|
||||||
|
|
||||||
return { totalReceived, totalSent, activeClients };
|
return { totalReceived, totalSent, activeClients, totalSessions };
|
||||||
});
|
});
|
||||||
|
|
||||||
const filteredClients = computed(() => {
|
const filteredClients = computed(() => {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
<div class="brand-logo">
|
<div class="brand-logo">
|
||||||
<i class="fas fa-shield-alt"></i>
|
<i class="fas fa-shield-alt"></i>
|
||||||
</div>
|
</div>
|
||||||
<h1>OpenVPN Monitor</h1>
|
<h1>OpenVPN Controller</h1>
|
||||||
<p class="text-muted">Secure Access Control</p>
|
<p class="text-muted">Secure Access Control</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -13,28 +13,32 @@
|
|||||||
<!-- Standard Login -->
|
<!-- Standard Login -->
|
||||||
<form v-if="!requires2FA" @submit.prevent="handleLogin">
|
<form v-if="!requires2FA" @submit.prevent="handleLogin">
|
||||||
<div class="mb-4">
|
<div class="mb-4">
|
||||||
<label class="form-label">Username</label>
|
<label class="form-label" for="loginUsername">Username</label>
|
||||||
<div class="input-group">
|
<div class="input-group">
|
||||||
<span class="input-group-text"><i class="fas fa-user"></i></span>
|
<span class="input-group-text"><i class="fas fa-user"></i></span>
|
||||||
<input
|
<input
|
||||||
|
id="loginUsername"
|
||||||
type="text"
|
type="text"
|
||||||
class="form-control"
|
class="form-control"
|
||||||
v-model="form.username"
|
v-model="form.username"
|
||||||
placeholder="Enter username"
|
placeholder="Enter username"
|
||||||
|
autocomplete="username"
|
||||||
required
|
required
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mb-4">
|
<div class="mb-4">
|
||||||
<label class="form-label">Password</label>
|
<label class="form-label" for="loginPassword">Password</label>
|
||||||
<div class="input-group">
|
<div class="input-group">
|
||||||
<span class="input-group-text"><i class="fas fa-lock"></i></span>
|
<span class="input-group-text"><i class="fas fa-lock"></i></span>
|
||||||
<input
|
<input
|
||||||
|
id="loginPassword"
|
||||||
type="password"
|
type="password"
|
||||||
class="form-control"
|
class="form-control"
|
||||||
v-model="form.password"
|
v-model="form.password"
|
||||||
placeholder="Enter password"
|
placeholder="Enter password"
|
||||||
|
autocomplete="current-password"
|
||||||
required
|
required
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
@@ -65,6 +69,9 @@
|
|||||||
v-model="otp"
|
v-model="otp"
|
||||||
placeholder="000 000"
|
placeholder="000 000"
|
||||||
maxlength="6"
|
maxlength="6"
|
||||||
|
inputmode="numeric"
|
||||||
|
autocomplete="one-time-code"
|
||||||
|
aria-label="6-digit authentication code"
|
||||||
required
|
required
|
||||||
autofocus
|
autofocus
|
||||||
>
|
>
|
||||||
@@ -86,7 +93,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="login-footer text-center mt-4">
|
<div class="login-footer text-center mt-4">
|
||||||
<p class="small text-muted">© 2026 Admin Dashboard</p>
|
<p class="small text-muted">© 2026 OpenVPN Controller</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -98,7 +105,7 @@ import { useRouter } from 'vue-router';
|
|||||||
import { useApi } from '../composables/useApi';
|
import { useApi } from '../composables/useApi';
|
||||||
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { apiClient } = useApi();
|
const { authApiClient } = useApi();
|
||||||
const loading = ref(false);
|
const loading = ref(false);
|
||||||
const error = ref('');
|
const error = ref('');
|
||||||
const requires2FA = ref(false);
|
const requires2FA = ref(false);
|
||||||
@@ -114,9 +121,7 @@ const handleLogin = async () => {
|
|||||||
loading.value = true;
|
loading.value = true;
|
||||||
error.value = '';
|
error.value = '';
|
||||||
try {
|
try {
|
||||||
// Auth routes are under /api/auth, while apiClient defaults to /api/v1
|
const response = await authApiClient.post('/login', form);
|
||||||
// We use a relative path with '..' to go up to /api
|
|
||||||
const response = await apiClient.post('../auth/login', form);
|
|
||||||
if (response.data.requires_2fa) {
|
if (response.data.requires_2fa) {
|
||||||
requires2FA.value = true;
|
requires2FA.value = true;
|
||||||
tempToken.value = response.data.temp_token;
|
tempToken.value = response.data.temp_token;
|
||||||
@@ -137,7 +142,7 @@ const handleVerify2FA = async () => {
|
|||||||
loading.value = true;
|
loading.value = true;
|
||||||
error.value = '';
|
error.value = '';
|
||||||
try {
|
try {
|
||||||
const response = await apiClient.post('../auth/verify-2fa', {
|
const response = await authApiClient.post('/verify-2fa', {
|
||||||
temp_token: tempToken.value,
|
temp_token: tempToken.value,
|
||||||
otp: otp.value
|
otp: otp.value
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,251 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div class="login-page">
|
|
||||||
<div class="login-card">
|
|
||||||
<div class="login-header">
|
|
||||||
<div class="brand-logo">
|
|
||||||
<i class="fas fa-shield-alt"></i>
|
|
||||||
</div>
|
|
||||||
<h1>OpenVPN Monitor</h1>
|
|
||||||
<p class="text-muted">Secure Access Control</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="login-body">
|
|
||||||
<!-- Standard Login -->
|
|
||||||
<form v-if="!requires2FA" @submit.prevent="handleLogin">
|
|
||||||
<div class="mb-4">
|
|
||||||
<label class="form-label">Username</label>
|
|
||||||
<div class="input-group">
|
|
||||||
<span class="input-group-text"><i class="fas fa-user"></i></span>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
class="form-control"
|
|
||||||
v-model="form.username"
|
|
||||||
placeholder="Enter username"
|
|
||||||
required
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="mb-4">
|
|
||||||
<label class="form-label">Password</label>
|
|
||||||
<div class="input-group">
|
|
||||||
<span class="input-group-text"><i class="fas fa-lock"></i></span>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
class="form-control"
|
|
||||||
v-model="form.password"
|
|
||||||
placeholder="Enter password"
|
|
||||||
required
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div v-if="error" class="alert alert-danger fade show mb-4">
|
|
||||||
<i class="fas fa-exclamation-circle me-2"></i>{{ error }}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button type="submit" class="btn btn-primary w-100 py-2 fw-bold" :disabled="loading">
|
|
||||||
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
|
||||||
Sign In
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<!-- 2FA Verification -->
|
|
||||||
<form v-else @submit.prevent="handleVerify2FA">
|
|
||||||
<div class="text-center mb-4">
|
|
||||||
<i class="fas fa-key fa-3x text-warning mb-3"></i>
|
|
||||||
<h3>Two-Factor Authentication</h3>
|
|
||||||
<p class="text-muted">Enter the 6-digit code from your authenticator app.</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="mb-4">
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
class="form-control form-control-lg text-center fw-bold"
|
|
||||||
v-model="otp"
|
|
||||||
placeholder="000 000"
|
|
||||||
maxlength="6"
|
|
||||||
required
|
|
||||||
autofocus
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div v-if="error" class="alert alert-danger fade show mb-4">
|
|
||||||
<i class="fas fa-exclamation-circle me-2"></i>{{ error }}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button type="submit" class="btn btn-warning w-100 py-2 fw-bold" :disabled="loading">
|
|
||||||
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
|
||||||
Verify & Continue
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<button type="button" class="btn btn-link w-100 mt-2 text-muted" @click="resetLogin">
|
|
||||||
Back to login
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="login-footer text-center mt-4">
|
|
||||||
<p class="small text-muted">© 2026 Admin Dashboard</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script setup>
|
|
||||||
import { reactive, ref } from 'vue';
|
|
||||||
import { useRouter } from 'vue-router';
|
|
||||||
import { useApi } from '../composables/useApi';
|
|
||||||
|
|
||||||
const router = useRouter();
|
|
||||||
const { apiClient } = useApi();
|
|
||||||
const loading = ref(false);
|
|
||||||
const error = ref('');
|
|
||||||
const requires2FA = ref(false);
|
|
||||||
const tempToken = ref('');
|
|
||||||
const otp = ref('');
|
|
||||||
|
|
||||||
const form = reactive({
|
|
||||||
username: '',
|
|
||||||
password: ''
|
|
||||||
});
|
|
||||||
|
|
||||||
const handleLogin = async () => {
|
|
||||||
loading.value = true;
|
|
||||||
error.value = '';
|
|
||||||
try {
|
|
||||||
// Auth routes are under /api/auth, while apiClient defaults to /api/v1
|
|
||||||
// We use a relative path with '..' to go up to /api
|
|
||||||
const response = await apiClient.post('../auth/login', form);
|
|
||||||
if (response.data.requires_2fa) {
|
|
||||||
requires2FA.value = true;
|
|
||||||
tempToken.value = response.data.temp_token;
|
|
||||||
} else {
|
|
||||||
localStorage.setItem('ovpmon_token', response.data.token);
|
|
||||||
localStorage.setItem('ovpmon_user', response.data.username);
|
|
||||||
router.push('/');
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Login Error:', err);
|
|
||||||
error.value = err.response?.data?.error || 'Login failed. Please check your connection.';
|
|
||||||
} finally {
|
|
||||||
loading.value = false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleVerify2FA = async () => {
|
|
||||||
loading.value = true;
|
|
||||||
error.value = '';
|
|
||||||
try {
|
|
||||||
const response = await apiClient.post('../auth/verify-2fa', {
|
|
||||||
temp_token: tempToken.value,
|
|
||||||
otp: otp.value
|
|
||||||
});
|
|
||||||
localStorage.setItem('ovpmon_token', response.data.token);
|
|
||||||
localStorage.setItem('ovpmon_user', response.data.username);
|
|
||||||
router.push('/');
|
|
||||||
} catch (err) {
|
|
||||||
error.value = err.response?.data?.error || 'Verification failed.';
|
|
||||||
} finally {
|
|
||||||
loading.value = false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const resetLogin = () => {
|
|
||||||
requires2FA.value = false;
|
|
||||||
tempToken.value = '';
|
|
||||||
otp.value = '';
|
|
||||||
error.value = '';
|
|
||||||
};
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.login-page {
|
|
||||||
min-height: 100vh;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
background-color: var(--bg-body);
|
|
||||||
padding: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.login-card {
|
|
||||||
width: 100%;
|
|
||||||
max-width: 400px;
|
|
||||||
background: var(--bg-card);
|
|
||||||
padding: 40px;
|
|
||||||
border-radius: 12px;
|
|
||||||
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
|
|
||||||
border: 1px solid var(--border-color);
|
|
||||||
}
|
|
||||||
|
|
||||||
.login-header {
|
|
||||||
text-align: center;
|
|
||||||
margin-bottom: 30px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.brand-logo {
|
|
||||||
width: 60px;
|
|
||||||
height: 60px;
|
|
||||||
background: var(--accent-color);
|
|
||||||
color: white;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
font-size: 24px;
|
|
||||||
border-radius: 12px;
|
|
||||||
margin: 0 auto 15px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.login-header h1 {
|
|
||||||
font-size: 24px;
|
|
||||||
font-weight: 700;
|
|
||||||
margin: 0;
|
|
||||||
color: var(--text-heading);
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-label {
|
|
||||||
font-weight: 600;
|
|
||||||
font-size: 0.85rem;
|
|
||||||
color: var(--text-heading);
|
|
||||||
}
|
|
||||||
|
|
||||||
.input-group-text {
|
|
||||||
background: var(--bg-element);
|
|
||||||
border-color: var(--border-color);
|
|
||||||
color: var(--text-muted);
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-control {
|
|
||||||
background: var(--bg-input);
|
|
||||||
border-color: var(--border-color);
|
|
||||||
color: var(--text-main);
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-control:focus {
|
|
||||||
border-color: var(--accent-color);
|
|
||||||
box-shadow: 0 0 0 3px rgba(9, 105, 218, 0.1);
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-primary {
|
|
||||||
background-color: #1652B8;
|
|
||||||
border-color: #1652B8;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-primary:hover {
|
|
||||||
background-color: #1449a5;
|
|
||||||
border-color: #1449a5;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-warning {
|
|
||||||
background-color: #EC7C31;
|
|
||||||
border-color: #EC7C31;
|
|
||||||
color: white;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-warning:hover {
|
|
||||||
background-color: #d66d2a;
|
|
||||||
border-color: #d66d2a;
|
|
||||||
color: white;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
@@ -165,6 +165,8 @@
|
|||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<ConfirmModal ref="initModal" @confirm="runInit" />
|
||||||
|
<ConfirmModal ref="clearModal" @confirm="runClear" />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -174,6 +176,7 @@ import { ref, computed, onMounted, onUnmounted, reactive } from 'vue';
|
|||||||
import { useApi } from '../composables/useApi';
|
import { useApi } from '../composables/useApi';
|
||||||
import { useToast } from '../composables/useToast';
|
import { useToast } from '../composables/useToast';
|
||||||
import { usePkiStatus } from '../composables/usePkiStatus';
|
import { usePkiStatus } from '../composables/usePkiStatus';
|
||||||
|
import ConfirmModal from '../components/ConfirmModal.vue';
|
||||||
|
|
||||||
const { profilesApiClient } = useApi();
|
const { profilesApiClient } = useApi();
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
@@ -198,6 +201,8 @@ const form = reactive({
|
|||||||
easyrsa_batch: true
|
easyrsa_batch: true
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const initModal = ref(null);
|
||||||
|
const clearModal = ref(null);
|
||||||
const isLoading = ref(false);
|
const isLoading = ref(false);
|
||||||
const action = ref(''); // 'save', 'init', 'clear'
|
const action = ref(''); // 'save', 'init', 'clear'
|
||||||
|
|
||||||
@@ -232,7 +237,7 @@ const loadConfig = async () => {
|
|||||||
|
|
||||||
// Populate form
|
// Populate form
|
||||||
Object.keys(data).forEach(key => {
|
Object.keys(data).forEach(key => {
|
||||||
if (form.hasOwnProperty(key)) {
|
if (Object.hasOwn(form, key)) {
|
||||||
form[key] = data[key];
|
form[key] = data[key];
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -290,9 +295,16 @@ const handleSave = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleInit = async () => {
|
const handleInit = () => {
|
||||||
if (!confirm('Are you sure you want to Initialize system? This will start the PKI initialization process.')) return;
|
initModal.value.open({
|
||||||
|
title: 'Initialize PKI?',
|
||||||
|
message: 'Are you sure you want to initialize the system? This will start the PKI initialization process.',
|
||||||
|
confirmText: 'Yes, initialize',
|
||||||
|
confirmBtnClass: 'btn-action-primary'
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const runInit = async () => {
|
||||||
isLoading.value = true;
|
isLoading.value = true;
|
||||||
action.value = 'init'; // locks the button until the server confirms the job state
|
action.value = 'init'; // locks the button until the server confirms the job state
|
||||||
try {
|
try {
|
||||||
@@ -312,9 +324,16 @@ const handleInit = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleClear = async () => {
|
const handleClear = () => {
|
||||||
if (!confirm('Are you sure you want to CLEAR PKI? This will delete all certificates and cannot be undone.')) return;
|
clearModal.value.open({
|
||||||
|
title: 'Clear PKI?',
|
||||||
|
message: 'Are you sure you want to CLEAR the PKI? This will delete all certificates and cannot be undone.',
|
||||||
|
confirmText: 'Yes, clear',
|
||||||
|
confirmBtnClass: 'btn-action-danger'
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const runClear = async () => {
|
||||||
isLoading.value = true;
|
isLoading.value = true;
|
||||||
action.value = 'clear';
|
action.value = 'clear';
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -84,6 +84,8 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<ConfirmModal ref="confirmModal" @confirm="runControl" />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -92,6 +94,7 @@ import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
|
|||||||
import { useApi } from '../composables/useApi';
|
import { useApi } from '../composables/useApi';
|
||||||
import { useToast } from '../composables/useToast';
|
import { useToast } from '../composables/useToast';
|
||||||
import { usePkiStatus } from '../composables/usePkiStatus';
|
import { usePkiStatus } from '../composables/usePkiStatus';
|
||||||
|
import ConfirmModal from '../components/ConfirmModal.vue';
|
||||||
|
|
||||||
const { profilesApiClient } = useApi();
|
const { profilesApiClient } = useApi();
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
@@ -114,6 +117,7 @@ const stats = reactive({
|
|||||||
uptime: null
|
uptime: null
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const confirmModal = ref(null);
|
||||||
const isLoading = ref(false);
|
const isLoading = ref(false);
|
||||||
const action = ref(''); // 'start', 'stop', 'restart'
|
const action = ref(''); // 'start', 'stop', 'restart'
|
||||||
let pollInterval = null;
|
let pollInterval = null;
|
||||||
@@ -131,9 +135,19 @@ const fetchStats = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleControl = async (cmd) => {
|
const CONFIRM_CLASSES = { start: 'btn-action-primary', restart: 'btn-action-save', stop: 'btn-action-danger' };
|
||||||
if (!confirm(`Are you sure you want to ${cmd.toUpperCase()} the OpenVPN service?`)) return;
|
|
||||||
|
|
||||||
|
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;
|
isLoading.value = true;
|
||||||
action.value = cmd;
|
action.value = cmd;
|
||||||
|
|
||||||
|
|||||||
@@ -264,6 +264,7 @@ import { ref, onMounted, reactive, watch } from 'vue';
|
|||||||
import { useApi } from '../composables/useApi';
|
import { useApi } from '../composables/useApi';
|
||||||
import { useToast } from '../composables/useToast';
|
import { useToast } from '../composables/useToast';
|
||||||
import { usePkiStatus } from '../composables/usePkiStatus';
|
import { usePkiStatus } from '../composables/usePkiStatus';
|
||||||
|
import { maskToCidr, parseCidr } from '../utils/cidr';
|
||||||
|
|
||||||
const { profilesApiClient } = useApi();
|
const { profilesApiClient } = useApi();
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
@@ -302,15 +303,8 @@ watch(isSplitTunnel, (val) => {
|
|||||||
form.tunnel_type = val ? 'SPLIT' : 'FULL';
|
form.tunnel_type = val ? 'SPLIT' : 'FULL';
|
||||||
});
|
});
|
||||||
|
|
||||||
// Helpers
|
// Netmask received from the server: used when the subnet is typed without a /nn suffix
|
||||||
function maskToCidr(mask) {
|
let currentNetmask = '';
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Methods
|
// Methods
|
||||||
const showMessage = (text, type = 'success') => toast.show(text, type);
|
const showMessage = (text, type = 'success') => toast.show(text, type);
|
||||||
@@ -329,7 +323,7 @@ const loadConfig = async () => {
|
|||||||
const data = payload.server ? payload.server : payload;
|
const data = payload.server ? payload.server : payload;
|
||||||
|
|
||||||
Object.keys(data).forEach(key => {
|
Object.keys(data).forEach(key => {
|
||||||
if (form.hasOwnProperty(key)) {
|
if (Object.hasOwn(form, key)) {
|
||||||
if (key === 'tunnel_type') {
|
if (key === 'tunnel_type') {
|
||||||
isSplitTunnel.value = data[key] === 'SPLIT';
|
isSplitTunnel.value = data[key] === 'SPLIT';
|
||||||
}
|
}
|
||||||
@@ -337,9 +331,10 @@ const loadConfig = async () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
currentNetmask = data.vpn_netmask || '';
|
||||||
if (data.vpn_network && data.vpn_netmask) {
|
if (data.vpn_network && data.vpn_netmask) {
|
||||||
const cidrSuffix = maskToCidr(data.vpn_netmask);
|
const cidrSuffix = maskToCidr(data.vpn_netmask);
|
||||||
if (cidrSuffix) {
|
if (cidrSuffix !== null) {
|
||||||
form.vpn_network = `${data.vpn_network}/${cidrSuffix}`;
|
form.vpn_network = `${data.vpn_network}/${cidrSuffix}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -351,20 +346,25 @@ const loadConfig = async () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleSave = 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;
|
isLoading.value = true;
|
||||||
action.value = 'save';
|
action.value = 'save';
|
||||||
|
|
||||||
const payload = { ...form };
|
const payload = { ...form };
|
||||||
payload.split_routes = payload.split_routes.filter(r => r && r.trim() !== '');
|
payload.split_routes = payload.split_routes.filter(r => r && r.trim() !== '');
|
||||||
payload.dns_servers = payload.dns_servers.filter(d => d && d.trim() !== '');
|
payload.dns_servers = payload.dns_servers.filter(d => d && d.trim() !== '');
|
||||||
|
payload.vpn_network = subnet.network;
|
||||||
if (payload.vpn_network.includes('/')) {
|
payload.vpn_netmask = subnet.netmask || currentNetmask || '255.255.255.0';
|
||||||
const [ip, suffix] = payload.vpn_network.split('/');
|
|
||||||
payload.vpn_network = ip;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await profilesApiClient.put('/config/server', payload);
|
await profilesApiClient.put('/config/server', payload);
|
||||||
|
currentNetmask = payload.vpn_netmask;
|
||||||
showMessage('Server configuration saved!', 'success');
|
showMessage('Server configuration saved!', 'success');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
showMessage(`Error saving: ${err.response?.data?.detail || err.message}`, 'error');
|
showMessage(`Error saving: ${err.response?.data?.detail || err.message}`, 'error');
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ export default defineConfig({
|
|||||||
output: {
|
output: {
|
||||||
manualChunks: {
|
manualChunks: {
|
||||||
'vendor-charts': ['chart.js'],
|
'vendor-charts': ['chart.js'],
|
||||||
'vendor-ui': ['bootstrap', 'sweetalert2']
|
'vendor-ui': ['bootstrap']
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# Учёт нескольких сессий одного пользователя (итог, 2026-10-06)
|
||||||
|
|
||||||
|
План: [2026-10-06_Multi_Session_Stats_PLAN.md](2026-10-06_Multi_Session_Stats_PLAN.md). Пользователь (CN) с несколькими устройствами (`duplicate-cn`) учитывается одной записью.
|
||||||
|
|
||||||
|
## Что сделано
|
||||||
|
|
||||||
|
| ID | Изменение |
|
||||||
|
|---|---|
|
||||||
|
| MS-1, MS-5 | `parse_status` берёт индекс колонки `Client ID` из строки `HEADER,CLIENT_LIST,...`; нет колонки или не число = `session_id None`. Ключ сессии `(CN, session_id or real_address, since_ts)` в кэше, базовой линии и снимке. Миграция 002: `active_sessions.session_id TEXT` (NULL допустим); старые строки снимка совпадают по запасному ключу |
|
||||||
|
| MS-4 | `clients.real_address` = адрес сессии с самым поздним началом; `last_bytes_*` = сумма текущих счётчиков всех сессий CN |
|
||||||
|
| MS-3 | `run_monitoring_cycle`: сессии сворачиваются в записи по CN (`merge_sessions_by_cn`) перед расчётом скоростей, `usage_history` и агрегацией: одна строка на CN за тик |
|
||||||
|
| MS-2, MS-3 (старые строки) | API: `current_recv_rate` / `current_sent_rate` = `MAX` по отметке времени от `SUM` скоростей; `get_client_history` (быстрый и обычный режимы) суммирует строки по `timestamp` до `MAX` |
|
||||||
|
| Документация | `Data_Architecture.md`, `API_Reference.md`, `APP_CORE/README.md`, эта сводка и строка в `Changes/README.md` |
|
||||||
|
|
||||||
|
Файлы: `APP_CORE/openvpn_gatherer_v3.py`, `APP_CORE/migrations.py`, `APP_CORE/openvpn_api_v3.py`, `APP_CORE/test_gatherer.py`, `APP_CORE/test_migrations.py`.
|
||||||
|
|
||||||
|
## Тесты
|
||||||
|
|
||||||
|
- `test_gatherer.py`: 2 новых теста (две сессии одного CN; `float` с тем же `Client ID` и перезапуск демона по снимку). До правки кода оба красные. `write_status` получил необязательный `client_id` (по умолчанию 1).
|
||||||
|
- `test_migrations.py`: ожидания обновлены под версию 2 (список применённых миграций, число миграций за запуск), добавлена проверка наличия колонки `session_id`. Новых тестов не добавлялось.
|
||||||
|
- Итог `pytest` в `APP_CORE`: 16 из 16 (14 прежних + 2 новых).
|
||||||
|
|
||||||
|
## Ручная проверка API (шаг 6)
|
||||||
|
|
||||||
|
Временная БД (миграции 1 и 2 применены), клиент `alice`, на двух отметках времени по две строки `usage_history` (две сессии): скорость Download 1,0 + 2,0 и 4,0 + 0,5.
|
||||||
|
|
||||||
|
| Проверка | Результат |
|
||||||
|
|---|---|
|
||||||
|
| `get_current_stats`: `current_recv_rate` / `current_sent_rate` | 4,5 / 0,45 (MAX от сумм: 3,0 и 4,5; прежнее поведение дало бы 4,0) |
|
||||||
|
| `get_client_history`, обычный режим | 2 точки: объём 300 и 450 байт, скорость 3,0 и 4,5 (суммы по сессиям) |
|
||||||
|
| `get_client_history`, быстрый режим (интервал 30 с) | объём 750, скорость 4,5 (MAX от сумм) |
|
||||||
|
|
||||||
|
## Отклонения от плана и замечания
|
||||||
|
|
||||||
|
- Отклонений от плана нет. Миграция 002 идемпотентна (колонка добавляется, только если её нет).
|
||||||
|
- Каталог `venv/` в корне проекта создан для запуска тестов; в `.gitignore` его нет, в `git status` он виден как неотслеживаемый.
|
||||||
|
- Не проверялось: работа на живом OpenVPN с `float` и `duplicate-cn`, обновление `update.sh` с миграцией 002 на тестовом хосте. Системная история (`/analytics`) уже суммировала по отметке времени, не менялась.
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# Учёт нескольких сессий одного пользователя (план, 2026-10-06)
|
||||||
|
|
||||||
|
Источник: анализ логики сбора статистики (запрос от 2026-10-06). Затронутый код: `APP_CORE/openvpn_gatherer_v3.py`, `APP_CORE/openvpn_api_v3.py`, `APP_CORE/migrations.py`, `APP_CORE/test_gatherer.py`.
|
||||||
|
|
||||||
|
Цель: пользователь (CN) с несколькими устройствами одновременно (`duplicate-cn`) учитывается **одной записью**: байты, скорость, история и «последние» значения агрегируются под учётной записью независимо от числа сессий.
|
||||||
|
|
||||||
|
## 1. Что уже верно (не меняем)
|
||||||
|
|
||||||
|
Итоги `clients.total_bytes_*` и корзины `stats_*` суммируют приросты всех сессий CN. Статус «Disconnected» ставится по CN, а не по сессии.
|
||||||
|
|
||||||
|
## 2. Проблемы и решения
|
||||||
|
|
||||||
|
| ID | Проблема | Решение |
|
||||||
|
|---|---|---|
|
||||||
|
| MS-1 (высокая) | Смена `real_address` без переподключения (`float`, Wi-Fi → LTE) меняет ключ сессии `(CN, адрес, начало)`; сессия считается новой, и её счётчики засчитываются повторно | Ключ сессии: `(CN, session_id, начало)`, где `session_id` это `Client ID` из статуса v2. Он не меняется при `float`. Если `Client ID` в статусе нет (старый OpenVPN), запасной ключ с `real_address` |
|
||||||
|
| MS-2 (средняя) | `current_recv_rate` / `current_sent_rate` = `MAX` по строкам сессий: при двух устройствах видна скорость одного | Скорость пользователя = **сумма** по сессиям за тик |
|
||||||
|
| MS-3 (средняя) | `usage_history` получает строку на сессию за тик: дубли времени в сыром графике, скорость в группировке берётся как `MAX` по сессиям | Писать **одну строку на CN за тик** (сумма байтов и скоростей). Для уже записанных строк (хранятся 7 дней) запросы API суммируют по `timestamp` до `MAX` |
|
||||||
|
| MS-4 (низкая) | `clients.real_address` и `last_bytes_*` отражают одну сессию (последнюю в списке / максимальную) | `real_address` = адрес сессии с самым поздним началом; `last_bytes_*` = **сумма** текущих счётчиков всех активных сессий |
|
||||||
|
| MS-5 (низкая) | Коллизия ключа: одинаковые CN, адрес и секунда подключения | Закрывается MS-1 (`Client ID` уникален в рамках процесса OpenVPN) |
|
||||||
|
|
||||||
|
## 3. Шаги
|
||||||
|
|
||||||
|
| # | Шаг | Результат |
|
||||||
|
|---|---|---|
|
||||||
|
| 0 | Тесты (минимум, см. п. 4) пишутся первыми и воспроизводят MS-1 и MS-3 на текущем коде (красные) | дефекты подтверждены |
|
||||||
|
| 1 | `parse_status`: индекс колонки `Client ID` берётся из строки `HEADER,CLIENT_LIST,...`; нет колонки или значение не число = `session_id = None`. В `client` добавляется `session_id` | сборщик знает идентификатор сессии |
|
||||||
|
| 2 | Миграция 002 (`migrations.py`): колонка `active_sessions.session_id TEXT` (NULL допустим). Резервная копия, проверки и защита от понижения версии уже в механизме миграций | снимок хранит идентификатор |
|
||||||
|
| 3 | Ключ сессии `(CN, session_id or real_address, since_ts)`; `_load_baseline` и запись снимка (шаг 6 цикла) используют тот же ключ. Старые строки снимка без `session_id` совпадают по запасному ключу, потерь при обновлении нет | MS-1, MS-5 закрыты |
|
||||||
|
| 4 | `update_client_status_and_bytes`: `real_address` берётся от сессии с максимальным `since_ts`; `last_bytes_*` = сумма `curr_recv/curr_sent` сессий CN | MS-4 закрыт |
|
||||||
|
| 5 | `run_monitoring_cycle`: перед `store_usage_history` и `aggregate` свернуть список сессий в список **по CN** (сумма `*_inc`, сумма скоростей, один `db_id`). `calculate_rates` считать по свёрнутому списку | MS-3 закрыт для новых данных, меньше записей |
|
||||||
|
| 6 | API: `current_*_rate` = `MAX` по `timestamp` от `SUM` скоростей; в `get_client_history` группировка по `timestamp` с `SUM` скорости перед `MAX` (быстрый и обычный режимы) | MS-2 закрыт, старые строки считаются верно |
|
||||||
|
| 7 | Документация: `DOCS/Core_Monitoring/Data_Architecture.md` (ключ сессии, агрегация по CN), `API_Reference.md` (смысл `real_address`, `last_bytes`, скорости), `APP_CORE/README.md`, строка в таблице `DOCS/Changes/README.md`, README.md проекта при необходимости, сводка `2026-10-06_Multi_Session_Stats.md` | документация актуальна |
|
||||||
|
|
||||||
|
## 4. Автотесты (минимум, 2 шт., в `test_gatherer.py`)
|
||||||
|
|
||||||
|
1. **Две сессии одного CN**: разные адреса и начала, разный трафик. Проверка: `clients.total_bytes_*` = сумма; в `usage_history` одна строка на тик, скорость = сумма; в `stats_5min` одна строка; отключение одной сессии оставляет статус Active и не искажает итог.
|
||||||
|
2. **`float`**: сессия меняет `real_address` при том же `Client ID` и начале. Проверка: прирост = разница счётчиков, без повторного учёта; то же после перезапуска демона (базовая линия из снимка с `session_id`).
|
||||||
|
|
||||||
|
Изменение API (шаг 6) проверяется вручную на копии БД с двумя сессиями (SQL-запросы), отдельный автотест не добавляется.
|
||||||
|
|
||||||
|
## 5. Совместимость и риски
|
||||||
|
|
||||||
|
- Схема: одна необязательная колонка, миграция автоматическая, перед ней резервная копия. Возврат на старый код после миграции требует восстановления БД из копии (защита от понижения версии, см. [Database migrations](../General/Database_Migrations.md)).
|
||||||
|
- Обновление при работающих сессиях: кэш пуст, базовая линия из старого снимка (без `session_id`) совпадает по запасному ключу, трафик не теряется и не дублируется.
|
||||||
|
- Значения `real_address` и `last_bytes_*` в таблице клиентов меняют смысл для пользователей с несколькими сессиями (суммарно, а не одна сессия). Подробности по каждой сессии остаются в `active_sessions`.
|
||||||
|
- Откат кода без миграции: не нужен, изменения сборщика и API обратимо совместимы со схемой (колонка необязательна).
|
||||||
|
|
||||||
|
## 6. Порядок выполнения
|
||||||
|
|
||||||
|
1. Утверждение плана.
|
||||||
|
2. Реализация субагентом (Sonnet 5.5, Medium Effort): шаги 0-6.
|
||||||
|
3. Проверка: `pytest` в `APP_CORE`, ручная проверка API (шаг 6).
|
||||||
|
4. Документация и сводка (шаг 7).
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# Скорость на графиках за период больше суток (сводка, 2026-10-07)
|
||||||
|
|
||||||
|
План: [2026-10-07_Aggregated_Speed_PLAN.md](2026-10-07_Aggregated_Speed_PLAN.md). Схема БД, миграции и гатерер не менялись.
|
||||||
|
|
||||||
|
## 1. Что изменено
|
||||||
|
|
||||||
|
- `APP_CORE/openvpn_api_v3.py`: словарь `BUCKET_SECONDS` (таблица -> секунды корзины) и функция `avg_rate_sql()`. Таблица берётся только из словаря, остальные аргументы это фиксированные выражения колонок, пользовательский ввод в SQL не попадает.
|
||||||
|
- `get_client_history` (ветка `is_aggregated`): `bytes_*_rate_mbps` = `bytes * 8 / 1e6 / секунды` вместо `0`.
|
||||||
|
- `get_analytics_data` (`7d`, `30d`; выбор таблицы не менялся, обе ветки используют `stats_hourly`): `total_rx_rate` / `total_tx_rate` считаются по сумме клиентов на одной отметке времени, дальше работают прежние `MAX` по интервалу группировки и zero-fill.
|
||||||
|
- Текущая неполная корзина: длительность `min(длина корзины, время с начала корзины)`, не менее 1 с (UTC, как в агрегатах).
|
||||||
|
- Fallback на `usage_history` (агрегатной таблицы нет) не затронут: отдаёт реальные скорости.
|
||||||
|
- `APP_UI/src/composables/useTrafficChart.js` (общий код графиков, правка действует для `HistoryModal.vue` и `Analytics.vue`): для диапазонов больше 24 часов (`7d`, `30d`) в режиме Speed серии называются «RX Mbps (avg)» / «TX Mbps (avg)»; для `1h`, `3h`, `24h` подписи прежние.
|
||||||
|
- `deploy/ui-dist` пересобран (`build-ui.sh --docker --publish`).
|
||||||
|
- Тест `APP_CORE/test_aggregated_speed.py`: временная БД с миграциями, клиент и две записи `stats_hourly` (450 MB rx / 90 MB tx); полная корзина даёт 1.0 / 0.2 Mbps, корзина, начавшаяся 30 минут назад, 2.0 / 0.4 Mbps; `get_analytics_data('7d')` даёт ненулевую скорость.
|
||||||
|
- Документация: `DOCS/Core_Monitoring/API_Reference.md`, `DOCS/Core_Monitoring/Data_Architecture.md`. Корневой `README.md` режим Speed не описывает, не менялся.
|
||||||
|
|
||||||
|
## 2. Результаты проверок
|
||||||
|
|
||||||
|
- `APP_CORE`, весь набор (venv проекта): 18 passed.
|
||||||
|
- UI в `node:20-alpine` на копии вне репозитория: `npm ci`, `lint` без замечаний, `test` 13 passed, `build` успешно. `check-ui.sh`: fresh.
|
||||||
|
- Стенд `ovpmon-test`: пересозданы только `app-api` и `app-ui` (`--no-deps`), `ovp-api` и `ovp-ui` healthy; `ovp-gatherer` и `ovp-profiler` не перезапускались (то же время старта и id). Ключ подписи JWT передан из окружения работающего контейнера (совпадение с профайлером проверено по хешу, значение нигде не выводилось). `GET http://127.0.0.1:8089/` даёт 200, `/api/v1/stats` без токена 401.
|
||||||
|
- `get_client_history` напрямую в контейнере `ovp-api` (БД открыта только на чтение), клиент `msalice`, 7 дней, `resolution=hourly`: 8 точек, все с ненулевой скоростью, например корзина 10:00 UTC: 4 820 448 байт rx / 4 819 188 байт tx = 0.0107 / 0.0107 Mbps; текущая корзина 11:00: 0.0107 Mbps (при простой нормировке на 3600 с была бы занижена). `get_analytics_data('7d')` и `('30d')`: 96 точек, максимум `total_rx_rate` 0.0203 Mbps.
|
||||||
|
|
||||||
|
## 3. Не проверено
|
||||||
|
|
||||||
|
- Визуальная проверка графиков в браузере (выполняет владелец).
|
||||||
|
- Работа через HTTP с токеном (учётные записи не создавались и не подбирались): проверен вызов метода напрямую.
|
||||||
|
- Отдельный тест на `resolution` `5min`, `15min`, `6h`, `daily` не писался (минимум тестов); формула общая, значения берутся из словаря.
|
||||||
|
|
||||||
|
## 4. Ограничения
|
||||||
|
|
||||||
|
- Средняя скорость сглаживает кратковременные пики; на периодах больше суток это отражено подписью «avg». В Analytics для `7d` и `30d` на точку берётся максимум часовых средних.
|
||||||
|
- Пиковые значения на больших периодах потребуют варианта 2 (колонки максимумов в агрегатах, миграция): вне этого изменения.
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Скорость на графиках за период больше суток (план, 2026-10-07)
|
||||||
|
|
||||||
|
Основание: на графиках клиента (модальное окно) и в Analytics режим Speed (Mbps) пуст для периодов 7d и 30d, на периодах до 24 часов скорость есть.
|
||||||
|
|
||||||
|
## 1. Причина
|
||||||
|
|
||||||
|
Для периодов больше 24 часов API читает агрегатные таблицы `stats_5min`, `stats_15min`, `stats_hourly`, `stats_6h`, `stats_daily`. В них только `bytes_received` и `bytes_sent` (`migrations.py`, раздел 3), колонок скорости нет. Запросы подставляют константу:
|
||||||
|
|
||||||
|
- `get_client_history` (`APP_CORE/openvpn_api_v3.py`, ветка `is_aggregated`): `0 as bytes_received_rate_mbps`, `0 as bytes_sent_rate_mbps`.
|
||||||
|
- `get_analytics_data` (там же, для `7d` и `30d`): `0 as total_rx_rate, 0 as total_tx_rate`.
|
||||||
|
|
||||||
|
## 2. Решение (вариант 1: средняя скорость из байтов)
|
||||||
|
|
||||||
|
Средняя скорость корзины = `bytes * 8 / 1 000 000 / секунды_корзины`, та же формула, что у гатерера (`calculate_rates`). Схема БД, гатерер и данные не меняются, история работает задним числом.
|
||||||
|
|
||||||
|
| Таблица | Секунд в корзине |
|
||||||
|
|---|---|
|
||||||
|
| `stats_5min` | 300 |
|
||||||
|
| `stats_15min` | 900 |
|
||||||
|
| `stats_hourly` | 3600 |
|
||||||
|
| `stats_6h` | 21600 |
|
||||||
|
| `stats_daily` | 86400 |
|
||||||
|
|
||||||
|
Незавершённая (текущая) корзина: длительность берётся как `min(длина корзины, время с начала корзины)`, минимум 1 секунда, иначе скорость была бы занижена.
|
||||||
|
|
||||||
|
## 3. Шаги
|
||||||
|
|
||||||
|
1. `get_client_history`: словарь `{таблица: секунды}`; в ветке `is_aggregated` вместо нулей выражение средней скорости (в SQL, значения для обоих направлений).
|
||||||
|
2. `get_analytics_data`: то же для `stats_hourly` (суммирование по клиентам на одной отметке времени остаётся, затем `MAX` по интервалу группировки уже работает как для сырых данных).
|
||||||
|
3. UI: в режиме Speed для периодов больше 24 часов подписи серий «RX Mbps (avg)» и «TX Mbps (avg)» (`HistoryModal.vue`, `Analytics.vue`; логика подписи в общем коде графиков, если он есть). Остальное в UI не меняется.
|
||||||
|
4. Тест (минимальный, `APP_CORE`, pytest): запись в `stats_hourly` с известным объёмом, `get_client_history` с `resolution='hourly'` возвращает ожидаемый `bytes_*_rate_mbps` (полная корзина и текущая неполная).
|
||||||
|
5. Проверка на стенде `ovpmon-test`: перезапуск только `ovp-api` (образ пересобирается), запрос `/api/v1/stats/<client>?range=7d` и `/api/v1/analytics?range=7d` возвращает ненулевую скорость при ненулевом трафике; визуальная проверка графиков выполняется владельцем. Пересборка `deploy/ui-dist` (`build-ui.sh --publish`), пересоздание `ovp-ui`.
|
||||||
|
6. Сводка `2026-10-07_Aggregated_Speed.md`, строка в `DOCS/Changes/README.md`, обновление описания метрик и API в `DOCS/Core_Monitoring` и `README.md`, где описан режим Speed.
|
||||||
|
|
||||||
|
## 4. Тесты
|
||||||
|
|
||||||
|
Один тест из шага 4. Остальное: проверка запросом на стенде.
|
||||||
|
|
||||||
|
## 5. Риски
|
||||||
|
|
||||||
|
- Средняя скорость сглаживает кратковременные пики; на периодах больше суток это ожидаемо и обозначено подписью «avg».
|
||||||
|
- Для пиковых значений на больших периодах потребуется вариант 2 (колонки максимумов в агрегатах, миграция): вне этого изменения.
|
||||||
|
- Перезапуск `ovp-api` на стенде кратковременно прерывает API; гатерер и тома не трогаем, делается только с разрешения владельца (запрошено в рамках этого изменения при утверждении плана).
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Backup: выравнивание бейджей в таблице назначений (сводка, 2026-10-07)
|
||||||
|
|
||||||
|
План: [2026-10-07_Backup_Badges_Align_PLAN.md](2026-10-07_Backup_Badges_Align_PLAN.md)
|
||||||
|
|
||||||
|
## Что изменено
|
||||||
|
|
||||||
|
- `APP_UI/src/views/BackupRestore.vue`, таблица Destinations: у всех пяти ячеек строки (Name, Type, Status, Last result, Actions) добавлен класс Bootstrap `align-top` (вертикальное выравнивание по верху вместо центра). Верхний отступ ячеек общий (12px из `.table td`), поэтому бейджи, название и кнопки действий начинаются на одной линии. Дата в Last result осталась под бейджем. Заголовки (`thead`) не менялись.
|
||||||
|
- Общий `.status-badge`, `main.css` и другие страницы не менялись.
|
||||||
|
- `deploy/ui-dist` пересобран (`deploy/native/build-ui.sh --docker --publish`), `SOURCE_HASH` обновлён.
|
||||||
|
|
||||||
|
## Проверки
|
||||||
|
|
||||||
|
- Node 20 (контейнер `node:20-alpine`, на копии `APP_UI` вне дерева): `npm ci`, `npm run build`, `npm run lint` без ошибок; `npm test`: 13 тестов пройдено.
|
||||||
|
- `deploy/native/check-ui.sh`: `fresh`.
|
||||||
|
- Стенд (проект `ovpmon-test`): пересоздан только `ovp-ui` (порт 8089); `ovp-api`, `ovp-gatherer`, `ovp-profiler` не перезапускались. `ovp-ui` healthy, `curl -sI http://127.0.0.1:8089/` даёт 200 и заголовок CSP, в отданном бандле `BackupRestore-B3KsHsl0.js` класс `align-top` присутствует.
|
||||||
|
|
||||||
|
## Не проверено
|
||||||
|
|
||||||
|
- Визуальная проверка в браузере (`http://192.168.5.9:8089/`): остаётся владельцу. Возможное расхождение по высоте в 1-2 пикселя между текстом названия, бейджами и иконками кнопок из-за разной высоты строки не измерялось.
|
||||||
|
|
||||||
|
## Документация
|
||||||
|
|
||||||
|
`README.md` проекта не менялся: правка чисто визуальная.
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# Backup: выравнивание бейджей в таблице назначений (план, 2026-10-07)
|
||||||
|
|
||||||
|
Основание: на странице Backup and Restore в таблице Destinations бейджи «Enabled» (колонка Status) и «OK» (колонка Last result) стоят на разной высоте (скриншот владельца).
|
||||||
|
|
||||||
|
## 1. Причина
|
||||||
|
|
||||||
|
Ячейки таблицы выравниваются по вертикали по центру. В колонке Last result под бейджем есть вторая строка (дата), поэтому ячейка выше, а бейдж в ней поднят. В колонках Status и Type бейдж один и стоит по центру строки.
|
||||||
|
|
||||||
|
## 2. Решение
|
||||||
|
|
||||||
|
`APP_UI/src/views/BackupRestore.vue`, таблица назначений: ячейки с бейджами (Type, Status, Last result) выравниваются по верхнему краю (`align-top`), у остальных ячеек строки (Name, Actions) то же выравнивание и одинаковый верхний отступ, чтобы бейджи, название и кнопки действий стояли на одной линии. Дату в Last result оставить под бейджем. Других страниц и общего стиля `.status-badge` не меняем.
|
||||||
|
|
||||||
|
## 3. Шаги
|
||||||
|
|
||||||
|
1. Правка разметки (при необходимости небольшой локальный класс в `main.css`).
|
||||||
|
2. Проверка: `npm run build` и `npm run lint` в Node 20 (контейнер `node:20-alpine`), пересборка `deploy/ui-dist` (`deploy/native/build-ui.sh --publish`, иначе `check-ui.sh` покажет `stale`), пересоздание только `ovp-ui` на стенде.
|
||||||
|
3. Скриншот или проверка владельцем: в среде нет браузера, поэтому визуальную проверку выполняет владелец на `http://192.168.5.9:8089/`.
|
||||||
|
4. Сводка `2026-10-07_Backup_Badges_Align.md`, строка в `DOCS/Changes/README.md`; в `README.md` изменений нет (чисто визуальная правка), это указать в сводке.
|
||||||
|
|
||||||
|
## 4. Тесты
|
||||||
|
|
||||||
|
Автотесты не нужны (вёрстка).
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# Резервное копирование и восстановление: сводка, проход 1 из 3 (2026-10-07)
|
||||||
|
|
||||||
|
План: [2026-10-07_Backup_Restore_PLAN.md](2026-10-07_Backup_Restore_PLAN.md). Руководство: [Backup and Restore](../Profiler_Management/Backup_Restore.md).
|
||||||
|
|
||||||
|
Проход 1 по плану: формат пакета, шифрование, безопасная распаковка, хранилище настроек, назначения **Local и S3 (`minio`)**, все маршруты API, движок восстановления, весь UI. FTP, SFTP, SMB, расписание: позже.
|
||||||
|
|
||||||
|
## Что сделано
|
||||||
|
|
||||||
|
**Backend (`APP_PROFILER`)**
|
||||||
|
- `services/backup/package.py`: имя пакета и разбор регулярным выражением; онлайн-снимок обеих БД (`Connection.backup`, одиночный файл без `-wal`); сборка tar.gz с `manifest.json` (формат, версии схем, SHA-256, среда, хост); безопасная распаковка (белый список верхних имён, отказ для абсолютных путей, `..`, ссылок, устройств, дублей, лимиты размера и числа записей); сверка манифеста с содержимым.
|
||||||
|
- `services/backup/crypto.py`: AES-256-GCM по блокам 1 МиБ, ключ из фразы через scrypt (N=2^15), заголовок с солью и параметрами, заголовок и признак последнего блока входят в AAD (обрезка и подмена обнаруживаются); границы параметров из заголовка.
|
||||||
|
- `services/backup/destinations.py`: общий интерфейс `test/put/list/get/delete`, реестр типов (расширение для ftp/sftp/smb: новый класс и запись в `DESTINATION_TYPES`; API принимает только реализованные типы). `local`: подпапка внутри `OVPMON_BACKUP_LOCAL_ROOT`, отказ при выходе из корня и символических ссылках, запись через временный файл. `s3`: библиотека `minio`, endpoint/TLS/регион/bucket/prefix/ключи, проверка форматов, таймауты.
|
||||||
|
- `services/backup/store.py`: отдельный файл `ovpmon_backup.db` рядом с БД профилировщика (настройки, назначения, история, таблица версии схемы, создаётся при старте); секреты назначений и парольная фраза шифруются Fernet-ключом из HKDF от ключа JWT, API отдаёт маску.
|
||||||
|
- `services/backup/engine.py`: одна фоновая задача на сервис (409 иначе), этапы и результат по каждому назначению, сбой одного назначения не останавливает остальные; ротация по `retention_count` (только пакеты нашего шаблона **этого хоста**); восстановление по п. 4 плана; история.
|
||||||
|
- `routers/backup.py`: маршруты п. 5 плана, все под `verify_token`; `utils/guards.py` и `pki.set_restore_running`: во время восстановления изменяющие PKI, профили, настройки и процесс OpenVPN запросы получают 409.
|
||||||
|
- `main.py`: создание хранилища при старте (сбой не останавливает управление VPN), регистрация роутера.
|
||||||
|
|
||||||
|
**Миграции монитора при восстановлении (решение).** Миграции БД мониторинга живут в `APP_CORE`, из процесса профилировщика их импортировать нельзя (отдельные venv, в образе профилировщика варианта B `APP_CORE` нет). Выбрано: миграции запускаются **на распакованных копиях до замены** (профилировщик: `migrations.run` в процессе; монитор: `python migrate.py --db <копия>` из каталога `APP_CORE`, найденного рядом с `APP_PROFILER` или по `OVPMON_CORE_DIR`, интерпретатор из `APP_CORE/venv`, иначе текущий). Так в рабочую систему попадает уже мигрированная БД, а при ошибке ничего не меняется. Если код миграций недоступен, пакет принимается только при **равной** версии схемы монитора, иначе отказ с понятным сообщением (в образе профилировщика варианта B код миграций добавлен позже: см. [Fixes](2026-10-07_Backup_Restore_Fixes.md), R3). Причина: Core применяет миграции только при своём старте, а восстановление его не перезапускает.
|
||||||
|
|
||||||
|
**UI (`APP_UI`)**: `views/BackupRestore.vue`, маршрут `/backup`, пункт Backup and Restore в MANAGEMENT; таблица назначений и модальное окно (поля типов приходят из `GET /backup/settings`), панель Backup (статус шифрования, флажки, Backup now, прогресс по назначениям, история), панель Restore (источник, автопроверка, пакеты новые сверху, фраза, красная кнопка, подтверждение с перечнем последствий, прогресс, вход заново); опрос статуса раз в 2 с. Небольшой блок стилей в `main.css`; `ConfirmModal` понимает переводы строк. Собранный UI `deploy/ui-dist` обновлён через `build-ui.sh --docker --publish`, `check-ui.sh`: актуален.
|
||||||
|
|
||||||
|
**Развёртывание**: `cryptography` и `minio` в `requirements.txt`; том `ovp_backups` на `/app/backups` и `OVPMON_BACKUP_LOCAL_ROOT=/app/backups` в обоих compose-файлах (в `deploy/docker/lib.sh` `VOLUMES` не менялся); каталог в образах. Системные службы: unit systemd разрешает запись в `/var/lib/ovpmon`, каталог `backups` создаётся службой, установщик не менялся.
|
||||||
|
|
||||||
|
**Документация**: `Profiler_Management/Backup_Restore.md`, `Profiler_Management/API_Reference.md`, `UI/Architecture.md`, `General/Overview.md`, `General/Configuration.md`, `Deployment/Containers/Reference.md`, `Deployment/System_Services/Reference.md`, `README.md`, `DOCS/README.md`, `DOCS/Changes/README.md`.
|
||||||
|
|
||||||
|
## Проверено
|
||||||
|
|
||||||
|
- Автотесты `APP_PROFILER/test_backup.py` (5 шт., без сети и без S3): круг пакета с шифрованием и неверной фразой; безопасная распаковка (`../`, абсолютный путь, ссылка, чужое имя, лишний файл в `db/`), пакет с более новой схемой и неизвестным форматом; два назначения (рабочее Local и падающая заглушка), результат по каждому, ротация, восстановление через движок с проверкой PKI, профилей и БД, страховочная копия; API: все маршруты без JWT дают 401, секреты замаскированы и зашифрованы в файле, тип ftp отклонён, удалённое назначение без фразы даёт 400. Весь `pytest` в `APP_PROFILER`: 20 пройдено, 2 прежних падения (`test_get_stats`, `test_control_invalid`, 404), не связаны с изменением.
|
||||||
|
- Запуск `migrate.py` из `APP_CORE` на копии БД со схемой 1: 1 -> 2.
|
||||||
|
- Драйвер S3: проверка форматов, создание клиента `minio`; сетевых вызовов не было.
|
||||||
|
- `docker compose config` обоих файлов; сборка UI (Vite, Node 20 в контейнере) без ошибок.
|
||||||
|
|
||||||
|
## Не проверено, открытые вопросы
|
||||||
|
|
||||||
|
- S3 на реальном бакете (проверит владелец); права ключа: list, put, get, delete.
|
||||||
|
- Ручной круг на стенде (копия, повреждение, восстановление, перенос между чистыми окружениями) и работа в системных службах через root-помощник.
|
||||||
|
- UI не просматривался в браузере (светлая и тёмная темы): только сборка.
|
||||||
|
- Образы с новыми зависимостями не собирались; сборка `cryptography` и `minio` на Alpine (musl) не проверена.
|
||||||
|
- Восстановление не перезапускает Core: файл БД монитора заменяется на месте, соединения открываются на каждую операцию; процесс, державший открытое соединение в момент замены, увидит новую БД при следующем обращении.
|
||||||
|
- Состояние задачи в памяти (один процесс профилировщика); прерванная перезапуском задача помечается `interrupted` в истории при старте.
|
||||||
|
- Смена ключа JWT делает сохранённые секреты нечитаемыми: их нужно ввести заново (в UI показывается ошибка при проверке).
|
||||||
|
- `General/Security_Architecture.md` (п. 11 плана) не обновлялся: файл описывает план аутентификации; описание рисков копий дано в руководстве.
|
||||||
|
|
||||||
|
## Отклонения от плана
|
||||||
|
|
||||||
|
- Миграции восстановленных БД выполняются **до** замены, на распакованных копиях, а не после (безопаснее: рабочая система не получает немигрированную БД).
|
||||||
|
- Для БД монитора без кода миграций принимаются только пакеты с равной схемой (в варианте B снято в проходе исправлений, R3).
|
||||||
|
- Ротация затрагивает только пакеты **своего хоста** (общий bucket нескольких серверов).
|
||||||
|
- Страховочные копии `pre-restore` лежат в отдельной папке `<корень>/pre-restore/` (последние 5), а не в выбранном назначении.
|
||||||
|
- Содержимое каталогов `pki/` и `client-config/` заменяется поэлементно (сам каталог может быть точкой монтирования тома), с откатом.
|
||||||
|
- Тестов пять вместо 3-4: добавлен тест восстановления через движок.
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# Резервное копирование: замечания и недостающие назначения, сводка (2026-10-07)
|
||||||
|
|
||||||
|
План: [2026-10-07_Backup_Restore_Fixes_PLAN.md](2026-10-07_Backup_Restore_Fixes_PLAN.md). Основа: [сводка прохода 1](2026-10-07_Backup_Restore.md). Руководство: [Backup and Restore](../Profiler_Management/Backup_Restore.md).
|
||||||
|
|
||||||
|
В этом проходе реализованы R1, R2, R3, R6, R7. R4 (варианты установки) и R5 (браузер) выполняют ассистент и владелец.
|
||||||
|
|
||||||
|
## Статус по пунктам
|
||||||
|
|
||||||
|
| ID | Статус | Что сделано |
|
||||||
|
|---|---|---|
|
||||||
|
| R1 | сделано | Имя сервера и время в имени пакета |
|
||||||
|
| R2 | сделано в коде и тесте; **восстановление на реальном стеке проверит ассистент** | Ограничение частоты сообщений gatherer |
|
||||||
|
| R3 | сделано в коде и документации; **реальную сборку образа проверит ассистент** | Код миграций монитора в образе профилировщика |
|
||||||
|
| R6 | сделано | Раздел Backups в `General/Security_Architecture.md` |
|
||||||
|
| R7 | сделано в коде, UI и тесте с подменой клиента; **на реальных серверах SFTP, FTP, FTPS проверит ассистент** | Назначения SFTP и FTP/FTPS |
|
||||||
|
|
||||||
|
## R1: имя сервера и время
|
||||||
|
|
||||||
|
- Настройка `server_name` хранится в `ovpmon_backup.db` (не в `ovpn_profiler.db`), проверка `^[A-Za-z0-9][A-Za-z0-9.-]{0,62}$`; `GET/PUT /backup/settings` отдают `server_name`, `effective_server_name` и `server_name_source` (`setting`, `public_ip`, `hostname`). Цепочка: настройка, затем `public_ip` из `system_settings` БД профилировщика (чтение только на чтение, пусто или нет таблицы: пропускается), затем очищенный hostname.
|
||||||
|
- Имя пакета: `ovpmon-backup_<имя>_<YYYYMMDDTHHMMSS>Z.ovpbak[.enc]`; при совпадении секунды в назначении добавляется `-2`, `-3` после `Z` (имена существующих файлов проверяются по списку назначения, перезаписи нет). Регулярное выражение имени обратно совместимо: пакеты прохода 1 с hostname видны и восстанавливаются.
|
||||||
|
- `manifest.json`: `server_name`, `hostname`, `created_at` с миллисекундами UTC.
|
||||||
|
- Ротация считает пакеты с тем же именем сервера в той же папке, порядок по (время, суффикс). Пакеты с другим именем (в том числе старые по hostname) не ротируются.
|
||||||
|
- Список пакетов отдаёт `server_name` вместо `host` (потребитель один, UI), сортировка по времени и суффиксу.
|
||||||
|
- UI: поле Server name в панели Backup с показом фактически используемого имени и источника; в списке пакетов Restore имя сервера, время в UTC и в местном времени браузера; то же в окне подтверждения.
|
||||||
|
|
||||||
|
## R2: журнал gatherer
|
||||||
|
|
||||||
|
`run_monitoring_cycle`: сообщение о пропуске тика пишется на 1-м тике, на пороге `status_invalid_max` (ERROR) и далее на каждом 60-м; при возврате файла один раз INFO `Status file is readable again after N skipped ticks`. Поведение БД и кэша без изменений. Тест `test_missing_status_file_logs_sparingly_and_reports_recovery` (125 тиков без файла: сообщения на 1, 6, 60, 120; восстановление: одна строка INFO). Тесты `APP_CORE`: 17 пройдено.
|
||||||
|
|
||||||
|
**К проверке ассистентом на стенде:** чистый стек, восстановление пакета, запуск OpenVPN, по журналу gatherer убедиться, что он перешёл к обычной работе и сессии появились.
|
||||||
|
|
||||||
|
## R3: миграции монитора в образе профилировщика
|
||||||
|
|
||||||
|
**Проверка до применения.** `APP_CORE/migrations.py` использует только стандартную библиотеку. `APP_CORE/migrate.py` импортирует `migrations` и `db`; `db.py` тоже только стандартная библиотека (`sqlite3`, `configparser`, `os`, `logging`, `migrations`). Сторонних пакетов нет, пункт применён.
|
||||||
|
|
||||||
|
**Отклонение от плана:** кроме `migrations.py` и `migrate.py` в образ копируется и **`db.py`** (`COPY --from=core migrations.py migrate.py db.py /opt/core/`): `migrate.py` импортирует его при запуске (без файла запуск падает с `ModuleNotFoundError`, проверено). Запуск как в движке (`python migrate.py --db <копия>`, cwd = каталог с файлами) проверен на копии БД: 0 -> 2.
|
||||||
|
|
||||||
|
- `APP_PROFILER/Dockerfile`: `COPY --from=core ...`, `ENV OVPMON_CORE_DIR=/opt/core`. `docker-compose.yml`: у `app-profiler` `build.context: ./APP_PROFILER` и `additional_contexts: core: ./APP_CORE`. `docker compose config` обоих файлов разбирается; `docker-compose.allinone.yml` не менялся.
|
||||||
|
- `engine.core_dir()` требует три файла (`migrate.py`, `migrations.py`, `db.py`); при найденном каталоге пакеты с более старой схемой монитора мигрируются, отказ по несовпадению схем остаётся только для старого образа без каталога (сообщение предлагает пересобрать образ).
|
||||||
|
- Требование docker compose 2.17+ записано в `DOCS/Deployment/Containers/README.md` (требования) и `Reference.md`. Проверки версии compose в `deploy/docker/lib.sh` нет (проверяется только наличие `docker compose` или `docker-compose`), поэтому предупреждение в скрипты не добавлялось.
|
||||||
|
- Оговорка про вариант B убрана из `Backup_Restore.md` и из сводки прохода 1.
|
||||||
|
|
||||||
|
**К проверке ассистентом:** реальная сборка образа профилировщика (Alpine) и восстановление пакета со схемой монитора v1 в стек с v2.
|
||||||
|
|
||||||
|
## R6: документация
|
||||||
|
|
||||||
|
`General/Security_Architecture.md`: раздел «Backups» перед «Verification Plan» (состав пакета, шифрование, секреты назначений, закрепление отпечатка SFTP, права каталогов, восстановление как граница доверия, ограничения). Остальной текст файла не менялся.
|
||||||
|
|
||||||
|
## R7: SFTP и FTP
|
||||||
|
|
||||||
|
- `services/backup/destinations.py`: классы `SFTPDestination` (`paramiko`) и `FTPDestination` (`ftplib`), метаданные `FIELDS` (новые виды `number` и `secret_multiline`, поля `warning` + `warn_if`), регистрация в `DESTINATION_TYPES` (удалённые типы требуют парольную фразу автоматически).
|
||||||
|
- **SFTP:** пароль или закрытый ключ (RSA, ECDSA, Ed25519; фраза ключа); пароль и ключ одновременно, без обоих, нечитаемый ключ отклоняются при сохранении. Политика ключей хоста `MissingHostKeyPolicy` принимает только закреплённый отпечаток SHA-256 (известные ключи не загружаются, AutoAdd нет); проверка происходит до отправки учётных данных. Незакреплённый узел: `test` возвращает `needs_trust`, `fingerprint`, `key_type`; `put/list/get/delete` отказывают без подключения; несовпадение: отказ (Test предлагает новый отпечаток с флагом `key_changed`). Закрепление: `POST /backup/destinations/{id}/trust-host-key` (сервер заново подключается и принимает ключ, только если он совпадает с показанным). `host_key` и `host_key_type` приходят только из этого вызова, клиентские значения отбрасываются, при правке без смены host и port закрепление сохраняется, при смене сбрасывается.
|
||||||
|
- **FTP:** `FTP_TLS` (explicit FTPS) по умолчанию, проверка сертификата по умолчанию (явное отключение), пассивный режим по умолчанию, обычный FTP допустим (предупреждение в форме, бейдж в списке и текст результата Test).
|
||||||
|
- **Оба:** загрузка во `.<имя>.part` и переименование; список только по регулярному выражению имени пакета; каталог относительный (как у Local, ведущий `/` отвергается), до 4 уровней, создаётся при записи; таймаут соединения 15 с, передачи 120 с; ошибки текстом без секретов; секреты шифруются и маскируются как у S3.
|
||||||
|
- `requirements.txt`: добавлен `paramiko`. (`cryptography` и `minio` добавлены проходом 1; в `git diff` относительно последнего коммита видны все три.)
|
||||||
|
- UI: типы SFTP и FTP в выборе, форма из `FIELDS` (число, многострочный секрет, предупреждения), показ закреплённого ключа, окно с отпечатком и кнопкой Trust после Test (при смене ключа предупреждение и красная кнопка), бейджи в таблице. Сборка `deploy/ui-dist`: `deploy/native/build-ui.sh --docker --publish`, `check-ui.sh`: актуален.
|
||||||
|
- Документация: `Backup_Restore.md`, `API_Reference.md`, `UI/Architecture.md`, `Core_Monitoring/Data_Architecture.md`, `DOCS/Changes/README.md`, `README.md`, `DOCS/README.md`.
|
||||||
|
|
||||||
|
**К проверке ассистентом на тестовых серверах** (`atmoz/sftp`, `vsftpd`/`pure-ftpd` с TLS и без): тест, копия, список, восстановление, ротация, одновременная запись в 3-4 назначения и сбой одного. Не проверялось: реальная работа `paramiko` и `ftplib` по сети (только подмена клиента), перенос данных через TLS 1.3 у `ftplib` (`unwrap` после загрузки у части серверов), `MLSD`/`NLST` у конкретных серверов, сборка `paramiko` (`cryptography`, `bcrypt`, `pynacl`) на Alpine.
|
||||||
|
|
||||||
|
## Тесты
|
||||||
|
|
||||||
|
Новые: 3 (`test_backup.py`: имя пакета, цепочка имён, уникальность, ротация по имени; SFTP/FTP параметры, закрепление и отказы с подменой клиента; `test_gatherer.py`: частота сообщений и восстановление). В существующем тесте API заменён «неподдерживаемый тип» `ftp` на `smb` (ftp теперь реализован). `pytest APP_PROFILER`: 22 пройдено, 2 прежних падения в `test_server_process.py` (`test_get_stats`, `test_control_invalid`) не тронуты. `pytest APP_CORE`: 17 пройдено.
|
||||||
|
|
||||||
|
## Результаты проверки на стендах (ассистент, 2026-10-07)
|
||||||
|
|
||||||
|
| Пункт | Результат |
|
||||||
|
|---|---|
|
||||||
|
| R1 имя и время | Имя `ovpn-stand` из настроек, формат `ovpmon-backup_ovpn-stand_20261007T061132Z.ovpbak.enc`; без имени берётся `public_ip`, затем `hostname`. |
|
||||||
|
| R2 журнал gatherer | Чистый стек: сообщения на 1-м и 6-м тике (ERROR), затем редко; после запуска OpenVPN запись `Status file is readable again after 7 skipped ticks`, сессии пошли. |
|
||||||
|
| R3 миграции в образе B | Образ профилировщика собран на Alpine, `/opt/core` с `migrate.py`, `migrations.py`, `db.py`. Пакет со схемой мониторинга v1 восстановлен в стек B, схема стала v2 (колонка `session_id` есть), gatherer работает. |
|
||||||
|
| R4 вариант A | Отдельный проект и порты: копия в Local, перенос пакета из стенда B по SFTP, вход прежним администратором, профили и `ca.crt` совпали, OpenVPN запустился, процессы supervisor работают. |
|
||||||
|
| R4 системные службы | Одноразовый контейнер Debian 12 с systemd: `install.sh` отработал, зависимости (`minio`, `paramiko`, `cryptography`) поставлены; копия в Local; восстановление пакета из стенда B по SFTP; владельцы и права (`ovpmon`, 600/700) верны; `server.conf` установлен помощником; OpenVPN запущен через помощник (`openvpn-server@server`); `ca.crt` совпал; схема БД мониторинга 2. |
|
||||||
|
| R7 SFTP | `atmoz/sftp`: отпечаток показан и совпал с `ssh-keygen -lf`; неверный отпечаток отклонён; без закрепления операции отклоняются; копия, список, восстановление, ротация (лимит 2: удалён старый) работают. |
|
||||||
|
| R7 FTP/FTPS | `pure-ftpd` с самоподписанным сертификатом: проверка сертификата отклоняет подключение с понятным текстом; без проверки FTPS работает (загрузка, список, восстановление, TLS 1.3 у `ftplib` без проблем); обычный FTP работает с предупреждением. |
|
||||||
|
| Несколько назначений | Одновременная запись в Local + SFTP + FTP: 3 из 3; при остановленном FTP: 2 из 3, у FTP «Host name cannot be resolved», остальные не затронуты. |
|
||||||
|
| R6 | Раздел «Backups» добавлен в `Security_Architecture.md`. |
|
||||||
|
|
||||||
|
Тестовые серверы, клоны и одноразовый контейнер удалены вместе с их томами и файлами секретов.
|
||||||
|
|
||||||
|
## Не проверено
|
||||||
|
|
||||||
|
- Страница в браузере (R5, владелец): светлая и тёмная темы, форма SFTP/FTP, окно Trust.
|
||||||
|
- Вход в SFTP по закрытому ключу (только подмена клиента), реальное изменение ключа хоста (`key_changed`), PKCS8-ключи Ed25519.
|
||||||
|
- Системные службы на Alpine (OpenRC); на Debian проверено в контейнере, а не на отдельной машине.
|
||||||
|
- Обратный перенос A или служб в контейнеры стенда B.
|
||||||
|
- S3: владелец проверил копирование в бакет (успешно, 2026-10-07); восстановление из S3 и ротация в S3 не подтверждены.
|
||||||
|
- SMB (вне плана, в очереди).
|
||||||
|
|
||||||
|
## Отклонения от плана
|
||||||
|
|
||||||
|
- В образ профилировщика копируется ещё и `db.py` (R3).
|
||||||
|
- В списке пакетов поле `host` переименовано в `server_name`.
|
||||||
|
- Каталог SFTP/FTP с ведущим `/` отвергается (у Local он молча нормализуется).
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
# Резервное копирование: замечания и недостающие назначения (план, 2026-10-07)
|
||||||
|
|
||||||
|
Основание: проверка первого прохода ([сводка](2026-10-07_Backup_Restore.md), [исходный план](2026-10-07_Backup_Restore_PLAN.md)) и проверка владельца в браузере: в настройке назначения доступны только локальная папка и S3, **SFTP и FTP из исходного требования отсутствуют**.
|
||||||
|
|
||||||
|
Вне этого плана: S3 (ждём бакет владельца), SMB (проход 3 исходного плана, остаётся в очереди), проверка страницы в браузере (выполняет владелец).
|
||||||
|
|
||||||
|
## 1. Список
|
||||||
|
|
||||||
|
| ID | Замечание | Решение |
|
||||||
|
|---|---|---|
|
||||||
|
| R1 | В имени пакета стоит `hostname`; в контейнере это случайный идентификатор | Имя пакета строится из **имени сервера из настроек** и точного времени (п. 2) |
|
||||||
|
| R2 | Gatherer на свежей или восстановленной установке пишет ERROR каждые 10 с, пока OpenVPN не запущен; восстановление после появления файла статуса не подтверждено | Ограничить частоту сообщений, писать о восстановлении, проверить на стенде (п. 3) |
|
||||||
|
| R3 | Вариант B: профилировщик не может мигрировать БД мониторинга из пакета с другой версией схемы (в образе нет кода `APP_CORE`), восстановление отказывает | Положить `migrations.py` и `migrate.py` из `APP_CORE` в образ профилировщика (п. 4) |
|
||||||
|
| R4 | Не проверено: вариант A (всё в одном контейнере), системные службы с root-помощником | Проверка по сценариям п. 6 |
|
||||||
|
| R6 | `General/Security_Architecture.md` не описывает резервные копии | Короткий раздел (п. 8) |
|
||||||
|
| R7 | Нет назначений **SFTP** и **FTP** | Реализовать (п. 5) |
|
||||||
|
|
||||||
|
(R5, проверка в браузере, выполняется владельцем и в план не входит.)
|
||||||
|
|
||||||
|
## 2. R1: имя сервера и время в имени пакета
|
||||||
|
|
||||||
|
В настройках **нет** поля «имя сервера» (есть только `public_ip`), поэтому:
|
||||||
|
|
||||||
|
- В настройки резервного копирования (**не** в `ovpn_profiler.db`, которая заменяется при восстановлении) добавляется поле **Server name**: `^[A-Za-z0-9][A-Za-z0-9.-]{0,62}$`, хранится в `ovpmon_backup.db`; API `GET/PUT /backup/settings` (`server_name`), поле на странице Backup and Restore. После переноса на новый сервер имя задаётся заново, оно не приезжает из пакета.
|
||||||
|
- Если имя не задано: `public_ip` из настроек VPN (если есть), иначе `hostname`. UI показывает, какое имя будет использовано.
|
||||||
|
- Формат: `ovpmon-backup_<server-name>_<YYYYMMDDTHHMMSS>Z.ovpbak[.enc]`: время UTC, до секунды, суффикс `Z`. При совпадении имени (две копии в одну секунду) добавляется `-2`, `-3`, файл не перезаписывается.
|
||||||
|
- В `manifest.json`: `server_name`, `hostname` (как сейчас), `created_at` с миллисекундами в UTC.
|
||||||
|
- Список пакетов в UI: имя сервера, время **в UTC и в локальном времени браузера**, размер, шифрование; сортировка по времени.
|
||||||
|
- Старые пакеты с прежним форматом имени остаются видимыми и восстанавливаются.
|
||||||
|
- Ротация считает пакеты с тем же именем сервера в одной папке; пакеты со старым `hostname` в ротации не участвуют (указать в документации). Серверы с одним именем в одной папке ротируют друг друга: имена задаёт владелец.
|
||||||
|
|
||||||
|
## 3. R2: журнал gatherer
|
||||||
|
|
||||||
|
- В `run_monitoring_cycle`: сообщение о пропуске тика пишется на 1-м тике, на пороге `status_invalid_max` (ERROR) и далее раз в 60 тиков (около 10 минут при интервале 10 с); при возврате файла один раз INFO «status file is readable again after N skipped ticks».
|
||||||
|
- Состояние БД и кэша при пропуске не меняется, как сейчас.
|
||||||
|
- Проверка: тест на счётчик сообщений; на стенде: чистый стек, восстановление пакета, запуск OpenVPN, по журналу gatherer убедиться, что он перешёл к обычной работе и сессии появились.
|
||||||
|
|
||||||
|
## 4. R3: миграции мониторинга в образе профилировщика
|
||||||
|
|
||||||
|
- `docker-compose.yml`: `additional_contexts: core: ./APP_CORE` для `app-profiler`; `APP_PROFILER/Dockerfile`: `COPY --from=core migrations.py migrate.py /opt/core/`, переменная `OVPMON_CORE_DIR=/opt/core`. Контекст сборки профилировщика не меняется. Для `deploy/allinone` изменений нет (там `APP_CORE` уже есть).
|
||||||
|
- Сначала проверить, что `APP_CORE/migrations.py` и `migrate.py` используют только стандартную библиотеку; если нет, пункт отменяется, остаётся прежнее ограничение (отказ при другой версии схемы), документировать.
|
||||||
|
- Убрать из `Backup_Restore.md` и сводки оговорку о варианте B; проверить восстановление пакета со схемой мониторинга v1 в стек с v2. Поддержка `additional_contexts` в `docker compose` хоста: нужна версия 2.17+ (на хосте 2.38); в документации указать требование.
|
||||||
|
|
||||||
|
## 5. R7: назначения SFTP и FTP
|
||||||
|
|
||||||
|
Те же интерфейс (`test`, `put`, `list`, `get`, `delete`), шифрование секретов, правила и ротация, что у Local и S3. Параметры описываются в `FIELDS` назначения, форма в UI строится из них (добавить вид поля «многострочный секрет» для закрытого ключа).
|
||||||
|
|
||||||
|
| | SFTP (`paramiko`) | FTP (`ftplib`) |
|
||||||
|
|---|---|---|
|
||||||
|
| Параметры | хост, порт (22), пользователь, каталог | хост, порт (21), пользователь, каталог, пассивный режим (вкл), **TLS (explicit FTPS), по умолчанию вкл**, проверка сертификата (вкл) |
|
||||||
|
| Секреты | пароль **или** закрытый ключ (+ его парольная фраза) | пароль |
|
||||||
|
| Проверка узла | **отпечаток ключа хоста (SHA-256) закрепляется**: первая проверка показывает отпечаток, администратор подтверждает кнопкой «Trust», он сохраняется в параметрах; при несовпадении подключение отклоняется. Копирование, список, восстановление без закреплённого отпечатка запрещены | при TLS проверяется сертификат; отключение проверки (самоподписанный) допускается явно, в UI предупреждение; без TLS в UI предупреждение, что пароль идёт открытым текстом |
|
||||||
|
| Запись | загрузка во временное имя `.part`, затем переименование | то же |
|
||||||
|
| Список | только файлы нашего формата имени | то же |
|
||||||
|
|
||||||
|
- Удалённые назначения требуют парольную фразу пакета (правило плана остаётся), а значит и SFTP, и FTP.
|
||||||
|
- Каталог проверяется как для Local (относительный, без `..`); имена файлов формируются только приложением.
|
||||||
|
- Таймауты подключения и передачи ограничены; ошибки возвращаются понятным текстом без секретов.
|
||||||
|
- Зависимость `paramiko` в `requirements.txt`; сборка образа на Alpine проверяется (зависит от `cryptography`, `bcrypt`, `pynacl`).
|
||||||
|
- Проверка на стенде тестовыми серверами в контейнерах в сети стенда: SFTP (`atmoz/sftp`), FTP и FTPS (`vsftpd` или `pure-ftpd`). Локальный S3 по-прежнему не поднимается. Круг на каждом: тест, копия, список в Restore, восстановление, ротация, одновременная запись в 3-4 назначения (Local + SFTP + FTP + при желании ещё одно) и сбой одного из них. Тестовые серверы и тома удаляются после проверки.
|
||||||
|
|
||||||
|
## 6. R4: проверки вариантов установки
|
||||||
|
|
||||||
|
**Вариант A (all-in-one).** Отдельный проект и порты (`ovp-allinone` не конфликтует с `ovp-*`), собрать образ, настроить локальное назначение (и SFTP/FTP), сделать копию, изменить данные, восстановить; затем **перенос пакета из стенда варианта B в A** и обратно. Проект удалить по окончании.
|
||||||
|
|
||||||
|
**Системные службы (root-помощник).** Устанавливать на этот хост нельзя (Debian, рабочие службы). Используется одноразовый **контейнер Debian 12 с systemd** (privileged, удаляется после проверки), в нём `deploy/native/install.sh`. Проверяем: установку новых зависимостей установщиком и `update.sh`; права `ovpmon` на `/var/lib/ovpmon/backups`; песочницу юнитов (`ReadWritePaths`); замену БД и каталогов под `ovpmon`; миграцию БД мониторинга через `APP_CORE/venv`; создание `server.conf`, публикацию CRL и перезапуск OpenVPN через помощник; перенос пакета из контейнерного стека в службы. Если контейнер с systemd не заработает, проверка сводится к разбору кода и юнитов, и это явно записывается в сводку как непроверенное.
|
||||||
|
|
||||||
|
## 7. Тесты
|
||||||
|
|
||||||
|
Не более 3 новых или изменённых автотестов: формат имени пакета и порядок выбора имени (настройка → `public_ip` → `hostname`) с уникальностью; ограничение частоты сообщений gatherer; проверка параметров SFTP/FTP и закрепления отпечатка (без сети, с подменой клиента). Всё остальное проверяется на стендах.
|
||||||
|
|
||||||
|
## 8. Документация (R6 и сопутствующая)
|
||||||
|
|
||||||
|
Раздел «Backups» в `General/Security_Architecture.md` (что в пакете, шифрование, секреты назначений, закрепление отпечатка SFTP, права каталогов, границы доверия); обновление `Profiler_Management/Backup_Restore.md` (SFTP, FTP, имя сервера, формат имени, ротация, вариант B), `API_Reference.md`, `UI/Architecture.md`, `Deployment/*/Reference.md` при необходимости, таблица в `Changes/README.md`, сводка `2026-10-07_Backup_Restore_Fixes.md`.
|
||||||
|
|
||||||
|
## 9. Решения по умолчанию (владелец поручил взять остальное в работу)
|
||||||
|
|
||||||
|
- Имя сервера задаётся в разделе Backup and Restore (не общим полем VPN-настроек).
|
||||||
|
- Системные службы проверяются в одноразовом контейнере Debian 12 с systemd.
|
||||||
|
|
||||||
|
## 10. Порядок
|
||||||
|
|
||||||
|
1. План утверждён владельцем (2026-10-07).
|
||||||
|
2. Реализация субагентом (Sonnet 5.5, Medium Effort): R1, R2, R3, R6, R7 (код, тесты, документация).
|
||||||
|
3. Проверки R2, R3, R4, R7 на стендах ассистентом, результаты в сводку; страницу в браузере проверяет владелец.
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
# Резервное копирование и восстановление (план, 2026-10-07)
|
||||||
|
|
||||||
|
Цель: создавать пакеты резервных копий и восстанавливать из них, в том числе **на другом сервере** (другая физическая или виртуальная машина, контейнеры; из контейнеров в системные службы и обратно). Управление есть в API и в UI: в разделе **Management** появляется пункт **Backup and Restore**.
|
||||||
|
|
||||||
|
Не путать с `deploy/docker/backup.sh` и `update.sh`: они копируют тома Docker целиком перед обновлением и работают только из командной строки. Новая функция работает из UI/API на уровне данных приложения и не зависит от способа установки.
|
||||||
|
|
||||||
|
## 1. Что входит в пакет
|
||||||
|
|
||||||
|
| Содержимое | Источник | Почему |
|
||||||
|
|---|---|---|
|
||||||
|
| `db/openvpn_monitor.db` | мониторинг: статистика, учётные записи, 2FA | консистентный снимок через онлайн-копию SQLite (`Connection.backup`), остановка не нужна |
|
||||||
|
| `db/ovpn_profiler.db` | профили, настройки сервера и PKI | то же |
|
||||||
|
| `pki/` (каталог `easy-rsa/pki`) | CA, ключи и сертификаты, CRL, `ta.key`, `dh.pem` | **секретные данные** |
|
||||||
|
| `client-config/*.ovpn` | выданные профили | пути в базе относительные, совпадают во всех вариантах установки |
|
||||||
|
| `manifest.json` | версия формата, время, хост, среда (`container`/`host`), версии схем БД, SHA-256 каждого файла, число профилей | проверка до восстановления |
|
||||||
|
|
||||||
|
Не входит (специально): `server.conf` (создаётся заново из настроек), `/etc/ovpmon/env` и `JWT_SECRET` (свои на каждом сервере), TLS-сертификат веб-интерфейса, логи, настройки назначений резервного копирования (см. п. 3), `ipp.txt`.
|
||||||
|
|
||||||
|
Имя пакета: `ovpmon-backup_<host>_<YYYYMMDDTHHMMSSZ>.ovpbak` (tar.gz); при шифровании добавляется `.enc`. Имя разбирается регулярным выражением, всё остальное в назначении игнорируется.
|
||||||
|
|
||||||
|
**Шифрование.** Пакет содержит закрытый ключ CA и хеши паролей. Опциональная парольная фраза в настройках: AES-256-GCM по блокам, ключ из фразы через scrypt, соль и параметры в заголовке (библиотека `cryptography`). Правило: **без фразы резервное копирование на удалённые назначения запрещено** (400), в локальную папку разрешено с предупреждением в UI. Фраза не возвращается API; при восстановлении вводится вручную.
|
||||||
|
|
||||||
|
## 2. Назначения (несколько одновременно)
|
||||||
|
|
||||||
|
Назначение = именованная запись: тип, параметры, секреты, флаг «включено», число хранимых копий (по умолчанию 14). «Backup now» отправляет пакет **во все включённые назначения** (или в выбранные), результат по каждому отдельно: сбой одного не отменяет остальные.
|
||||||
|
|
||||||
|
| Тип | Реализация | Параметры |
|
||||||
|
|---|---|---|
|
||||||
|
| Local | каталог на сервере | подпапка внутри корня `OVPMON_BACKUP_LOCAL_ROOT` (системные службы: `/var/lib/ovpmon/backups`, контейнеры: `/app/backups`, том `ovp_backups`); пути вне корня и символические ссылки отклоняются |
|
||||||
|
| FTP | `ftplib` (+ FTPS explicit TLS) | хост, порт, пользователь, пароль, каталог, TLS |
|
||||||
|
| SFTP | `paramiko` | хост, порт, пользователь, пароль или ключ, каталог; **отпечаток ключа хоста** фиксируется при первой проверке и далее обязателен |
|
||||||
|
| S3 | `minio` (Python SDK; работает с AWS S3 и совместимыми хранилищами, решение владельца) | endpoint, TLS вкл/выкл, регион (необязательно), bucket, префикс, access/secret key; режим адресации (path/virtual-host) при необходимости |
|
||||||
|
| SMB (Samba) | `smbprotocol` (клиент, без монтирования ОС и без root) | хост, порт, общая папка (share), каталог, пользователь, пароль, домен |
|
||||||
|
|
||||||
|
Общий интерфейс: `test()`, `put(file)`, `list()`, `get(name)`, `delete(name)`. Ротация: после успешной записи удаляются самые старые пакеты **нашего формата имени** сверх лимита.
|
||||||
|
|
||||||
|
Секреты назначений шифруются в базе ключом из `OVPMON_API_SECRET_KEY` (HKDF), API возвращает их только как маску. Они **не попадают в пакет** (на новом сервере назначения настраиваются заново; секреты старого сервера не переносятся). Смена ключа подписи требует повторного ввода секретов.
|
||||||
|
|
||||||
|
## 3. Хранение настроек резервного копирования
|
||||||
|
|
||||||
|
**Отдельный файл SQLite** рядом с базой профилировщика (`ovpmon_backup.db`): назначения, настройки, история запусков. Причина: восстановление заменяет `ovpn_profiler.db` и `openvpn_monitor.db`; настройки назначений не должны ни попадать в пакет, ни пропадать при восстановлении. Схема создаётся при старте сервиса (`CREATE IF NOT EXISTS` + таблица версии), существующие миграции не затрагиваются.
|
||||||
|
|
||||||
|
## 4. Восстановление
|
||||||
|
|
||||||
|
Поток в UI: **Source** (выпадающий список назначений) → автоматическая проверка источника (подключение, права на чтение, поиск пакетов) → **Package** (выпадающий список: дата, хост, размер, признак шифрования, новые сверху) → поле фразы (если пакет зашифрован) → отдельная кнопка **Restore** → окно подтверждения → прогресс.
|
||||||
|
|
||||||
|
Шаги на сервере (фоновая задача, одна на весь сервис, как асинхронная инициализация PKI):
|
||||||
|
|
||||||
|
1. Скачать пакет во временный каталог, расшифровать, проверить `manifest.json` и SHA-256 всех файлов.
|
||||||
|
2. **Безопасная распаковка**: только ожидаемые имена верхнего уровня; абсолютные пути, `..`, ссылки, устройства и превышение лимита размера отклоняются.
|
||||||
|
3. Отказ, если схема БД в пакете **новее** кода (версии в манифесте), или формат пакета неизвестен. Пакеты со старой схемой допустимы: после замены запускаются существующие миграции.
|
||||||
|
4. **Страховочная копия текущего состояния** в локальное назначение (`pre-restore`); если сделать её не удалось, восстановление не начинается.
|
||||||
|
5. Остановить OpenVPN (если запущен), заменить БД атомарным `os.replace`, `pki/` и `client-config/` каталогами через временные имена с откатом при ошибке; сбросить пул соединений SQLAlchemy профилировщика. Мониторинг и gatherer открывают БД на каждую операцию, остановка не нужна.
|
||||||
|
6. Миграции восстановленных БД; перегенерировать `server.conf` и опубликовать CRL существующим путём (в системных службах через root-помощник; помощник и его белый список не меняются); запустить OpenVPN, если он работал.
|
||||||
|
7. Результат в историю. UI предлагает войти заново (учётные записи теперь из пакета).
|
||||||
|
|
||||||
|
Во время восстановления изменяющие PKI и профили запросы получают 409 (тот же механизм, что у инициализации PKI). После переноса на новый сервер администратор проверяет адрес сервера (`remote`) в настройках VPN: он приходит из пакета.
|
||||||
|
|
||||||
|
## 5. API (Profiler API, префикс `/api`, снаружи `/profiles-api/`, все маршруты под JWT)
|
||||||
|
|
||||||
|
| Метод | Путь | Назначение |
|
||||||
|
|---|---|---|
|
||||||
|
| GET, PUT | `/backup/settings` | флаг и смена парольной фразы (значение не возвращается), корень локальных копий, лимит по умолчанию |
|
||||||
|
| GET, POST | `/backup/destinations` | список, создание |
|
||||||
|
| PUT, DELETE | `/backup/destinations/{id}` | изменение, удаление |
|
||||||
|
| POST | `/backup/destinations/{id}/test` | проверка подключения и записи |
|
||||||
|
| POST | `/backup/run` | запуск копирования (`destination_ids` необязательно), 202 |
|
||||||
|
| GET | `/backup/destinations/{id}/packages` | проверить источник и перечислить пакеты (имя, время, размер, шифрование) |
|
||||||
|
| POST | `/backup/restore` | `destination_id`, `package`, `passphrase` (необязательно), 202 |
|
||||||
|
| GET | `/backup/status` | текущая задача: этапы и результат по назначениям |
|
||||||
|
| GET | `/backup/history` | последние запуски |
|
||||||
|
|
||||||
|
Имя пакета проверяется регулярным выражением и берётся только из листинга; пути от клиента не принимаются.
|
||||||
|
|
||||||
|
## 6. UI
|
||||||
|
|
||||||
|
Новый вид `APP_UI/src/views/BackupRestore.vue`, маршрут `/backup`, пункт **Backup and Restore** в разделе MANAGEMENT боковой панели (рядом с Certificates и Server Process, тот же стиль ссылки и значка). Внешний вид повторяет существующие страницы: `config-wrapper` / `config-card` / `config-header`, `status-badge`, `BaseModal`, `ConfirmModal`, `useToast`, оба светлых и тёмных оформления; английские подписи, как везде.
|
||||||
|
|
||||||
|
1. **Destinations**: таблица (имя, тип, статус «включено», последний результат, действия Test / Edit / Delete), кнопка «Add destination», модальное окно с полями выбранного типа.
|
||||||
|
2. **Backup**: статус шифрования (предупреждение, если фразы нет), флажки назначений, кнопка **Backup now**, прогресс и результат по каждому назначению, история.
|
||||||
|
3. **Restore**: выбор источника, список пакетов, фраза, кнопка **Restore** (красная, с подтверждением, перечисляющим последствия).
|
||||||
|
|
||||||
|
## 7. Развёртывание
|
||||||
|
|
||||||
|
- Зависимости в `APP_PROFILER/requirements.txt`: `cryptography`, `paramiko`, `minio`, `smbprotocol`. Если сценарий S3 не получится реализовать на `minio`, драйвер S3 откатывается (решение владельца: сначала `minio`); интерфейс назначений от этого не меняется.
|
||||||
|
- Контейнеры: новый том `ovp_backups` на `/app/backups` в `docker-compose.yml` и `docker-compose.allinone.yml`. Список томов в `deploy/docker/lib.sh` (`VOLUMES`, пять томов) **не расширяется**: том с копиями не копируется внутрь копий томов.
|
||||||
|
- Системные службы: каталог `/var/lib/ovpmon/backups` создаётся службой (владелец `ovpmon`), установщик не меняется; сборка Python-зависимостей на Alpine проверяется.
|
||||||
|
- Nginx: изменений нет (задачи асинхронные, опрос статуса).
|
||||||
|
|
||||||
|
## 8. Шаги реализации (три прохода, после каждого проверка)
|
||||||
|
|
||||||
|
Приоритет владельца: резервное копирование и восстановление **в бакет S3 и из него**. Поэтому S3 входит в первый проход.
|
||||||
|
|
||||||
|
| Проход | Содержимое | Проверка |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 | Формат пакета, шифрование, безопасная распаковка, хранилище настроек, назначения **Local и S3 (`minio`)**, API (все маршруты), движок восстановления, весь UI | автотесты; ручной круг на стенде с локальным назначением (копия, повреждение данных, восстановление, перенос между чистыми окружениями); S3 проверяется владельцем на его бакете вместе с ассистентом, **локальный S3 для эмуляции не поднимается** |
|
||||||
|
| 2 | FTP, SFTP | на стенде тестовые контейнеры (vsftpd/pure-ftpd, `atmoz/sftp`) |
|
||||||
|
| 3 | SMB, ротация во всех типах, документация, сводка | тестовый контейнер Samba; одновременная запись в 3-4 назначения и сбой одного из них |
|
||||||
|
|
||||||
|
## 9. Автотесты (минимум, 3-4 шт., `APP_PROFILER`)
|
||||||
|
|
||||||
|
1. Полный круг пакета: создать, зашифровать, проверить, восстановить во временные каталоги (БД читаются, PKI и профили совпадают), неверная фраза отклоняется.
|
||||||
|
2. Безопасная распаковка: пакет с `../` и ссылкой отклоняется; пакет с более новой схемой отклоняется.
|
||||||
|
3. Несколько назначений: одно рабочее (Local) и одно с ошибкой, результат по каждому, ротация по лимиту.
|
||||||
|
4. API: маршруты требуют JWT; секреты в ответах замаскированы; удалённое назначение без фразы отклоняется.
|
||||||
|
|
||||||
|
Клиенты S3/FTP/SFTP/SMB проверяются вручную (раздел 8), без юнит-тестов; для S3 драйвер подменяется в тесте заглушкой интерфейса назначений, настоящий S3 в автотестах не используется.
|
||||||
|
|
||||||
|
## 10. Риски
|
||||||
|
|
||||||
|
- Пакет содержит ключ CA и хеши паролей: шифрование обязательно для удалённых назначений, права локальных каталогов 700/600, секреты не пишутся в журнал.
|
||||||
|
- Восстановление заменяет учётные записи и PKI: обязательная страховочная копия и подтверждение с перечнем последствий.
|
||||||
|
- Сервер подключается к адресам, заданным администратором (SSRF в рамках функции); доступ только по JWT единственной роли, адреса и порты проверяются по формату.
|
||||||
|
- Размер: база статистики может быть большой; пакет собирается потоково через временный файл, нужен запас места в `/tmp` или в корне локальных копий.
|
||||||
|
- Возврат к прежнему состоянию после неудачного восстановления: каталоги и БД заменяются через временные имена, страховочная копия остаётся.
|
||||||
|
|
||||||
|
## 11. Документация
|
||||||
|
|
||||||
|
Новый `DOCS/Profiler_Management/Backup_Restore.md` (руководство, включая перенос между серверами в обоих вариантах установки), обновление `Profiler_Management/API_Reference.md`, `UI/Architecture.md`, `General/Overview.md` (где лежат данные), `General/Security_Architecture.md`, `Deployment/Containers/Reference.md` (новый том), `Deployment/System_Services/Reference.md` (каталог копий), README.md (таблица документации), `DOCS/Changes/README.md`, сводка `2026-10-07_Backup_Restore.md`.
|
||||||
|
|
||||||
|
## 12. Порядок
|
||||||
|
|
||||||
|
1. Утверждение плана (и решений из раздела «Вопросы»).
|
||||||
|
2. Реализация субагентом (Sonnet 5.5, Medium Effort), три прохода.
|
||||||
|
3. Проверка на стенде после каждого прохода, затем документация и сводка.
|
||||||
|
|
||||||
|
## Решения владельца (2026-10-07)
|
||||||
|
|
||||||
|
1. Парольная фраза обязательна для удалённых назначений: **да**.
|
||||||
|
2. Расписание автоматических копий: **позже, отдельным шагом**.
|
||||||
|
3. Загрузка пакета с компьютера как источник восстановления: **нет**.
|
||||||
|
4. Драйвер S3: **`minio`**; при невозможности реализовать сценарий откат на другой драйвер. Тестирование на бакете владельца, локальный S3 не поднимается.
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
# Скрипты установки и миграции: проверка на новом коде (сводка, 2026-10-07)
|
||||||
|
|
||||||
|
План: [2026-10-07_Deploy_Scripts_Check_PLAN.md](2026-10-07_Deploy_Scripts_Check_PLAN.md).
|
||||||
|
|
||||||
|
## 1. Что проверено
|
||||||
|
|
||||||
|
| Проверка | Результат |
|
||||||
|
|---|---|
|
||||||
|
| Синтаксис всех `deploy/**/*.sh` (`bash -n`) | без ошибок |
|
||||||
|
| `deploy/native/install.sh` из нового кода (Debian 12, systemd, одноразовый контейнер) | работает, новые зависимости (`minio`, `paramiko`, `cryptography`) установлены, службы активны |
|
||||||
|
| **Обновление** `deploy/native/update.sh` со старой версии (`ad6995b`) на новую, в той же среде | работает: резервная копия, подготовка, миграция мониторинга 1 → 2 отдельным шагом, запуск, проверки; данные (PKI, профиль) сохранены, раздел Backup доступен, копия создаётся |
|
||||||
|
| `deploy/native/update.sh --rollback` | работает: код, БД (схема 1), PKI и профили восстановлены, службы активны |
|
||||||
|
| Скрипты Docker: разбор | `MIG_TARGETS` (профилировщик `/app`, мониторинг `/app` или `/app/APP_CORE`) соответствуют новым образам; том `ovp_backups` намеренно вне `VOLUMES`; `compose.previous.yml` задаёт только образы |
|
||||||
|
|
||||||
|
## 2. Найденные расхождения и что сделано
|
||||||
|
|
||||||
|
### D1. Docker: версия compose для варианта B
|
||||||
|
|
||||||
|
Вариант B (`docker-compose.yml`) использует `additional_contexts` (Docker Compose v2.17+); на более старом compose или на `docker-compose` v1 сборка падала с невнятной ошибкой.
|
||||||
|
|
||||||
|
Сделано в `deploy/docker/lib.sh`:
|
||||||
|
|
||||||
|
- `version_ge FOUND REQUIRED` - чистое сравнение версий `MAJOR.MINOR[.PATCH]` без обращения к docker; игнорирует ведущую `v` и суффиксы (`-desktop.1`). Код возврата: 0 - не ниже требуемой, 1 - ниже, 2 - не разобрана.
|
||||||
|
- `need_compose_version` - для варианта B: `docker-compose` v1 - остановка; `docker compose version --short` ниже `MIN_COMPOSE_VERSION` (2.17.0) - остановка; версия не разобрана - предупреждение и продолжение. Для варианта A ничего не делает. Сообщения: что требуется, что найдено, как исправить (обновить плагин или взять вариант A).
|
||||||
|
|
||||||
|
Вызовы: фаза 0 `install.sh` (после `need_docker`, до `dc`) и фаза 0 `update.sh` (до `dc config -q`; `--rollback` не собирает образы, проверка не нужна). `backup.sh` и `restore.sh` образы не собирают - не затронуты.
|
||||||
|
|
||||||
|
Документация: `DOCS/Deployment/Containers/README.md`, `Reference.md` (упомянуто, что скрипты проверяют версию).
|
||||||
|
|
||||||
|
### D2. Native: `ovpmon_backup.db` в копии и восстановлении
|
||||||
|
|
||||||
|
Файл настроек Backup and Restore (назначения, парольная фраза, зашифрованные секреты) не попадал в копию хоста. Сделано в `deploy/native/lib.sh`:
|
||||||
|
|
||||||
|
- `resolve_db_paths`: новая переменная `DB_BACKUPCFG` - `ovpmon_backup.db` в каталоге `DB_PROFILER` (так задаёт приложение: `APP_PROFILER/services/backup/store.py`, отдельной переменной окружения нет).
|
||||||
|
- `make_backup`: необязательная копия `db/backupcfg.db` тем же `backup_db` (API SQLite, проверка целостности, владелец и права сохраняются); нет файла - строка в журнале, не предупреждение и не сбой; запись `db_backupcfg=` в `MANIFEST`; файл входит в `SHA256SUMS` (через `db/*`).
|
||||||
|
- `verify_backup`: цикл по `db/*.db` выполняет только `PRAGMA integrity_check` (проверок схемы и миграций нет), поэтому код не менялся, уточнён комментарий.
|
||||||
|
- `restore_all`: `restore_db` для `db/backupcfg.db` (атомарно, заменённый файл остаётся как `<файл>.failed-<время>`); нет копии (копия старой версии) - живой файл не трогается.
|
||||||
|
|
||||||
|
Пакеты Backup and Restore (`/var/lib/ovpmon/backups`) в копию не входят: `code.tar.gz` собирается из каталога установки (`APP_CORE`, `APP_PROFILER`), `etc-*.tar.gz` из `/etc`, каталог данных `/var/lib/ovpmon` целиком не архивируется (копируются только три файла БД через API SQLite). Изменения это не меняют.
|
||||||
|
|
||||||
|
Документация: `DOCS/Deployment/System_Services/Operations.md` (состав копии, восстановление, ручной вариант), `Reference.md`.
|
||||||
|
|
||||||
|
## 3. Шаги плана
|
||||||
|
|
||||||
|
| Шаг | Содержание | Статус |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 | D1 | выполнен |
|
||||||
|
| 2 | D2 | выполнен |
|
||||||
|
| 3 | Проверка D2 в контейнере Debian 12 с systemd | проверяет ассистент |
|
||||||
|
| 4 | Проверка D1 заглушкой `docker` в `PATH` | проверяет ассистент |
|
||||||
|
| 5 | Живая проверка скриптов Docker (варианты A и B) | проверяет ассистент |
|
||||||
|
| 6 | Сводка и строка в `DOCS/Changes/README.md` | выполнен |
|
||||||
|
|
||||||
|
Выполнено при разработке (без docker): `sh -n` и `bash -n` для изменённых скриптов; `version_ge` на примерах (2.16.9 - ниже, 2.17.0, v2.38.2, 2.40.3-desktop.1 - не ниже, 1.29.2 - ниже, мусор - не разобрана); `need_compose_version` с подменой `docker`; `resolve_db_paths`, `backup_db`, `check_db_copy`, `restore_db` на временных файлах.
|
||||||
|
|
||||||
|
## 4. Результаты проверки (ассистент, 2026-10-07)
|
||||||
|
|
||||||
|
| Проверка | Среда | Результат |
|
||||||
|
|---|---|---|
|
||||||
|
| D2: `backup.sh` | Debian 12 + systemd (одноразовый контейнер) | в копии есть `db/backupcfg.db`, запись `db_backupcfg` в MANIFEST, копия проверена |
|
||||||
|
| D2: `restore.sh` | то же | изменённая настройка (`server_name`) вернулась из копии, назначение сохранилось; заменённый файл сохранён как `.failed-*` |
|
||||||
|
| D2: старая копия без `backupcfg.db` | то же | восстановление проходит (INFO, файл не тронут) |
|
||||||
|
| D2: `update.sh` + `--rollback` | то же | обновление со старой версии (`ad6995b`) и откат работают, `ovpmon_backup.db` сохраняется и восстанавливается |
|
||||||
|
| D1: версия compose | реальный `docker compose` 2.38.2 | в фазе 0 `update.sh` пишет «required for variant B: 2.17.0 or newer», далее штатно; отказ при 2.16.9, v1 для варианта B и разбор версий проверены подменой `docker` и таблицей примеров |
|
||||||
|
| Docker, вариант B: `install.sh` старой версии, данные (PKI, профиль), `update.sh`, `update.sh --rollback` | отдельный проект и порты, стенд временно остановлен | обновление прошло, миграция мониторинга 1 → 2 отдельным шагом, данные на месте, раздел Backup работает, копия создаётся; откат поднял предыдущие образы, стек здоров |
|
||||||
|
| Docker, вариант A: то же | то же | то же |
|
||||||
|
| Alpine 3.23 + OpenRC: `install.sh` старой версии, `update.sh` на новую, миграция 1 → 2 | одноразовый контейнер (`--init`, `--privileged`, OpenRC) | установка и обновление прошли, службы `ovpmon-*` и nginx запущены, проверки здоровья пройдены |
|
||||||
|
| Alpine: резервное копирование и восстановление в приложении | то же | копия в Local; восстановление остановило и снова запустило OpenVPN через помощник (служба `openvpn` OpenRC), данные вернулись |
|
||||||
|
| Alpine: `backup.sh`, `restore.sh`, `update.sh --rollback` | то же | `db/backupcfg.db` в копии и в MANIFEST, настройка Backup вернулась после `restore.sh`; откат и повторное обновление проходят |
|
||||||
|
|
||||||
|
Наблюдения: (1) `update.sh` не проверяет, идёт ли инициализация PKI: остановка профилировщика в этот момент оставляет маркер `.pki-init-in-progress` и осиротевший процесс `easyrsa gen-dh`; инициализацию нужно запустить заново из UI (редкий случай, не исправлялся). (2) В контейнерах для OpenRC нужен init, убирающий зомби (`docker run --init`), иначе `rc-service ... restart` зависает: это особенность тестовой среды, а не скриптов.
|
||||||
|
|
||||||
|
Не проверено: автоматический откат при сбое после остановки (искусственно не вызывался), срабатывание проверки D1 на реально старом compose (только подмена), Alpine на отдельной машине (проверено в контейнере).
|
||||||
|
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# Скрипты установки и миграции: проверка на новом коде (план, 2026-10-07)
|
||||||
|
|
||||||
|
Основание: проверка `deploy/` после изменений (учёт сессий, миграция 2, Backup and Restore, новые зависимости, образ профилировщика с `additional_contexts`).
|
||||||
|
|
||||||
|
## 1. Что проверено
|
||||||
|
|
||||||
|
| Проверка | Результат |
|
||||||
|
|---|---|
|
||||||
|
| Синтаксис всех `deploy/**/*.sh` (`bash -n`) | без ошибок |
|
||||||
|
| `deploy/native/install.sh` из нового кода (Debian 12, systemd, одноразовый контейнер) | работает, новые зависимости (`minio`, `paramiko`, `cryptography`) установлены, службы активны |
|
||||||
|
| **Обновление** `deploy/native/update.sh` со старой версии (`ad6995b`) на новую, в той же среде | работает: резервная копия, подготовка, миграция мониторинга 1 → 2 отдельным шагом, запуск, проверки; данные (PKI, профиль) сохранены, раздел Backup доступен, копия создаётся |
|
||||||
|
| `deploy/native/update.sh --rollback` | работает: код, БД (схема 1), PKI и профили восстановлены, службы активны |
|
||||||
|
| Скрипты Docker: разбор | `MIG_TARGETS` (профилировщик `/app`, мониторинг `/app` или `/app/APP_CORE`) соответствуют новым образам; том `ovp_backups` намеренно вне `VOLUMES`; `compose.previous.yml` задаёт только образы |
|
||||||
|
|
||||||
|
## 2. Найденные расхождения
|
||||||
|
|
||||||
|
| ID | Расхождение | Решение |
|
||||||
|
|---|---|---|
|
||||||
|
| D1 | Docker: `need_docker` не проверяет версию compose. Вариант B (`docker-compose.yml`) использует `additional_contexts` (Docker Compose v2.17+); на более старом compose или на `docker-compose` v1 сборка падает с невнятной ошибкой | Проверка версии в предварительной проверке (фаза 0) для варианта B: нужен `docker compose` v2.17+, иначе остановка с понятным сообщением. Вариант A не затронут |
|
||||||
|
| D2 | Native: `backup.sh`, `update.sh` (фаза 1) и `restore.sh`/`--rollback` копируют и восстанавливают две базы (`monitor.db`, `profiler.db`), но **не `ovpmon_backup.db`** (назначения и парольная фраза резервного копирования). После аварийного восстановления на том же сервере настройки Backup and Restore пропали бы (в Docker файл лежит в томе `db_data` и копируется) | Включить `ovpmon_backup.db` в копию и восстановление как необязательный файл (нет файла: предупреждения нет в журнале ошибок, не сбой). Каталог `/var/lib/ovpmon/backups` (пакеты) в копию **не** входит, как и том `ovp_backups` |
|
||||||
|
|
||||||
|
## 3. Шаги
|
||||||
|
|
||||||
|
1. D1: функция проверки версии в `deploy/docker/lib.sh`, вызов из `install.sh`, `update.sh` (и `backup.sh`/`restore.sh`, если они выполняют сборку; иначе не нужен), для варианта B. Документировать требование в `DOCS/Deployment/Containers/README.md` (уже есть) и в сообщении.
|
||||||
|
2. D2: в `deploy/native/lib.sh` (создание копии, проверка копии по `SHA256SUMS`/`MANIFEST`, восстановление) добавить необязательный `db/backupcfg.db`; путь `OVPMON_BACKUP_CONFIG_DB_PATH`, иначе `ovpmon_backup.db` рядом с БД профилировщика (как в приложении). Обновить `DOCS/Deployment/System_Services/Operations.md` (состав копии).
|
||||||
|
3. Проверка D2 в контейнере Debian 12 с systemd: `backup.sh`, изменение настроек Backup, `restore.sh`, настройки на месте; `update.sh --rollback` не теряет `ovpmon_backup.db`.
|
||||||
|
4. Проверка D1: имитация старой версии compose (подмена `docker` скриптом-заглушкой в `PATH`) и штатного запуска.
|
||||||
|
5. Живая проверка скриптов Docker (варианты A и B: установка старой версии, обновление до новой, откат): нужен остановленный стенд (`ovp-*`), так как предварительная проверка скриптов не допускает контейнеры другого варианта. Выполняется с разрешения владельца.
|
||||||
|
6. Сводка `2026-10-07_Deploy_Scripts_Check.md`, строка в `DOCS/Changes/README.md`.
|
||||||
|
|
||||||
|
## 4. Тесты
|
||||||
|
|
||||||
|
Автотестов нет (скрипты оболочки), проверка шагами 3-5.
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Шаблоны OpenVPN: сверка с мануалом 2.7 (сводка, 2026-10-07)
|
||||||
|
|
||||||
|
План: [2026-10-07_OVPN_Templates_PLAN.md](2026-10-07_OVPN_Templates_PLAN.md).
|
||||||
|
|
||||||
|
## 1. Что изменено
|
||||||
|
|
||||||
|
| # | Файл | Результат |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 | `APP_PROFILER/templates/client.ovpn.j2` | Удалена строка `windows-driver wintun` |
|
||||||
|
| 2 | `APP_PROFILER/templates/client.ovpn.j2` | Удалён блок `tls-client` / `#tls-client` (директива `client` уже включает `tls-client`) |
|
||||||
|
| 3 | `APP_PROFILER/templates/client.ovpn.j2` | Удалены `user nobody` и `group nobody` |
|
||||||
|
| 4 | `APP_PROFILER/templates/client.ovpn.j2` | Для `protocol == 'udp'` добавлена строка `explicit-exit-notify` (без аргумента) после `nobind`, внутри `{% if protocol == 'udp' %}` |
|
||||||
|
| 5 | `APP_PROFILER/templates/server.conf.j2` | Удалены `tls-server` (ветка tcp), комментарий `# explicit-exit-notify 1` и строка `log`; остались `log-append` и `explicit-exit-notify 1` для не-tcp |
|
||||||
|
|
||||||
|
Остальное содержимое шаблонов не менялось (`data-ciphers`, `data-ciphers-fallback`, `persist-key`, `key-direction`, пустые строки).
|
||||||
|
|
||||||
|
Добавлен один тест: `APP_PROFILER/test_client_template.py` (рендер клиентского шаблона для tcp и udp).
|
||||||
|
|
||||||
|
## 2. Проверка
|
||||||
|
|
||||||
|
- Рендер обоих шаблонов для `tcp` и `udp` (окружение Jinja из `services/generator.py`):
|
||||||
|
- клиент: нет `windows-driver`, `tls-client`, `user`, `group`; `explicit-exit-notify` только в udp;
|
||||||
|
- сервер: нет `tls-server`, `# explicit-exit-notify`, строки `log `; есть `log-append`, `user nobody`, `group nogroup`, `server`, `ca`, `cert`, `key`; `explicit-exit-notify 1` только в udp.
|
||||||
|
- Валидатор root-помощника (`validate()` из `ovpmon-helper`, вызван офлайн без root, без побочных эффектов): серверные конфиги udp и tcp приняты.
|
||||||
|
- `pytest` в `APP_PROFILER` (venv проекта, зависимости доустановлены): 16 прошли, 2 упали (`test_server_process.py::test_get_stats`, `::test_control_invalid`, ответ 404). Эти два падения воспроизводятся и на прежних шаблонах, к изменению не относятся.
|
||||||
|
- Запуск клиента 2.7 с новым профилем на стенде: не выполнялся, остаётся за владельцем.
|
||||||
|
|
||||||
|
## 3. Ограничения
|
||||||
|
|
||||||
|
- Уже выданные `.ovpn` в `client-config/` сохраняют старые строки (в том числе `windows-driver`). Перегенерация существующих профилей - отдельный шаг по решению владельца.
|
||||||
|
- Серверный `server.conf` изменится только после следующей генерации и применения конфигурации через API.
|
||||||
|
- Документация: описаний содержимого шаблонов, затронутых изменением, в `DOCS/` и `APP_PROFILER/README.md` нет, правки не потребовались.
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# Шаблоны OpenVPN: сверка с мануалом 2.7 (план, 2026-10-07)
|
||||||
|
|
||||||
|
Источник: сверка `APP_PROFILER/templates/client.ovpn.j2` и `server.conf.j2` с [мануалом OpenVPN 2.7](https://openvpn.net/community-docs/community-articles/openvpn-2-7-manual.html). Повод: клиент 2.7.7 отклонил профиль из-за `windows-driver` (`Unrecognized option`).
|
||||||
|
|
||||||
|
## 1. Изменения
|
||||||
|
|
||||||
|
| # | Файл | Изменение | Основание |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1 | `client.ovpn.j2` | Удалить `windows-driver wintun` | Мануал 2.7: «Removed in OpenVPN 2.7»; профиль не запускается |
|
||||||
|
| 2 | `client.ovpn.j2` | Удалить блок `tls-client` / `#tls-client` | Директива `client` уже включает `tls-client` |
|
||||||
|
| 3 | `client.ovpn.j2` | Удалить `user nobody` и `group nobody` | Группа `nobody` отсутствует в Debian/Ubuntu (на сервере `nogroup`); на пользовательских устройствах сброс привилегий не нужен |
|
||||||
|
| 4 | `client.ovpn.j2` | Для `protocol == 'udp'` добавить `explicit-exit-notify` | Сервер сразу видит отключение, а не ждёт таймаут `keepalive` (120 с): точнее статус «Active» в мониторинге |
|
||||||
|
| 5 | `server.conf.j2` | Удалить `tls-server` (ветка tcp), закомментированный дубль `# explicit-exit-notify 1`, строку `log` (оставить `log-append`) | `server` включает `tls-server`; `log` и `log-append` указывают на один файл |
|
||||||
|
|
||||||
|
Не меняется: `data-ciphers` и `data-ciphers-fallback` (содержат `AES-256-CBC` для старых клиентов, решение об отказе от CBC принимает владелец стенда), `persist-key` (игнорируется в 2.7, нужна для 2.4-2.6).
|
||||||
|
|
||||||
|
## 2. Ограничения и проверка
|
||||||
|
|
||||||
|
- Root-помощник (`ovpmon-helper`) и его белый список директив не меняются: удаляются только директивы, обязательные (`user nobody`, `group nogroup`, `server`, `ca`, `cert`, `key`) остаются. Директива `explicit-exit-notify` в белом списке есть, в клиентский профиль она не проходит через помощника.
|
||||||
|
- Уже выданные `.ovpn` хранятся файлами в `client-config/` и сохранят старые строки. Перегенерация существующих профилей в этот план не входит (отдельный шаг по решению владельца).
|
||||||
|
- Проверка: `pytest` в `APP_PROFILER`; рендер обоих шаблонов для `tcp` и `udp` (без `windows-driver`, `tls-client`, `user`/`group` в клиенте; `explicit-exit-notify` только в udp); запуск клиента 2.7 с новым профилем на стенде.
|
||||||
|
- Автотесты: добавить не более одного теста на рендер клиентского шаблона (tcp и udp), если подходящего теста нет.
|
||||||
|
|
||||||
|
## 3. Порядок
|
||||||
|
|
||||||
|
1. План утверждён владельцем (2026-10-07).
|
||||||
|
2. Реализация субагентом (Sonnet 5.5, Medium Effort).
|
||||||
|
3. Проверка, документация (`DOCS/`, где упомянуты шаблоны), сводка `2026-10-07_OVPN_Templates.md`, строка в `DOCS/Changes/README.md`.
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# Доставка UI: сборка, CSP и nginx без root (сводка, 2026-10-07)
|
||||||
|
|
||||||
|
План: [2026-10-07_UI_Delivery_Hardening_PLAN.md](2026-10-07_UI_Delivery_Hardening_PLAN.md). Выполнены этапы A-D, по коммиту на этап, последний коммит - документация. Код `APP_UI/src`, бэкенд (`APP_CORE`, `APP_PROFILER`), B4 (`disable-2fa`) и разбиение `BackupRestore.vue` не менялись.
|
||||||
|
|
||||||
|
Решения владельца: для этапа D взят `nginxinc/nginx-unprivileged:alpine` (порт 8080); переменная называется `OVPMON_CSP_CONNECT_EXTRA` (внутри контейнеров `OVP_CSP_CONNECT_EXTRA`), значение - origin через пробел.
|
||||||
|
|
||||||
|
## 1. Что сделано
|
||||||
|
|
||||||
|
### Этап A. `deploy/ui-dist` (коммит `d38acd7`)
|
||||||
|
|
||||||
|
`check-ui.sh` до пересборки: `stale` (сборка `7960728...`, исходники `d778aa1...`). `build-ui.sh --publish` (режим Docker, `node:20-alpine`) опубликовал сборку с `SOURCE_HASH d778aa16...`; `check-ui.sh` после: `fresh`. В коммит вошёл только `deploy/ui-dist` (новые файлы `Clients-*.js`, `useFormatters-*.js`, `useTrafficChart-*.js`, удалены `vite.svg` и старые хеши). Временных файлов в дереве нет.
|
||||||
|
|
||||||
|
### Этап B. CSP и дополнительные origin для `connect-src` (коммит `d5e83ea`)
|
||||||
|
|
||||||
|
| Шаг | Результат |
|
||||||
|
|---|---|
|
||||||
|
| B1 | `APP_UI/Dockerfile`: `ENV OVP_CSP_CONNECT_EXTRA=""`; шаблон: `connect-src 'self' ${OVP_CSP_CONNECT_EXTRA}`; `docker-compose.yml`: `OVP_CSP_CONNECT_EXTRA: ${OVPMON_CSP_CONNECT_EXTRA:-}` |
|
||||||
|
| B2 | All-in-one: переменная добавлена в явный список `envsubst` в `entrypoint.sh`; `docker-compose.allinone.yml` передаёт `OVPMON_CSP_CONNECT_EXTRA` |
|
||||||
|
| B3 | Единый CSP: `set $csp "..."` на уровне `server`, `add_header Content-Security-Policy $csp always;` в `server` и в `location /assets/` |
|
||||||
|
| B4 | Проверка значения (только `https://host[:port]` и `http://host[:port]`, разделитель - пробелы, пустое допустимо; без `;`, кавычек, запятых, путей, пробела в начале и в конце): `deploy/docker/lib.sh` (`csp_extra_problem`, вызывается из `check_env_file`, то есть в `install.sh` и `update.sh`), `deploy/native/lib.sh` (та же функция), `APP_UI/check-csp-connect-extra.sh` - один скрипт для образа `app-ui` (`/docker-entrypoint.d/15-check-csp-connect-extra.sh`, выполняется до `20-envsubst-on-templates.sh`) и для all-in-one (копируется в образ, вызывается из `entrypoint.sh`). Три копии правила содержат комментарий «держать в согласии» |
|
||||||
|
| B5 | Системный nginx: в `ovpmon.conf.template` добавлен CSP с `@CSP_CONNECT_EXTRA@` (на уровне `server`, `Cache-Control: no-store` остался). `render_nginx SRC PORT OUT [ORIGINS]` проверяет значение и подставляет его с ведущим пробелом, при пустом значении ничего не остаётся. `install.sh` и `update.sh` принимают `--csp-connect-extra ORIGINS`, значение хранится в состоянии `OVPMON_CSP_CONNECT_EXTRA`; `update.sh` без флага берёт его из состояния, `--csp-connect-extra ""` убирает; справка обновлена |
|
||||||
|
| B6 | Документация: `DOCS/UI/Architecture.md`, `DOCS/Deployment/Containers/Reference.md`, `Troubleshooting.md`, `DOCS/Deployment/System_Services/Nginx_Configuration.md` (раздел 4), `README.md`, `Operations.md`, `Reference.md` (состояние), `APP_UI/README.md` |
|
||||||
|
|
||||||
|
### Этап C. `npm ci` в all-in-one (коммит `71ea4c5`)
|
||||||
|
|
||||||
|
`deploy/allinone/Dockerfile`: `npm install` -> `npm ci`.
|
||||||
|
|
||||||
|
### Этап D. nginx без root в `app-ui` (коммит `3347fff`)
|
||||||
|
|
||||||
|
| Шаг | Результат |
|
||||||
|
|---|---|
|
||||||
|
| D1 | `APP_UI/Dockerfile`: база `nginxinc/nginx-unprivileged:alpine`, `EXPOSE 8080`, комментарий о root заменён описанием |
|
||||||
|
| D2 | Шаблон: `listen ${OVP_UI_PORT};`; `ENV OVP_UI_PORT=8080` в образе; в all-in-one `entrypoint.sh` задаёт `OVP_UI_PORT=80` и передаёт в `envsubst` |
|
||||||
|
| D3 | `docker-compose.yml`: `"${OVPMON_HTTP_PORT:-80}:8080"`, healthcheck на `http://127.0.0.1:8080/`. `docker-compose.allinone.yml` не менялся (порт 80) |
|
||||||
|
| D4 | В `deploy/docker/*.sh` внутренний порт 80 контейнера `app-ui` не упоминается (скрипты работают только с портом хоста). В документации обновлены `Containers/Reference.md` и `README.md`; прочие «порт 80» относятся к хосту, системному nginx или вариантам, которых изменение не касается |
|
||||||
|
|
||||||
|
## 2. Проверки (команды и результаты)
|
||||||
|
|
||||||
|
Все проверки в одноразовых контейнерах и образах с именами `ovpchk-*`; рабочие контейнеры `ovp-*` не запускались, не останавливались и не перезапускались.
|
||||||
|
|
||||||
|
| Что | Как | Результат |
|
||||||
|
|---|---|---|
|
||||||
|
| A | `deploy/native/check-ui.sh` до и после `build-ui.sh --publish` | `stale` (код 1) -> `fresh` (код 0) |
|
||||||
|
| B4, правило | 23 значения (допустимые: пусто, один origin, два через пробел, с портом, IP; недопустимые: `;`, запятая, кавычки, путь, `*`, `ftp://`, пустой хост и порт, порт 99999, лишний `:`, пробел в начале и в конце, табуляция, `#`, `&`) через `sh` (dash) и `bash` | `deploy/native/lib.sh` и `deploy/docker/lib.sh` дают одинаковый вывод; скрипт `check-csp-connect-extra.sh` в busybox `ash` (контейнер `alpine:3`) принимает и отклоняет те же значения |
|
||||||
|
| B4, `.env` | `check_env_file` с временным `.env` | пустое и допустимое значения проходят, `https://a.com; x` отклонено с сообщением |
|
||||||
|
| B, `app-ui` | образ из `APP_UI` (на тот момент `nginx:alpine`), `curl -I` на `/`, `/assets/*.css`, `/config.json`, `/clients/some/route`, `/index.html`; пустое и непустое значение | заголовок CSP есть везде, origin в `connect-src`; недопустимое значение: контейнер завершается с кодом 1 и сообщением из `15-check-csp-connect-extra.sh` |
|
||||||
|
| B, all-in-one | сборка образа, одноразовый контейнер (без `NET_ADMIN`, без томов), значения допустимое/пустое/недопустимое | допустимое: `200`, CSP с origin, `nginx -T` содержит `$csp` и `listen 80`, `nginx -t` проходит, запуск дошёл до `supervisord`; пустое: `200`, CSP без лишних origin; недопустимое: `FATAL` и остановка до миграций |
|
||||||
|
| B5, системный nginx | `render_nginx` с пустым и непустым значением (в т.ч. с двойным пробелом между origin), `nginx -t` в контейнере `nginx:alpine` с временным сертификатом | оба конфига проходят; в файле нет остатков `@...@`; при пустом значении `connect-src 'self';`; значение с `;` отклонено до записи файла (код 1); `curl -kI` к одноразовому контейнеру: `Cache-Control: no-store` и CSP на `/` и на маршруте SPA |
|
||||||
|
| B5, маркер | `install_managed` для файла без маркера | код 2, файл не изменён |
|
||||||
|
| B5, справка | `install.sh --help`, `update.sh --help` | флаг описан |
|
||||||
|
| C | `docker build --no-cache --target ui-build -f deploy/allinone/Dockerfile .` (чтобы не взять слой из кэша), затем полная сборка | `npm ci`: 201 пакет, `vite build` проходит |
|
||||||
|
| D | образ `app-ui` на `nginx-unprivileged`: `id`, `ps`, `nginx -T`, `curl`, `wget` (команда healthcheck) | uid 101 (`nginx`), все процессы nginx от `nginx`; `listen 8080`; шаблон отрисован; `/`, `/config.json`, маршрут SPA - `200`, заголовки те же; `/api/x` без бэкенда - `502` (допустимо); `wget -q -O /dev/null http://127.0.0.1:8080/` успешен; порядок скриптов `10-listen`, `15-check-csp...`, `15-local-resolvers.envsh`, `20-envsubst`: проверочный скрипт выполняется и останавливает контейнер до отрисовки |
|
||||||
|
| D, all-in-one | пересборка и запуск после D | `listen 80`, `200`, CSP с origin |
|
||||||
|
| compose | `docker compose config` с временным `JWT_SECRET` | `app-ui`: `target: 8080`, `published: "80"`, `OVP_CSP_CONNECT_EXTRA` передан, healthcheck на 8080; all-in-one: конфигурация корректна |
|
||||||
|
| Синтаксис | `sh -n` для изменённых скриптов | без ошибок |
|
||||||
|
| Уборка | `docker image rm` временных образов (`ovpchk-*`, `nginx:alpine`, `nginxinc/nginx-unprivileged:alpine`), временные каталоги и файлы в `/tmp` | остатков нет |
|
||||||
|
|
||||||
|
## 3. Отклонения от плана
|
||||||
|
|
||||||
|
- Значение с пробелом в начале или в конце отклоняется (план: пробел в начале недопустим; конец добавлен для симметрии).
|
||||||
|
- Проверка для `app-ui` и all-in-one вынесена в один скрипт `APP_UI/check-csp-connect-extra.sh` (план предлагал отдельные реализации); правило при этом продублировано ещё в двух библиотеках `lib.sh`.
|
||||||
|
- В контейнере `app-ui` при пустом значении CSP содержит `connect-src 'self' ;` (пробел перед `;`): `envsubst` подставляет пустую строку. Для политики безвредно. В all-in-one и в системном nginx пробелы нормализуются.
|
||||||
|
- Для системного nginx в шаблоне плейсхолдер стоит без пробела перед ним (`'self'@CSP_CONNECT_EXTRA@;`): `render_nginx` добавляет пробел вместе со значением.
|
||||||
|
|
||||||
|
## 4. Что не проверено
|
||||||
|
|
||||||
|
- Живые `install.sh` / `update.sh` на хосте (native и docker) и `docker compose up` стенда: нужно разрешение владельца. Проверены только отдельные функции (`csp_extra_problem`, `render_nginx`, `check_env_file`, `install_managed`), `sh -n`, справка и `docker compose config`.
|
||||||
|
- Обновление существующей установки контейнеров: при `update.sh` пересоздание `ovp-ui` с портом 8080 внутри не запускалось.
|
||||||
|
- Браузерная проверка CSP (шрифты Font Awesome, inline-стили Bootstrap и Chart.js): браузера в среде нет.
|
||||||
|
- Вызов API другого origin с непустым `OVPMON_CSP_CONNECT_EXTRA` (CORS и `config.json`) проверен только по заголовку.
|
||||||
|
- `update.sh` системных служб на установке с уже записанным состоянием (чтение `OVPMON_CSP_CONNECT_EXTRA` из `deploy.state`) не запускался.
|
||||||
|
|
||||||
|
## 5. Риски и примечания
|
||||||
|
|
||||||
|
- Пользовательские compose-файлы или внешний прокси, которые публикуют порт 80 контейнера `ovp-ui`, нужно перевести на 8080 (внешний порт хоста не меняется).
|
||||||
|
- Образ `nginx-unprivileged` не входит в закреплённые версии (тег `alpine`); при необходимости зафиксировать версию.
|
||||||
|
- Значение CSP попадает в заголовок ответа: проверка обязательна, при изменении правила менять все три копии (`deploy/native/lib.sh`, `deploy/docker/lib.sh`, `APP_UI/check-csp-connect-extra.sh`).
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
# Доставка UI: сборка, CSP и nginx без root (план, 2026-10-07)
|
||||||
|
|
||||||
|
Основание: открытые пункты после `2026-10-07_UI_Review_Fixes.md`. Код `APP_UI/src` не меняется. B4 (`disable-2fa`) и разбиение `BackupRestore.vue` остаются вне плана.
|
||||||
|
|
||||||
|
## 1. Что найдено при подготовке
|
||||||
|
|
||||||
|
| Факт | Следствие |
|
||||||
|
|---|---|
|
||||||
|
| `SOURCE_HASH` считается по `APP_UI/src`, `public`, `index.html`, `package*.json`, `vite.config.js`, `jsconfig.json`. Шаблон nginx и `Dockerfile` в хеш не входят | `deploy/ui-dist` устарел из-за этапов 1-4 прошлого изменения; пересборка нужна один раз и не зависит от остальных этапов этого плана |
|
||||||
|
| Шаблон `APP_UI/default.conf.template` общий для образа `app-ui` и all-in-one. Образ `app-ui` подставляет переменные окружения сам, all-in-one вызывает `envsubst` с явным списком `OVP_*` (`deploy/allinone/entrypoint.sh:78`) | Новая переменная должна быть добавлена в оба места, иначе в конфиге останется буквальный `${...}` |
|
||||||
|
| CSP в шаблоне записан дважды (в `server` и в `location /assets/`) | Единый источник: `set $csp "..."` на уровне `server`, `add_header Content-Security-Policy $csp always` в обоих местах |
|
||||||
|
| Системный nginx (`deploy/native/nginx/ovpmon.conf.template`) отдаёт `Cache-Control: no-store` на всё и не имеет CSP; параметры (`HTTPS_PORT`) хранятся через `state_set` и подставляются `render_nginx` | Новый параметр хранится так же; существующие установки получают CSP при `update.sh`, пока в файле есть маркер управления |
|
||||||
|
| Healthcheck `app-ui` и публикация порта в `docker-compose.yml` привязаны к порту 80 | Для nginx без root порт меняется на 8080: правки compose и healthcheck |
|
||||||
|
|
||||||
|
## 2. Этапы
|
||||||
|
|
||||||
|
### Этап A. Пересборка `deploy/ui-dist` (пункт 2)
|
||||||
|
|
||||||
|
1. `deploy/native/check-ui.sh`: зафиксировать `stale` до пересборки.
|
||||||
|
2. `deploy/native/build-ui.sh --publish` (на хосте Node 18, поэтому режим Docker, образ `node:20-alpine`).
|
||||||
|
3. `check-ui.sh`: результат `ok`.
|
||||||
|
4. Коммит `deploy/ui-dist` отдельно от остальных этапов.
|
||||||
|
|
||||||
|
### Этап B. CSP для другого origin API (пункт 3)
|
||||||
|
|
||||||
|
| Шаг | Что делаем |
|
||||||
|
|---|---|
|
||||||
|
| B1 | Контейнеры: переменная `OVP_CSP_CONNECT_EXTRA` (пусто по умолчанию, значение: origin через пробел, например `https://api.example.com`). `ENV OVP_CSP_CONNECT_EXTRA=""` в `APP_UI/Dockerfile`; в шаблоне `connect-src 'self' ${OVP_CSP_CONNECT_EXTRA}`; в `docker-compose.yml` `OVP_CSP_CONNECT_EXTRA: ${OVPMON_CSP_CONNECT_EXTRA:-}` |
|
||||||
|
| B2 | All-in-one: добавить переменную в список `envsubst` и значение по умолчанию в `entrypoint.sh`; `docker-compose.allinone.yml` передаёт `OVPMON_CSP_CONNECT_EXTRA` |
|
||||||
|
| B3 | Единый CSP через `set $csp` (см. выше) |
|
||||||
|
| B4 | Проверка значения: допускаются только `https://host[:port]` и `http://host[:port]` без пробелов, `;` и кавычек (иначе можно внедрить директиву CSP). Для контейнеров проверка в `entrypoint.sh` (all-in-one) и в `deploy/docker/lib.sh` (скрипты установки); для `app-ui` без entrypoint проверка там же, где читается `.env` |
|
||||||
|
| B5 | Системный nginx: CSP добавляется в `ovpmon.conf.template` с плейсхолдером `@CSP_CONNECT_EXTRA@`; `render_nginx` подставляет значение из `state_get OVPMON_CSP_CONNECT_EXTRA` (по умолчанию пусто); `install.sh` и `update.sh` принимают `--csp-connect-extra ORIGINS` и сохраняют его через `state_set`. `Cache-Control: no-store` остаётся |
|
||||||
|
| B6 | Документация: `DOCS/UI/Architecture.md`, `DOCS/Deployment/Containers/Reference.md`, `DOCS/Deployment/System_Services/Nginx_Configuration.md` и `Reference.md` |
|
||||||
|
|
||||||
|
### Этап C. `npm ci` в all-in-one (пункт 4, часть 1)
|
||||||
|
|
||||||
|
`deploy/allinone/Dockerfile`: `npm install` заменить на `npm ci`; сборка образа и `docker-compose.allinone.yml` не меняются. Проверка: `docker build -f deploy/allinone/Dockerfile .` во временный образ (после проверки удалить).
|
||||||
|
|
||||||
|
### Этап D. nginx без root в образе `app-ui` (пункт 5)
|
||||||
|
|
||||||
|
Решение: `nginxinc/nginx-unprivileged:alpine` (шаблоны из `/etc/nginx/templates` рендерятся как и раньше, процесс от пользователя `nginx`, порт 8080).
|
||||||
|
|
||||||
|
| Шаг | Что делаем |
|
||||||
|
|---|---|
|
||||||
|
| D1 | `APP_UI/Dockerfile`: базовый образ `nginxinc/nginx-unprivileged:alpine`, `EXPOSE 8080`; убрать комментарий о root |
|
||||||
|
| D2 | Шаблон: `listen ${OVP_UI_PORT}`. `ENV OVP_UI_PORT=8080` в Dockerfile; в all-in-one значение 80 задаёт `entrypoint.sh` (все процессы там под supervisord от root для OpenVPN, образ не меняется) |
|
||||||
|
| D3 | `docker-compose.yml`: `"${OVPMON_HTTP_PORT:-80}:8080"`, healthcheck на `http://127.0.0.1:8080/`. Внешний порт не меняется |
|
||||||
|
| D4 | Проверка `deploy/docker/*.sh` и документации на упоминания внутреннего порта 80 `app-ui` |
|
||||||
|
| D5 | Проверка в одноразовом контейнере: `nginx -t`, `id` (не root), `curl -I` (заголовки, 200 на `/`, прокси `/api/` отвечает 502 без бэкенда, что допустимо) |
|
||||||
|
|
||||||
|
Если образ без root не подходит (например, политика на образы), этап D откладывается, остальное не затрагивается.
|
||||||
|
|
||||||
|
## 3. Порядок и коммиты
|
||||||
|
|
||||||
|
A, B, C, D: по одному коммиту, этапы независимы. Код пишет субагент (Sonnet 5.5, Medium) после утверждения плана.
|
||||||
|
|
||||||
|
## 4. Проверки
|
||||||
|
|
||||||
|
- **A:** `check-ui.sh` до и после.
|
||||||
|
- **B:** `nginx -t` на шаблоне с пустым и непустым `OVP_CSP_CONNECT_EXTRA`; `curl -I` показывает origin в `connect-src`; недопустимое значение (`;`, пробел в начале, кавычка) отклоняется с понятным сообщением. Для системного nginx: `render_nginx` во временный файл и `nginx -t` в одноразовом контейнере; `update.sh` не затирает файл без маркера.
|
||||||
|
- **C, D:** сборка образов, `nginx -t`, `curl -I`, `docker image rm` временных образов.
|
||||||
|
- Рабочие контейнеры и службы не трогаем; живая проверка `install.sh`/`update.sh` и compose на стенде делается только с разрешения владельца.
|
||||||
|
- Автотесты не добавляем (оболочка и конфигурация).
|
||||||
|
|
||||||
|
## 5. Риски
|
||||||
|
|
||||||
|
- Значение CSP попадает в заголовок: без проверки B4 можно внедрить лишнюю директиву, поэтому проверка обязательна.
|
||||||
|
- Этап D меняет внутренний порт образа: при пользовательских compose-файлах, ссылающихся на порт 80 контейнера `ovp-ui`, нужно обновить публикацию порта. Указать в сводке.
|
||||||
|
- Браузерная проверка (шрифты Font Awesome, inline-стили под CSP) остаётся ручной: в среде нет браузера.
|
||||||
|
- По завершении: сводка `2026-10-07_UI_Delivery_Hardening.md`, строка в `DOCS/Changes/README.md`, обновление `README.md` проекта и профильных документов.
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
# Ревью фронта APP_UI: исправления (сводка, 2026-10-07)
|
||||||
|
|
||||||
|
План: [2026-10-07_UI_Review_Fixes_PLAN.md](2026-10-07_UI_Review_Fixes_PLAN.md). Выполнены этапы 1-4 (U1-U18), по коммиту на этап. Бэкенд (`APP_CORE`, `APP_PROFILER`) не менялся.
|
||||||
|
|
||||||
|
## 1. Что сделано
|
||||||
|
|
||||||
|
### Этап 1. Реальные ошибки
|
||||||
|
|
||||||
|
| ID | Результат |
|
||||||
|
|---|---|
|
||||||
|
| U1 | Неверный пароль или OTP в `change-password` / `change-username` больше не разлогинивает: запросы `/auth/*` идут через отдельный клиент без перехватчика сессии (см. U13). Ошибка показывается тостом, окно остаётся открытым |
|
||||||
|
| U2 | `fetchCertificates` возвращает массив (иначе пустой); `Analytics.vue` читает его напрямую, панель Expiring и KPI заполняются. Сортировка без `\|\| 0` |
|
||||||
|
| U3 | Проверено по `APP_PROFILER/schemas.py` и `PUT /config/server`: схема `SystemSettingsUpdate` задаёт `vpn_netmask = 255.255.255.0` по умолчанию, поэтому при отсутствии поля **каждое сохранение молча сбрасывало маску в /24**, а подсеть другой длины не проходила проверку. Теперь UI отправляет `vpn_netmask` вместе с `vpn_network`. Разбор CIDR вынесен в `src/utils/cidr.js` (проверка октетов, суффикса 0-32, сплошной маски); без суффикса берётся текущая маска; неверный ввод даёт сообщение до запроса. Неиспользуемая переменная `suffix` убрана |
|
||||||
|
| U4 | `formatBytes`: `null`, `undefined`, `NaN`, отрицательные и бесконечные значения дают `0 B`; индекс единицы ограничен таблицей. `formatRate` не даёт `NaN` |
|
||||||
|
| U5 | Сортировка в `Certificates.vue` через `??`: сертификат с 0 дней больше не уходит в конец |
|
||||||
|
|
||||||
|
### Этап 2. Безопасность и поставка
|
||||||
|
|
||||||
|
| ID | Результат |
|
||||||
|
|---|---|
|
||||||
|
| U6 | `default.conf.template`: `X-Content-Type-Options`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, CSP (`default-src 'self'`, `style-src 'self' 'unsafe-inline'`, `img-src 'self' data:`, `font-src 'self' data:`, `connect-src 'self'`, `frame-ancestors 'none'`, `object-src 'none'`), `gzip`, `server_tokens off`; `/assets/` с `Cache-Control: public, max-age=31536000, immutable` и `404` для отсутствующих файлов; `index.html` и `config.json` с `Cache-Control: no-cache`; удалён лишний `proxy_pass_header Authorization`. Переменные `${OVP_*}` и nginx-переменные не затронуты. `add_header` в `location /assets/` повторяет заголовки безопасности (иначе nginx не наследует их из `server`) |
|
||||||
|
| U7 | `Dockerfile`: `npm ci`; добавлен `.dockerignore` (`node_modules`, `dist`, `.vscode`, `.git`, `*.bak`, `*.log`). Запуск nginx не от root **не сделан**: образ `nginx:alpine` рендерит шаблон в `/etc/nginx/conf.d` и слушает 80; непривилегированный вариант меняет образ и порт (compose публикует `:80`). Причина записана комментарием в `Dockerfile` |
|
||||||
|
| U8 | `v-html` заменён компонентом `StatusBadge.vue` (используется в `Certificates.vue` и `ProfileDetailsModal.vue`, логика статуса в одном месте). Токен остаётся в `localStorage`: **принятый риск** (см. раздел 3) |
|
||||||
|
|
||||||
|
### Этап 3. Чистка и дублирование
|
||||||
|
|
||||||
|
| ID | Результат |
|
||||||
|
|---|---|
|
||||||
|
| U9 | `composables/useTrafficChart.js`: понижение числа точек, подписи, цвета темы, конфиг Chart.js, жизненный цикл графика. `Analytics.vue` и `HistoryModal.vue` используют его (суммарно на 93 строки меньше) |
|
||||||
|
| U10 | `MutationObserver` вынесен в `useThemeObserver` (`composables/useTheme.js`), отключается в `onUnmounted`; в `Account.vue` наблюдатель и переменная `isDark` не использовались и удалены; `URL.revokeObjectURL` после скачивания профиля (через 1 с) |
|
||||||
|
| U11 | `ConfirmModal`: уникальный `id` через `useId()`; `confirm()` в `ServerManagement.vue` и `PKIConfig.vue` (Init, Clear) заменён на `ConfirmModal`; `Swal` в `Account.vue` заменён тостами, результаты 2FA (включено, отключено, ошибка) тоже тостами, `ConfirmModal` остался только для подтверждения отключения 2FA; `sweetalert2` удалён из зависимостей и `vite.config.js` |
|
||||||
|
| U12 | Удалены `Login.vue.bak` (`git rm`), глобальный перехватчик в `main.js` (инстансы `axios.create()` его не наследуют), `sass` (scss не использовался), `props` в `HistoryModal`, `id="themeIcon"`/`refreshIcon`, пустые `<p></p>` (отступ после заголовка секции сохранён правилом `.nav-section-header + .nav-link` в CSS), неиспользуемый `apiClient` в `Clients.vue`; `proccessData` -> `processData` |
|
||||||
|
| U13 | `authApiClient` (база `/api/auth`, выводится из `api_base_url` заменой `/v1` на `/auth`); хак `'../auth/...'` убран из `Login.vue` и `Account.vue` |
|
||||||
|
| U14 | Маршрут-ловушка `/:pathMatch(.*)*` с перенаправлением на `/` (гостя защита маршрутов отправит на вход); `Clients` грузится лениво, страница входа не тянет `chart.js`; `isAuthenticated` в `App.vue` определяется токеном и публичностью маршрута |
|
||||||
|
| U15 | `BaseModal`: размер через `computed`, убрано событие-дубль `close` (оставлено `closed`; `@close` нигде не использовался); `NewClientModal`: фокус по событию `opened`, проверка имени, кнопка неактивна при неверном имени; `HistoryModal.loadHistory`: счётчик запросов, устаревший ответ отбрасывается (и при закрытии окна) |
|
||||||
|
|
||||||
|
Тема (часть U17) сделана в этапе 3: `initTheme()` вызывается в `main.js` до монтирования приложения (без мигания), при первом запуске берётся `prefers-color-scheme`, дальше сохранённый выбор.
|
||||||
|
|
||||||
|
### Этап 4. Доступность и оформление
|
||||||
|
|
||||||
|
| ID | Результат |
|
||||||
|
|---|---|
|
||||||
|
| U16 | `Login.vue`: `label for`/`id`, `autocomplete="username"` / `"current-password"` / `"one-time-code"`, `inputmode="numeric"` и `aria-label` у кода 2FA (то же в `Account.vue`, плюс `new-password`); строки таблицы сертификатов фокусируются и открываются по Enter, ссылка клиента в `Clients.vue` получила `href="#"`, заголовки сортировки - `tabindex` и Enter |
|
||||||
|
| U17 | Единое имя «OpenVPN Controller» (вход, боковая панель, текст в Account, подвал), favicon `logo.svg` вместо `vite.svg` (файл удалён), тема по системной настройке |
|
||||||
|
| U18 | ESLint 10 с минимальной конфигурацией (`eslint.config.js`: recommended + `vue/flat/essential`, `npm run lint`, замечаний нет). `BackupRestore.vue` не разбивался (вынесено в отдельное изменение, как в плане) |
|
||||||
|
|
||||||
|
## 2. Что не сделано и почему
|
||||||
|
|
||||||
|
| Пункт | Причина |
|
||||||
|
|---|---|
|
||||||
|
| B4 (`disable-2fa` требует пароль) | Вне плана: решение владельца, затрагивает бэкенд |
|
||||||
|
| Разбиение `BackupRestore.vue` (803 строки) | По плану отдельное изменение |
|
||||||
|
| Запуск nginx не от root (U7) | См. выше: ломает схему образа и порт |
|
||||||
|
| Ручная проверка в браузере | Браузера на стенде нет (см. раздел 4) |
|
||||||
|
| `deploy/ui-dist` (закоммиченная сборка UI для системных служб) | Не обновлялась: `deploy/native/check-ui.sh` показывает `stale`. Нужно `deploy/native/build-ui.sh --publish` и коммит `deploy/ui-dist` (шаг мейнтейнера) |
|
||||||
|
|
||||||
|
## 3. Принятый риск: токен в localStorage
|
||||||
|
|
||||||
|
JWT хранится в `localStorage` (`ovpmon_token`). Любой XSS на странице может его прочитать. Меры, которые снижают риск: нет `v-html` с данными, CSP (`script-src 'self'`) в контейнерном nginx, `X-Frame-Options`. Переход на `HttpOnly`-cookie требует схемы cookie и защиты от CSRF на бэкенде (`APP_CORE`) и в этом изменении не делается.
|
||||||
|
|
||||||
|
## 4. Проверки
|
||||||
|
|
||||||
|
| Проверка | Результат |
|
||||||
|
|---|---|
|
||||||
|
| `npm ci --dry-run` (после обновления `package-lock.json`) | проходит |
|
||||||
|
| `npm run build` (Node 20, контейнер `node:20-alpine`) | проходит; главный чанк 249 -> 238 кБ, `vendor-ui` 162 -> 82 кБ, `chart.js` на странице входа не грузится |
|
||||||
|
| `npm test` (Vitest) | 3 файла, 13 тестов проходят: `formatBytes`/`formatRate` (U4), разбор CIDR (U3), клиент `/auth/*` не разлогинивает на 401, остальные разлогинивают (U1) |
|
||||||
|
| `npm run lint` | без замечаний |
|
||||||
|
| `docker build APP_UI` (временный образ, удалён) | собирается с `npm ci` |
|
||||||
|
| `nginx -t` с отрендеренным шаблоном (одноразовый контейнер из образа `nginx:alpine`, без обращения к рабочим контейнерам) | успешно |
|
||||||
|
| Заголовки (`curl -I` к одноразовому контейнеру с собранным `dist`, порт 127.0.0.1:18080, потом остановлен) | `/`, `/index.html`, `/config.json`, маршрут SPA: `Cache-Control: no-cache`, 4 заголовка безопасности; `/assets/*.js`: `immutable`, `Content-Encoding: gzip`, заголовки безопасности; несуществующий `/assets/nope.js`: 404 |
|
||||||
|
| Ручной проход в браузере (неверный пароль в Account, панель Expiring, смена маски, темы, модальные окна, клавиатура, CSP без нарушений в консоли) | **не выполнялся**: браузера нет. Остаётся для владельца. Риск CSP из плана (шрифты Font Awesome, inline-стили) проверен только по составу сборки: шрифты берутся из `/assets/`, `style-src` допускает inline |
|
||||||
|
|
||||||
|
## 4.1. Отклонения от плана
|
||||||
|
|
||||||
|
- Тема перенесена в этап 3 (общий файл `App.vue`).
|
||||||
|
- Имя клиента: `^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$` вместо `^[A-Za-z0-9_-]+$`: первый символ и длина совпадают с правилом профилировщика (`schemas.py`, `username`), точки не разрешены, как и в подсказке формы.
|
||||||
|
- `Cache-Control` для `/assets/` без `expires`, одной строкой `public, max-age=31536000, immutable`.
|
||||||
|
- Для U1 не использовано сопоставление текста ошибки токена («Token has expired»): при истёкшей сессии запрос `/auth/*` покажет ошибку, разлогинит следующий обычный запрос (смена маршрута вызывает `/user/me`).
|
||||||
|
- `eslint` 10 с `@eslint/js` и `globals`: выбрано, так как 9.x помечен в npm как неподдерживаемый.
|
||||||
|
|
||||||
|
## 5. Открытые вопросы
|
||||||
|
|
||||||
|
1. Нужен ли CSP `connect-src 'self'` во всех развёртываниях: если `config.json` указывает на другой origin API, его нужно добавить в `connect-src` (контейнерный шаблон).
|
||||||
|
2. Системные службы (`deploy/native/nginx/ovpmon.conf.template`) уже имеют свои заголовки без CSP и с `Cache-Control: no-store`; all-in-one использует `APP_UI/default.conf.template` (получил заголовки), его `Dockerfile` по-прежнему делает `npm install` (`deploy/allinone/Dockerfile`, не менялся).
|
||||||
|
3. Обновить `deploy/ui-dist` (см. раздел 2).
|
||||||
|
4. B4 и разбиение `BackupRestore.vue`.
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# Ревью фронта APP_UI: план исправлений (план, 2026-10-07)
|
||||||
|
|
||||||
|
Основание: ревью `APP_UI` (Vue 3, Vite, Bootstrap). Код не менялся; план делится на этапы, каждый можно выполнить и проверить отдельно.
|
||||||
|
|
||||||
|
## 1. Область
|
||||||
|
|
||||||
|
Входит: `APP_UI/` (код, `default.conf.template`, `Dockerfile`, `package.json`).
|
||||||
|
Не входит: изменения API бэкенда, кроме п. B4 (отдельное решение владельца).
|
||||||
|
|
||||||
|
## 2. Найденное и решение
|
||||||
|
|
||||||
|
### Этап 1. Реальные ошибки (приоритет высокий)
|
||||||
|
|
||||||
|
| ID | Проблема | Решение |
|
||||||
|
|---|---|---|
|
||||||
|
| U1 | Неверный `current_password` или OTP в `change-password` / `change-username` даёт HTTP 401 (`openvpn_api_v3.py:859, 909, 913`). Перехватчик `useApi.js` на любой 401 чистит токен и уходит на `/login`: пользователь разлогинен, ошибки не видит | В перехватчике не считать 401 истечением сессии для запросов `/auth/*` (кроме проверки токена). Бэкенд не меняем |
|
||||||
|
| U2 | `Analytics.vue`: `fetchCertificates` возвращает массив, код проверяет `res.success && Array.isArray(res.data)`; панель «Expiring» и KPI всегда пусты | Принимать массив; общий разбор ответа в `useApi` |
|
||||||
|
| U3 | `VPNConfig.vue`: суффикс CIDR отбрасывается, `vpn_netmask` в форме нет; смена маски не применяется | Преобразовывать CIDR в маску и отправлять `vpn_netmask` вместе с `vpn_network`; убрать неиспользуемую переменную |
|
||||||
|
| U4 | `formatBytes(null/undefined)` даёт «NaN undefined» | Защита: нечисло или отрицательное значение даёт «0 B» |
|
||||||
|
| U5 | `Certificates.vue`: `days_remaining \|\| 9999` отправляет сертификат с 0 днями в конец списка | Сравнение через `?? ` |
|
||||||
|
|
||||||
|
### Этап 2. Безопасность и поставка
|
||||||
|
|
||||||
|
| ID | Проблема | Решение |
|
||||||
|
|---|---|---|
|
||||||
|
| U6 | nginx без заголовков безопасности, gzip и кэширования ассетов; лишний `proxy_pass_header Authorization` | Добавить `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy`, CSP (разрешить `self`, `data:` для картинок, inline-стили Bootstrap/Chart.js), gzip; `Cache-Control` для `/assets/` (immutable) и `no-cache` для `index.html` и `config.json`; убрать лишнюю директиву |
|
||||||
|
| U7 | `Dockerfile`: `npm install`, нет `.dockerignore`, nginx от root | `npm ci`, `.dockerignore` (`node_modules`, `dist`, `.vscode`, `*.bak`); оставить базовый образ, если запуск не от root ломает шаблон конфигурации (решить при проверке) |
|
||||||
|
| U8 | Токен в `localStorage` и `v-html` в `Certificates.vue` | `v-html` заменить шаблоном (статусный бейдж как компонент). Хранение токена не меняем (требует cookie-схемы на бэкенде), фиксируем как принятый риск в `DOCS` |
|
||||||
|
|
||||||
|
### Этап 3. Чистка и устранение дублирования
|
||||||
|
|
||||||
|
| ID | Проблема | Решение |
|
||||||
|
|---|---|---|
|
||||||
|
| U9 | Дубль кода графиков в `Analytics.vue` и `HistoryModal.vue` (downsample, метки, цвета темы, конфиг Chart.js) | Composable `useTrafficChart` |
|
||||||
|
| U10 | `MutationObserver` в `Analytics.vue` и `Account.vue` не отключается; `URL.createObjectURL` не освобождается | `disconnect()` в `onUnmounted`; `revokeObjectURL` |
|
||||||
|
| U11 | Дубль `id="confirmModal"` при нескольких `ConfirmModal`; три способа подтверждения (`confirm()`, `ConfirmModal`, `Swal`); `ConfirmModal` как окно «Success» | Уникальный `id` (проп или счётчик); `confirm()` в Server и PKI заменить на `ConfirmModal`; `Swal` в Account заменить на тосты и `ConfirmModal`; удалить `sweetalert2` |
|
||||||
|
| U12 | Мёртвый код: глобальный перехватчик в `main.js` (инстансы `axios.create()` его не наследуют), `Login.vue.bak`, неиспользуемые `props` в `HistoryModal`, `id="themeIcon"`/`refreshIcon`, пустые `<p></p>`, `proccessData`, `sass` | Удалить; переименовать функцию |
|
||||||
|
| U13 | Хак `'../auth/login'` в `apiClient` | Отдельный инстанс `authApiClient` на `/api/auth` в `useApi` |
|
||||||
|
| U14 | Нет маршрута 404; `Clients` и `Login` грузятся статически и тянут `chart.js` на странице входа; `isAuthenticated` в `App.vue` зависит от имени маршрута | Catch-all маршрут (перенаправление на `/`); ленивая загрузка `Clients`; `isAuthenticated` по токену |
|
||||||
|
| U15 | `BaseModal`: `sizeClass` не реактивен, дубль `close`/`closed`; `NewClientModal`: фокус через `setTimeout(500)`, нет проверки имени; гонка в `HistoryModal.loadHistory` | Computed для размера; фокус по событию `opened`; проверка `^[A-Za-z0-9_-]+$`; игнорировать устаревший ответ |
|
||||||
|
|
||||||
|
### Этап 4. Доступность и оформление (низкий приоритет)
|
||||||
|
|
||||||
|
| ID | Проблема | Решение |
|
||||||
|
|---|---|---|
|
||||||
|
| U16 | Login: нет `for` у `label`, `autocomplete`, `inputmode`; кликабельные `<tr>` и `<a>` без клавиатуры | `autocomplete="username"/"current-password"/"one-time-code"`, `inputmode="numeric"`; `href`/`tabindex` и Enter для кликабельных элементов |
|
||||||
|
| U17 | Разные названия продукта, favicon Vite, подвал «Admin Dashboard», тема без `prefers-color-scheme` | Единое имя «OpenVPN Controller», свой favicon (`logo.svg`), тема по системной настройке при первом запуске, установка до монтирования (без мигания) |
|
||||||
|
| U18 | Нет линтера; `BackupRestore.vue` 803 строки | ESLint (минимальная конфигурация для Vue). Разбиение `BackupRestore.vue` вынести в отдельное изменение, здесь не делаем |
|
||||||
|
|
||||||
|
### Требует решения владельца (вне плана)
|
||||||
|
|
||||||
|
| ID | Вопрос |
|
||||||
|
|---|---|
|
||||||
|
| B4 | `POST /auth/disable-2fa` не требует пароля или OTP: украденная сессия отключает 2FA. Предлагается требовать `current_password` (и OTP). Затрагивает бэкенд (`APP_CORE`) и форму в `Account.vue` |
|
||||||
|
|
||||||
|
## 3. Порядок выполнения
|
||||||
|
|
||||||
|
1. Утвердить план. Субагент (Sonnet 5.5, Medium) пишет код по этапам 1-4, каждый этап отдельным коммитом.
|
||||||
|
2. Этап 1 и U6/U7: проверка сборкой (`npm run build`) и вручную в браузере (неверный пароль в Account, панель Expiring, смена маски, заголовки `curl -I`).
|
||||||
|
3. Этапы 3-4: сборка, ручной проход по всем страницам (темы, модальные окна, обновление данных, переходы между страницами без ошибок в консоли).
|
||||||
|
4. Сводка `2026-10-07_UI_Review_Fixes.md`, строка в `DOCS/Changes/README.md`, обновление `APP_UI/README.md` и `DOCS/UI`.
|
||||||
|
|
||||||
|
## 4. Тесты
|
||||||
|
|
||||||
|
Минимум (Vitest, добавляется в `devDependencies`): `useFormatters` (U4), разбор CIDR в маску (U3), перехватчик 401 для `/auth/*` (U1). Остальное: сборка и ручная проверка.
|
||||||
|
|
||||||
|
## 5. Риски
|
||||||
|
|
||||||
|
- CSP (U6) может блокировать inline-стили и шрифты Font Awesome: проверить в браузере, при необходимости `style-src 'unsafe-inline'`.
|
||||||
|
- Замена `Swal` (U11) меняет вид сообщений в Account: согласовать на ревью.
|
||||||
|
- U3 зависит от поведения `PUT /config/server`: перед правкой проверить, что частичная схема не сбрасывает `vpn_netmask`.
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Показ нескольких сессий клиента в UI (сводка, 2026-11-12)
|
||||||
|
|
||||||
|
План: [2026-11-12_Multi_Session_UI_PLAN.md](2026-11-12_Multi_Session_UI_PLAN.md)
|
||||||
|
|
||||||
|
## Что изменено
|
||||||
|
|
||||||
|
- `APP_CORE/openvpn_api_v3.py`, `get_current_stats`: один запрос к `active_sessions`, группировка по CN. В запись клиента добавлены `sessions_count` и `sessions` (адрес, начало в UTC, байты, МБ). Для отключённых клиентов `0` и `[]`; при отсутствии таблицы список пуст. Прежние поля не менялись, `/api/v1/stats` отдаёт новые поля без правок маршрута.
|
||||||
|
- `APP_UI/src/views/Clients.vue`: бейдж «×N» (кнопка, `aria-expanded`) при двух и более сессиях; «N devices» вместо одного адреса; раскрывающиеся строки сессий (адрес, начало, Down/Up в МБ), состояние раскрытия в `ref` переживает автообновление; KPI «Active Sessions» рядом с «Active Clients».
|
||||||
|
- `APP_UI/src/utils/sessions.js`: чистые функции `sessionsBadge`, `toggleExpanded`, `visibleSessions`.
|
||||||
|
- `deploy/ui-dist` пересобран (`deploy/native/build-ui.sh --docker --publish`), `SOURCE_HASH` обновлён.
|
||||||
|
- Документация: `DOCS/Core_Monitoring/API_Reference.md` (новые поля), `DOCS/UI/Architecture.md` (страница Clients), строка в `DOCS/Changes/README.md`.
|
||||||
|
- Сборщик, схема БД и миграции не менялись.
|
||||||
|
|
||||||
|
## Тесты (2 шт.)
|
||||||
|
|
||||||
|
- `APP_CORE/test_multi_session.py`: CN с двумя сессиями, CN с одной, отключённый CN; прежние поля без изменений.
|
||||||
|
- `APP_UI/src/utils/sessions.test.js`: бейдж только при `sessions_count > 1`, раскрытие и сворачивание.
|
||||||
|
|
||||||
|
## Проверки
|
||||||
|
|
||||||
|
`pytest` в `APP_CORE`: 19 passed. `npm test`: 15 passed. `npm run lint`: без замечаний. Сборка UI в контейнере прошла, `SOURCE_HASH` совпадает с исходниками.
|
||||||
|
|
||||||
|
## Отклонения от плана и ограничения
|
||||||
|
|
||||||
|
- UI-тест проверяет чистые функции, а не смонтированный компонент: `@vue/test-utils` в проекте нет, зависимость не добавлялась.
|
||||||
|
- API-тест вызывает `api.get_current_stats()` напрямую: маршрут закрыт JWT и лишь пробрасывает поля. Красный прогон на старом коде отдельно не делался.
|
||||||
|
- Видимой подписи «Show sessions» нет, только `title` и `aria-expanded`.
|
||||||
|
- Ручная проверка на стенде с двумя устройствами под одним CN (шаг 4 плана) **не выполнена**.
|
||||||
|
- Коммит не создан.
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
# Показ нескольких сессий клиента в UI (план, 2026-11-12)
|
||||||
|
|
||||||
|
Источник: анализ состояния проекта (запрос от 2026-11-12). Затронутый код: `APP_CORE/openvpn_api_v3.py`, `APP_UI/src/views/Clients.vue`, `APP_CORE/test_*.py`, `APP_UI/src/**/*.test.js`.
|
||||||
|
|
||||||
|
Цель: в списке клиентов видно, что пользователь (CN) подключён с нескольких устройств, и можно посмотреть параметры каждой сессии.
|
||||||
|
|
||||||
|
## 1. Исходное состояние
|
||||||
|
|
||||||
|
- Сборщик пишет по строке на сессию в `active_sessions` (адрес, байты, `connected_since`, `session_id`), таблица обновляется каждый тик.
|
||||||
|
- `/api/v1/stats` отдаёт одну запись на CN: статус `Active`/`Disconnected`, суммарные байты и скорость, `real_address` последней сессии.
|
||||||
|
- `/api/v1/sessions` отдаёт все активные сессии, но UI его не вызывает.
|
||||||
|
- В UI число сессий и список устройств не видны.
|
||||||
|
|
||||||
|
## 2. Решение
|
||||||
|
|
||||||
|
Расширить `/api/v1/stats`, а не добавлять второй запрос из UI: поллинг остаётся один, данные согласованы между собой.
|
||||||
|
|
||||||
|
| ID | Изменение | Результат |
|
||||||
|
|---|---|---|
|
||||||
|
| MU-1 | `get_current_stats`: один запрос к `active_sessions`, сессии группируются по `common_name`; в каждую запись клиента добавляются `sessions_count` (0 для отключённых) и `sessions` (адрес, `connected_since` в UTC, байты приёма и отправки) | API отдаёт число и список сессий вместе с клиентом |
|
||||||
|
| MU-2 | `Clients.vue`: бейдж «×N» рядом со статусом, если `sessions_count > 1`; в колонке адреса при N > 1 показывать «N devices» вместо одного адреса | многосессионность видна в списке |
|
||||||
|
| MU-3 | `Clients.vue`: по клику на бейдж раскрывается вложенная строка со списком сессий (адрес, начало, Down/Up в МБ), повторный клик скрывает; состояние раскрытия хранится в `ref` и переживает автообновление | детали по каждому устройству |
|
||||||
|
| MU-4 | KPI на странице Clients: рядом с `Active clients` показать общее число сессий (сумма `sessions_count`) | видна нагрузка по сессиям, а не только по пользователям |
|
||||||
|
|
||||||
|
Вне объёма: изменение сборщика, схемы БД, метрики `Concurrent Users (Peak)` на Analytics (она считает пользователей, это корректно), принудительное отключение сессии.
|
||||||
|
|
||||||
|
## 3. Шаги
|
||||||
|
|
||||||
|
| # | Шаг | Результат |
|
||||||
|
|---|---|---|
|
||||||
|
| 0 | Тест API (красный на текущем коде): две строки `active_sessions` у одного CN, одна у другого, ни одной у третьего | поведение зафиксировано |
|
||||||
|
| 1 | MU-1 в `openvpn_api_v3.py`; обратная совместимость: существующие поля не меняются, поля только добавляются; при отсутствии таблицы `active_sessions` `sessions = []` | тест из шага 0 зелёный |
|
||||||
|
| 2 | MU-2, MU-4 в `Clients.vue` | бейдж и счётчик |
|
||||||
|
| 3 | MU-3 в `Clients.vue` | раскрывающийся список |
|
||||||
|
| 4 | Сборка UI и пересборка `deploy/ui-dist` по принятой процедуре проекта; ручная проверка на стенде с двумя клиентами под одним CN | подтверждено в реальном UI |
|
||||||
|
| 5 | Документация: `DOCS/Core_Monitoring/API_Reference.md` (поля `sessions_count`, `sessions`), `DOCS/UI` (описание страницы Clients), README.md, строка в таблице `DOCS/Changes/README.md`, сводка `2026-11-12_Multi_Session_UI.md` | документация актуальна |
|
||||||
|
|
||||||
|
## 4. Автотесты (минимум, 2 шт.)
|
||||||
|
|
||||||
|
1. **API** (`pytest`, в `APP_CORE`): `/api/v1/stats` возвращает `sessions_count` и `sessions` для CN с двумя сессиями, `0` и пустой список для отключённого, прежние поля без изменений.
|
||||||
|
2. **UI** (`Vitest`): компонент показывает бейдж «×2» только при `sessions_count > 1` и раскрывает список сессий по клику.
|
||||||
|
|
||||||
|
## 5. Совместимость и риски
|
||||||
|
|
||||||
|
- Схема и сборщик не меняются, миграций нет. Откат: возврат кода API и UI.
|
||||||
|
- Новые поля только добавляются, другие потребители `/api/v1/stats` не затронуты.
|
||||||
|
- Размер ответа растёт на число активных сессий (десятки строк), на поллинг не влияет.
|
||||||
|
- `connected_since` хранится в UTC, в UI выводится так же, как другие даты на странице, формат единый.
|
||||||
|
- Между двумя тиками сборщика список сессий может отставать на один тик; для мониторинга это допустимо.
|
||||||
|
|
||||||
|
## 6. Порядок выполнения
|
||||||
|
|
||||||
|
1. Утверждение плана.
|
||||||
|
2. Реализация субагентом (Sonnet 5.5, Medium Effort): шаги 0-3.
|
||||||
|
3. Проверка: `pytest` в `APP_CORE`, `npm test` и ESLint в `APP_UI`, ручная проверка (шаг 4).
|
||||||
|
4. Документация и сводка (шаг 5).
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Суммаризация: доработки по итогам обновления ПРОД (2026-11-12)
|
||||||
|
|
||||||
|
План: [2026-11-12_Prod_Upgrade_Fixes_PLAN.md](2026-11-12_Prod_Upgrade_Fixes_PLAN.md). Источник: `prod_upgrade_findings.md`.
|
||||||
|
|
||||||
|
## Что сделано
|
||||||
|
|
||||||
|
| Шаг | Изменение | Файлы |
|
||||||
|
|-----|-----------|-------|
|
||||||
|
| 1 | `Query(None, enum=[...])` → `Optional[Literal["server", "pki"]] = Query(None)`; тест значений параметра (200 / 422) | `APP_PROFILER/routers/system.py`, `APP_PROFILER/test_config_section.py` |
|
||||||
|
| 2 | Закреплены `fastapi==0.143.3`, `starlette==1.8.0`, `uvicorn==0.54.0`, `pydantic==2.14.1`; в `APP_CORE` добавлены верхние границы по мажору | `APP_PROFILER/requirements.txt`, `APP_CORE/requirements.txt` |
|
||||||
|
| 3 | При отказе `wait_http` выводится лог связанных сервисов (API → свой сервис, nginx-проверки → все) | `deploy/native/lib.sh` |
|
||||||
|
| 4 | `OLD_VERSION`: `deploy.state` → `<prefix>/VERSION` → `unknown` | `deploy/native/update.sh` |
|
||||||
|
| 5 | `migrate.py`: подсказка `Hint:` про `OVPMON_*_DB_PATH`, если БД не найдена и `--db` не задан; коды возврата не менялись | `APP_CORE/migrate.py`, `APP_PROFILER/migrate.py` |
|
||||||
|
| 6 | Документация: `--source --no-pull`, фиксация зависимостей, `PIP_CONSTRAINT` | `DOCS/Deployment/System_Services/Operations.md`, `README.md`, `DOCS/Changes/README.md` |
|
||||||
|
| + | Починены два устаревших теста `test_server_process.py` (см. ниже) | `APP_PROFILER/test_server_process.py` |
|
||||||
|
|
||||||
|
## Проверка (ревью после субагента)
|
||||||
|
|
||||||
|
- Дифф сверен с планом: все шаги выполнены, лишних изменений нет. Имена переменных БД сверены с `APP_CORE/db.py` и `install.sh`.
|
||||||
|
- `bash -n` для `lib.sh` и `update.sh`: без ошибок.
|
||||||
|
- Тесты в `venv` проекта: `APP_CORE` 19 passed; `APP_PROFILER` 25 passed (после правки ниже).
|
||||||
|
- Тесты `APP_PROFILER` в чистом окружении с закреплённым набором (fastapi 0.143.3, starlette 1.8.0, uvicorn 0.54.0, pydantic 2.14.1): те же результаты до правки тестов. Закреплённый набор ставится и работает.
|
||||||
|
|
||||||
|
## Починка двух падавших тестов
|
||||||
|
|
||||||
|
`test_server_process.py::test_get_stats` и `::test_control_invalid` падали с 404 и до нашего изменения. Причина в самих тестах: они ходили на `/server/process/...` без префикса `/api` (роутер подключён с ним с первого коммита) и без подмены `verify_token` (иначе 401). Приложение работает правильно (на `/api/...` с токеном: 200 и 400). Исправлено: добавлен префикс `/api`, подмена `verify_token` и временная БД по образцу `test_pki_guard.py`; убран мёртвый блок `__main__` и `print`. Тест `stats` проверяет только форму ответа.
|
||||||
|
|
||||||
|
## Не проверено
|
||||||
|
|
||||||
|
- Вывод лога сервиса при реальном отказе health-check и расчёт `OLD_VERSION` на хосте с `deploy.state`: проверены только синтаксис и чтение кода, на живой установке не запускались.
|
||||||
|
- Верхние границы в `APP_CORE/requirements.txt` (`Flask-Cors<7`, `qrcode<9`, `bcrypt<6`) выбраны по текущим мажорам; сверить с набором на ПРОД.
|
||||||
|
|
||||||
|
## Вне объёма
|
||||||
|
|
||||||
|
- Команда «показать diff и применить» для ручных установок.
|
||||||
|
- Расследование повторов `Client disconnected` в логе gatherer.
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# План: доработки по результатам обновления ПРОД (2026-11-12)
|
||||||
|
|
||||||
|
Источник: `prod_upgrade_findings.md`. Статус: **ожидает утверждения**.
|
||||||
|
|
||||||
|
## Проверка находок по коду
|
||||||
|
|
||||||
|
| # | Находка | Статус в коде | Решение |
|
||||||
|
|---|---------|---------------|---------|
|
||||||
|
| 1 | `Query(..., enum=...)` падает на новом FastAPI; зависимости без версий | Подтверждено: единственное место `APP_PROFILER/routers/system.py:16`; `APP_PROFILER/requirements.txt` без версий, `APP_CORE` только `>=` | Исправить |
|
||||||
|
| 2 | Health-check не показывает причину отказа | Лог выводится только если сервис не `active`; при ошибке HTTP (`wait_http`) лога нет | Исправить |
|
||||||
|
| 3 | `OLD_VERSION == NEW_VERSION` в итоге | `OLD_VERSION` берётся из `$PREFIX/VERSION`, а не из `deploy.state` | Исправить + описать режим `--source --no-pull` в документации |
|
||||||
|
| 4a | `migrate.py --check` код 2 без окружения | Не ошибка: код 2 = «есть неприменённые миграции» (БД по умолчанию не существует) | Только понятное сообщение, когда БД не найдена |
|
||||||
|
| 4b | Нужен GNU tar | Уже есть: `check_gnu_tar` в `update.sh:271` | Не требуется |
|
||||||
|
| 4c | Ручная установка: diff шаблонов | Отдельная функция (новая команда) | Вне объёма, отдельное изменение |
|
||||||
|
| 4d | Повтор `Client disconnected` каждые ~20 с | Не расследовалось | Вне объёма, отдельное расследование |
|
||||||
|
|
||||||
|
## Шаги
|
||||||
|
|
||||||
|
1. **Совместимость профайлера.** `routers/system.py`: `Query(None, enum=[...])` → `Literal["server", "pki"]` (с сохранением значения по умолчанию `None`). Один тест на значения параметра (допустимое / недопустимое → 422).
|
||||||
|
2. **Фиксация зависимостей.**
|
||||||
|
- `APP_PROFILER/requirements.txt`: `fastapi==0.143.3`, `starlette==1.8.0`, `uvicorn==0.54.0`, `pydantic==2.14.1` (рабочий набор с ПРОД); остальные пакеты без изменений.
|
||||||
|
- `APP_CORE/requirements.txt`: добавить верхние границы по мажорной версии (`Flask>=3.0.0,<4` и т. д.).
|
||||||
|
- Прогнать тесты в `venv` на зафиксированном наборе.
|
||||||
|
3. **Диагностика health-check** (`deploy/native/lib.sh`): при отказе `wait_http` выводить `show_service_log` для сервиса, к которому относится проверка (monitoring API → `ovpmon-api`, profiler API → `ovpmon-profiler`; для nginx-проверок — все сервисы).
|
||||||
|
4. **Версия «до»** (`deploy/native/update.sh`): `OLD_VERSION` брать из `OVPMON_VERSION` в `deploy.state`, при отсутствии — из `$PREFIX/VERSION`.
|
||||||
|
5. **`migrate.py`** (оба компонента): если БД не существует и `--db` не задан, добавить в вывод подсказку про `OVPMON_*_DB_PATH` / `/etc/ovpmon/env`. Код возврата не меняется.
|
||||||
|
6. **Документация.** В `DOCS/Deployment` описать режим `--source --no-pull` (состояние git-каталога установки, `git reset --hard origin/main` с сохранением живого `config.ini`), фиксацию зависимостей и `PIP_CONSTRAINT`. Обновить `README.md` и `DOCS/Changes/README.md`.
|
||||||
|
|
||||||
|
## Исполнение
|
||||||
|
|
||||||
|
Код пишет субагент (Sonnet 5.5, Medium Effort) после утверждения плана. По завершении — файл `2026-11-12_Prod_Upgrade_Fixes.md` (суммаризация).
|
||||||
|
|
||||||
|
## Риски
|
||||||
|
|
||||||
|
- Закреплённые версии устареют: обновлять осознанно, проверкой тестами. Для Docker-образов набор тот же, пересборка подтянет его.
|
||||||
|
- Изменение `Literal` меняет схему OpenAPI (enum остаётся, формат корректнее).
|
||||||
@@ -20,3 +20,14 @@ Every change has a plan (`*_PLAN.md`) before it and a summary of what was done a
|
|||||||
| 2026-10-05 | Комплексный анализ кодовой базы на основе графа знаний: безопасность, корректность, архитектура, тесты, рекомендации P0-P2 | [plan](2026-10-05_Code_Review_PLAN.md) · [change](2026-10-05_Code_Review.md) · [отчёт](../code_review/2026-10-05_1607Z_Codebase_Analysis.md) |
|
| 2026-10-05 | Комплексный анализ кодовой базы на основе графа знаний: безопасность, корректность, архитектура, тесты, рекомендации P0-P2 | [plan](2026-10-05_Code_Review_PLAN.md) · [change](2026-10-05_Code_Review.md) · [отчёт](../code_review/2026-10-05_1607Z_Codebase_Analysis.md) |
|
||||||
| 2026-10-05 | Сборщик трафика: устойчивый цикл, остановка по сигналу, проверка целостности и свежести файла статуса, учёт сессий по времени их начала (BUG-02, BUG-03) | [plan](2026-10-05_Gatherer_Reliability_PLAN.md) · [change](2026-10-05_Gatherer_Reliability.md) |
|
| 2026-10-05 | Сборщик трафика: устойчивый цикл, остановка по сигналу, проверка целостности и свежести файла статуса, учёт сессий по времени их начала (BUG-02, BUG-03) | [plan](2026-10-05_Gatherer_Reliability_PLAN.md) · [change](2026-10-05_Gatherer_Reliability.md) |
|
||||||
| 2026-10-05 | Ключ подписи JWT без значения по умолчанию: Core и Profiler не запускаются при пустом, слабом или заимствованном из примера ключе; проверка в установщиках, `update.sh` выпускает ключ при необходимости (SEC-01) | [plan](2026-10-05_JWT_Secret_Fail_Closed_PLAN.md) · [change](2026-10-05_JWT_Secret_Fail_Closed.md) |
|
| 2026-10-05 | Ключ подписи JWT без значения по умолчанию: Core и Profiler не запускаются при пустом, слабом или заимствованном из примера ключе; проверка в установщиках, `update.sh` выпускает ключ при необходимости (SEC-01) | [plan](2026-10-05_JWT_Secret_Fail_Closed_PLAN.md) · [change](2026-10-05_JWT_Secret_Fail_Closed.md) |
|
||||||
|
| 2026-10-06 | Учёт нескольких сессий одного пользователя: ключ сессии по `Client ID` (устойчив к `float`), одна запись на CN за тик, скорость и история суммируются по сессиям (MS-1..MS-5); миграция 002 | [plan](2026-10-06_Multi_Session_Stats_PLAN.md) · [change](2026-10-06_Multi_Session_Stats.md) |
|
||||||
|
| 2026-10-07 | Шаблоны OpenVPN по мануалу 2.7: из клиентского профиля убраны `windows-driver`, `tls-client`, `user`/`group`, для udp добавлен `explicit-exit-notify`; из серверного убраны `tls-server`, дубль `# explicit-exit-notify`, строка `log` | [plan](2026-10-07_OVPN_Templates_PLAN.md) · [change](2026-10-07_OVPN_Templates.md) |
|
||||||
|
| 2026-10-07 | Резервное копирование и восстановление из UI и API (проход 1 из 3): пакет с базами, PKI и профилями, шифрование, назначения Local и S3, ротация, восстановление с миграцией и откатом, страница Backup and Restore | [plan](2026-10-07_Backup_Restore_PLAN.md) · [change](2026-10-07_Backup_Restore.md) · [guide](../Profiler_Management/Backup_Restore.md) |
|
||||||
|
| 2026-10-07 | Резервное копирование: замечания и дополнения: имя сервера и точное время UTC в имени пакета, назначения SFTP (закрепление отпечатка ключа хоста) и FTP/FTPS, миграции монитора в образе профилировщика (вариант B), ограничение частоты сообщений сборщика, раздел Backups в Security_Architecture | [plan](2026-10-07_Backup_Restore_Fixes_PLAN.md) · [change](2026-10-07_Backup_Restore_Fixes.md) · [guide](../Profiler_Management/Backup_Restore.md) |
|
||||||
|
| 2026-10-07 | Проверка скриптов установки и миграции на новом коде: проверка версии compose для варианта B (Docker Compose 2.17+), `ovpmon_backup.db` в резервной копии и восстановлении системных служб | [plan](2026-10-07_Deploy_Scripts_Check_PLAN.md) · [change](2026-10-07_Deploy_Scripts_Check.md) |
|
||||||
|
| 2026-10-07 | Ревью фронта: 401 на `/auth/*` не разлогинивает, панель Expiring, `vpn_netmask` при сохранении (раньше сбрасывалась в /24), заголовки безопасности и кэш в nginx, `npm ci`, общий код графиков, `ConfirmModal` и тосты вместо `confirm()`/SweetAlert2, отдельный клиент `/api/auth`, доступность, ESLint и Vitest | [plan](2026-10-07_UI_Review_Fixes_PLAN.md) · [change](2026-10-07_UI_Review_Fixes.md) |
|
||||||
|
| 2026-10-07 | Доставка UI: пересборка `deploy/ui-dist`, единый CSP с `OVPMON_CSP_CONNECT_EXTRA` (контейнеры и системный nginx, флаг `--csp-connect-extra`), `npm ci` в all-in-one, `app-ui` на `nginx-unprivileged` (порт 8080 внутри) | [plan](2026-10-07_UI_Delivery_Hardening_PLAN.md) · [change](2026-10-07_UI_Delivery_Hardening.md) |
|
||||||
|
| 2026-10-07 | Backup: бейджи Type, Status и Last result в таблице Destinations выровнены по верхнему краю строки (`align-top`), дата остаётся под бейджем | [plan](2026-10-07_Backup_Badges_Align_PLAN.md) · [change](2026-10-07_Backup_Badges_Align.md) |
|
||||||
|
| 2026-10-07 | Скорость (Mbps) на графиках за период больше суток: средняя скорость корзины из байтов агрегатных таблиц вместо нулей (история клиента и Analytics), подписи «RX/TX Mbps (avg)» | [plan](2026-10-07_Aggregated_Speed_PLAN.md) · [change](2026-10-07_Aggregated_Speed.md) |
|
||||||
|
| 2026-11-12 | Clients: несколько сессий одного пользователя видны в UI: бейдж «×N», «N devices» вместо адреса, раскрывающийся список сессий, KPI Active Sessions; `/api/v1/stats` отдаёт `sessions_count` и `sessions` | [plan](2026-11-12_Multi_Session_UI_PLAN.md) · [change](2026-11-12_Multi_Session_UI.md) |
|
||||||
|
| 2026-11-12 | Доработки по итогам обновления ПРОД: `Literal` вместо `Query(enum=)` в профайлере (совместимость с новым FastAPI), фиксация зависимостей, лог сервиса при отказе health-check, версия «до» из `deploy.state`, подсказка в `migrate.py`, документация `--source --no-pull` | [plan](2026-11-12_Prod_Upgrade_Fixes_PLAN.md) · [change](2026-11-12_Prod_Upgrade_Fixes.md) |
|
||||||
@@ -22,6 +22,7 @@ Provides aggregated trend data for the entire server. optimized for visualizatio
|
|||||||
* **7d**: Returns 105-minute intervals (1h 45m).
|
* **7d**: Returns 105-minute intervals (1h 45m).
|
||||||
* **30d**: Returns 450-minute intervals (7h 30m).
|
* **30d**: Returns 450-minute intervals (7h 30m).
|
||||||
* **Zero-Filling**: Missing data periods are automatically filled with zeros to ensure graph continuity.
|
* **Zero-Filling**: Missing data periods are automatically filled with zeros to ensure graph continuity.
|
||||||
|
* **Speed (`total_rx_rate`, `total_tx_rate`)**: for `24h` it is the peak of the summed rates over a point interval (raw `usage_history`). For `7d` and `30d` the source is `stats_hourly`, which keeps only bytes, so the rate is the **average** of an hourly bucket (`bytes * 8 / 1e6 / 3600`, Mbps), summed over clients; per point the maximum of the hourly averages is returned. Short peaks are smoothed out.
|
||||||
|
|
||||||
#### Example Response
|
#### Example Response
|
||||||
```json
|
```json
|
||||||
@@ -75,6 +76,8 @@ The API automatically selects the aggregation interval based on the requested ra
|
|||||||
|
|
||||||
*All short-term ranges (≤24h) include automatic **Zero-Filling**.*
|
*All short-term ranges (≤24h) include automatic **Zero-Filling**.*
|
||||||
|
|
||||||
|
**Speed fields.** For ranges up to 24h `bytes_received_rate_mbps` / `bytes_sent_rate_mbps` are the peak over the point interval (raw samples). The aggregate tables (`stats_5min`, `stats_15min`, `stats_hourly`, `stats_6h`, `stats_daily`) keep only bytes, so for longer ranges (and `resolution` other than `raw`) the fields are the **average speed of the bucket**: `bytes * 8 / 1e6 / bucket seconds` (300, 900, 3600, 21600, 86400). For the current incomplete bucket the duration is `min(bucket length, time since the bucket start)`, at least 1 second. The UI labels such series "RX Mbps (avg)" / "TX Mbps (avg)". If an aggregate table is missing, the API falls back to `usage_history` and returns real speeds.
|
||||||
|
|
||||||
#### Examples: Long-Term Aggregated Data
|
#### Examples: Long-Term Aggregated Data
|
||||||
|
|
||||||
To explicitly request data from long-term storage tables (skipping raw data), use the `resolution` parameter or specific ranges.
|
To explicitly request data from long-term storage tables (skipping raw data), use the `resolution` parameter or specific ranges.
|
||||||
@@ -136,6 +139,12 @@ Returns a snapshot of all known clients.
|
|||||||
|
|
||||||
### `GET /stats`
|
### `GET /stats`
|
||||||
|
|
||||||
|
Field notes (a user with several simultaneous sessions is one record):
|
||||||
|
- `current_recv_rate_mbps` / `current_sent_rate_mbps`: peak over the last 30 seconds of the **sum of the rates of all sessions** of the user at one tick (not the rate of a single session).
|
||||||
|
- `real_address`: the address of the session with the latest start. `last_bytes_received/sent` (table `clients`): the sum of the current counters of all active sessions. Per-session values are in `GET /sessions`.
|
||||||
|
- `sessions_count` and `sessions`: the active sessions of the user from `active_sessions` (`real_address`, `connected_since` in UTC, `bytes_received`, `bytes_sent`, `received_mb`, `sent_mb`). `0` and `[]` for a disconnected client or when the table is absent. The Clients page uses them for the "×N" badge and the list of devices.
|
||||||
|
- In `GET /stats/<common_name>` the history of every interval has the volume and the rate summed over the user's sessions (rate: `MAX` over the interval of the per-tick sum).
|
||||||
|
|
||||||
#### Example Response
|
#### Example Response
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -8,11 +8,11 @@ The gatherer runs a continuous loop (default interval: **10 seconds**).
|
|||||||
|
|
||||||
### A. Log Parsing
|
### A. Log Parsing
|
||||||
- **Source**: `/var/log/openvpn/openvpn-status.log` (Status File v2, CSV format).
|
- **Source**: `/var/log/openvpn/openvpn-status.log` (Status File v2, CSV format).
|
||||||
- **Target Fields**: `Common Name`, `Real Address`, `Bytes Sent`, `Bytes Received`, `Connected Since (time_t)`.
|
- **Target Fields**: `Common Name`, `Real Address`, `Bytes Sent`, `Bytes Received`, `Connected Since (time_t)`, `Client ID` (the column index is taken from the `HEADER,CLIENT_LIST,...` line; a missing column or a non-numeric value means no session id).
|
||||||
- **Filtering**: Only lines starting with `CLIENT_LIST`.
|
- **Filtering**: Only lines starting with `CLIENT_LIST`.
|
||||||
|
|
||||||
### B. Delta Calculation (`update_client_status_and_bytes`)
|
### B. Delta Calculation (`update_client_status_and_bytes`)
|
||||||
The log provides *lifetime* counters for a session. The gatherer calculates the traffic *delta* (increment) since the last check. A session is identified by the key `(common_name, real_address, connected_since_ts)`, where `connected_since_ts` is the `Connected Since (time_t)` column (index 8) of `CLIENT_LIST`. A reconnect always gets a new `connected_since_ts` and therefore a new session.
|
The log provides *lifetime* counters for a session. The gatherer calculates the traffic *delta* (increment) since the last check. A session is identified by the key `(common_name, session_id or real_address, connected_since_ts)`, where `session_id` is the `Client ID` of the status file (it does not change when the client address changes without a reconnect, `float`) and `connected_since_ts` is the `Connected Since (time_t)` column (index 8) of `CLIENT_LIST`. If the status has no `Client ID` (old OpenVPN), `real_address` is used instead. A reconnect always gets a new `connected_since_ts` and therefore a new session. `active_sessions.session_id` (TEXT, nullable, migration 2) stores the id; old snapshot rows without it match by the fallback key.
|
||||||
|
|
||||||
| Situation | Increment |
|
| Situation | Increment |
|
||||||
|-----------|-----------|
|
|-----------|-----------|
|
||||||
@@ -22,10 +22,12 @@ The log provides *lifetime* counters for a session. The gatherer calculates the
|
|||||||
| Not in cache, session older than the daemon and no snapshot (first start after an update, lost DB) | Baseline: increment `0`, a WARNING with the client name is logged (the only case of lost traffic, once per session). |
|
| Not in cache, session older than the daemon and no snapshot (first start after an update, lost DB) | Baseline: increment `0`, a WARNING with the client name is logged (the only case of lost traffic, once per session). |
|
||||||
| `connected_since_ts` is missing or not a number (non-standard status file) | Fallback heuristic: counters below 10 MB are counted as a new session, otherwise increment `0`; a WARNING is logged. |
|
| `connected_since_ts` is missing or not a number (non-standard status file) | Fallback heuristic: counters below 10 MB are counted as a new session, otherwise increment `0`; a WARNING is logged. |
|
||||||
|
|
||||||
|
**Several sessions of one user** (`duplicate-cn`): the increments of all sessions of a common name are added up and belong to one `clients` row. In `clients`, `real_address` is the address of the session with the latest start and `last_bytes_received/sent` is the **sum** of the current counters of all active sessions; per-session details stay in `active_sessions`. Before writing `usage_history` and the aggregates the sessions are collapsed into **one record per common name per tick** (sum of increments and of rates).
|
||||||
|
|
||||||
Cache changes are collected in a temporary structure and applied only after the database transaction is committed. If the transaction fails, the cache is unchanged and the next tick counts the difference for the whole interval.
|
Cache changes are collected in a temporary structure and applied only after the database transaction is committed. If the transaction fails, the cache is unchanged and the next tick counts the difference for the whole interval.
|
||||||
|
|
||||||
### B1. Read Validity, Grace Period, Restart and Shutdown
|
### B1. Read Validity, Grace Period, Restart and Shutdown
|
||||||
- **Validity** (`parse_status`): the status file must contain a `TITLE` line, a `TIME,<text>,<epoch>` line and end with `END`. A missing file, a read error or an incomplete file (read while OpenVPN rewrites it) makes the gatherer **skip the tick entirely**: the database and the cache are not touched, and the next valid tick counts the difference for the whole interval. After `status_invalid_max` (default 6) skipped ticks in a row the message is logged at ERROR level.
|
- **Validity** (`parse_status`): the status file must contain a `TITLE` line, a `TIME,<text>,<epoch>` line and end with `END`. A missing file, a read error or an incomplete file (read while OpenVPN rewrites it) makes the gatherer **skip the tick entirely**: the database and the cache are not touched, and the next valid tick counts the difference for the whole interval. The skip is logged on the first tick, at `status_invalid_max` (default 6, level ERROR) and then every 60th tick (about every 10 minutes at the default interval), not on every tick; when the file is readable again one INFO line says after how many skipped ticks.
|
||||||
- **Freshness**: if `TIME` is older than `status_stale_seconds` (default 60 s), OpenVPN is considered stopped: there are no clients, all clients become `Disconnected`, sessions leave the cache via the grace period. A valid, fresh file without `CLIENT_LIST` lines simply means no clients.
|
- **Freshness**: if `TIME` is older than `status_stale_seconds` (default 60 s), OpenVPN is considered stopped: there are no clients, all clients become `Disconnected`, sessions leave the cache via the grace period. A valid, fresh file without `CLIENT_LIST` lines simply means no clients.
|
||||||
- **Grace period**: a session missing from the status is not dropped at once. Its `missing_ticks` counter grows each tick and the session is removed from the cache when it reaches `session_grace_ticks` (default 3, about 30 s). A session that comes back with the same key continues without double counting. A removed session is remembered (last counters, 1 hour) so that a late return with the same key is still counted as a continuation.
|
- **Grace period**: a session missing from the status is not dropped at once. Its `missing_ticks` counter grows each tick and the session is removed from the cache when it reaches `session_grace_ticks` (default 3, about 30 s). A session that comes back with the same key continues without double counting. A removed session is remembered (last counters, 1 hour) so that a late return with the same key is still counted as a continuation.
|
||||||
- **Restart**: at start the gatherer loads `active_sessions` as the baseline (see the table above). `active_sessions.connected_since` stores the real session start in UTC (`YYYY-MM-DD HH:MM:SS`), which is also what `/sessions` returns.
|
- **Restart**: at start the gatherer loads `active_sessions` as the baseline (see the table above). `active_sessions.connected_since` stores the real session start in UTC (`YYYY-MM-DD HH:MM:SS`), which is also what `/sessions` returns.
|
||||||
@@ -34,7 +36,7 @@ Cache changes are collected in a temporary structure and applied only after the
|
|||||||
|
|
||||||
### C. Rate Calculation
|
### C. Rate Calculation
|
||||||
- **Speed**: Calculated as `Increment * 8 / (Interval * 1_000_000)` to get **Mbps**.
|
- **Speed**: Calculated as `Increment * 8 / (Interval * 1_000_000)` to get **Mbps**.
|
||||||
- **Storage**: Raw samples (10s resolution) including speed and volume are stored in the `usage_history` table.
|
- **Storage**: Raw samples (10s resolution) including speed and volume are stored in the `usage_history` table: one row per user per tick (the rate is the sum over the user's sessions). Rows written by earlier versions have one row per session; the API sums rows with the same `timestamp` before taking `MAX` over an interval.
|
||||||
|
|
||||||
## 2. Data Aggregation (TSDB)
|
## 2. Data Aggregation (TSDB)
|
||||||
|
|
||||||
@@ -49,6 +51,8 @@ To support long-term statistics without storing billions of rows, the `TimeSerie
|
|||||||
| `stats_6h` | **6 Hours** | 00:00, 06:00, 12:00... | 180 Days |
|
| `stats_6h` | **6 Hours** | 00:00, 06:00, 12:00... | 180 Days |
|
||||||
| `stats_daily` | **1 Day** | 00:00:00 | 365 Days |
|
| `stats_daily` | **1 Day** | 00:00:00 | 365 Days |
|
||||||
|
|
||||||
|
The aggregate tables hold only `bytes_received` / `bytes_sent`, no speed. For periods over 24 hours the API derives the **average speed** of a bucket from its bytes (`bytes * 8 / 1e6 / bucket seconds`; for the current incomplete bucket the time since its start is used); peaks are available only in `usage_history` (up to 24 hours).
|
||||||
|
|
||||||
**Logic**: Every 10s cycle, the calculated `Increment` is added to the sum of *all* relevant overlapping buckets. A single 5MB download contributes immediately to the current 5min, 15min, Hourly, 6h, and Daily counters simultaneously.
|
**Logic**: Every 10s cycle, the calculated `Increment` is added to the sum of *all* relevant overlapping buckets. A single 5MB download contributes immediately to the current 5min, 15min, Hourly, 6h, and Daily counters simultaneously.
|
||||||
|
|
||||||
## 3. Data Retention
|
## 3. Data Retention
|
||||||
|
|||||||
Loaded 100 of 152 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user