252 lines
9.4 KiB
Python
252 lines
9.4 KiB
Python
"""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]
|