Files
OpenVPN-Monitoring-Simple/APP_PROFILER/routers/backup.py
T

218 lines
8.2 KiB
Python
Raw Normal View History

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)