Backup and Restore: packages, Local/S3/SFTP/FTP destinations, UI and API

Encrypted packages (databases, PKI, client profiles) with safe restore and
a pre-restore safety copy, usable for server-to-server migration across
container and system-service installs. New Management page, ovp_backups
volume, migrations code in the profiler image, server name in package names.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ayurishchevandClaude Sonnet 5.5 committed 2026-10-07 09:38:09 +03:00
1 parent d29c261347
commit f8cdcd0fc6
55 files changed
+4401 -37

No files matched your search

+218
View File
@@ -0,0 +1,218 @@
import re
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from utils.auth import verify_token
from services.backup import BackupError, Busy, Invalid, destinations, engine, package, store
router = APIRouter(dependencies=[Depends(verify_token)])
NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9 _.-]{0,63}$")
PASSPHRASE_MIN = 8
class SettingsUpdate(BaseModel):
passphrase: Optional[str] = Field(None, max_length=256) # set or change; never returned
clear_passphrase: bool = False
default_retention: Optional[int] = Field(None, ge=1, le=1000)
server_name: Optional[str] = Field(None, max_length=63) # '' clears it (fallback names are used)
class DestinationIn(BaseModel):
name: str = Field(..., max_length=64)
type: str = Field(..., max_length=20)
enabled: bool = True
retention_count: Optional[int] = Field(None, ge=1, le=1000)
params: dict = {}
secrets: dict = {} # absent, empty or masked values keep the stored secret
class TrustIn(BaseModel):
fingerprint: str = Field(..., max_length=80) # the one shown by Test
class RunIn(BaseModel):
destination_ids: Optional[list[int]] = None
class RestoreIn(BaseModel):
destination_id: int
package: str = Field(..., max_length=200)
passphrase: Optional[str] = Field(None, max_length=256)
def _fail(e: Exception):
"""BackupError family -> HTTP error. Messages never contain secrets."""
if isinstance(e, Busy):
raise HTTPException(status_code=409, detail=str(e))
if isinstance(e, destinations.DestinationError):
raise HTTPException(status_code=502, detail=str(e))
raise HTTPException(status_code=400, detail=str(e))
def _types_info():
return [{"id": t, "label": cls.label, "remote": t in destinations.REMOTE_TYPES, "fields": cls.FIELDS,
"pins_host_key": bool(cls.PIN_PARAMS)}
for t, cls in destinations.DESTINATION_TYPES.items()]
@router.get("/backup/settings")
def get_settings():
effective, source = engine.effective_server_name()
return {
"encryption_enabled": store.has_passphrase(),
"default_retention": store.default_retention(),
"server_name": store.get_server_name(),
"effective_server_name": effective,
"server_name_source": source,
"local_root": destinations.local_root(),
"types": _types_info(),
}
@router.put("/backup/settings")
def update_settings(body: SettingsUpdate):
if engine.is_running():
raise HTTPException(status_code=409, detail="A backup or restore is running")
if body.passphrase is not None and body.clear_passphrase:
raise HTTPException(status_code=400, detail="Give a passphrase or clear it, not both")
server_name = (body.server_name or "").strip()
if server_name and not package.SERVER_NAME_RE.match(server_name):
raise HTTPException(status_code=400, detail="Server name: 1-63 letters, digits, '.' or '-', "
"starting with a letter or digit")
if body.passphrase is not None:
if len(body.passphrase) < PASSPHRASE_MIN:
raise HTTPException(status_code=400, detail=f"Passphrase must have at least {PASSPHRASE_MIN} characters")
store.set_passphrase(body.passphrase)
if body.clear_passphrase:
remote = [d["name"] for d in store.list_destinations()
if d["enabled"] and d["type"] in destinations.REMOTE_TYPES]
if remote:
raise HTTPException(status_code=400, detail="Remote destinations need a passphrase: disable or "
f"delete them first ({', '.join(remote)})")
store.set_passphrase(None)
if body.default_retention is not None:
store.set_default_retention(body.default_retention)
if body.server_name is not None:
store.set_server_name(server_name)
return get_settings()
@router.get("/backup/destinations")
def list_destinations():
return store.list_destinations()
def _prepare(body: DestinationIn, previous: Optional[dict]):
cls = destinations.DESTINATION_TYPES.get(body.type)
if cls is None:
raise HTTPException(status_code=400, detail=f"Unsupported destination type: {body.type}")
name = body.name.strip()
if not NAME_RE.match(name):
raise HTTPException(status_code=400, detail="Name: 1-64 letters, digits, spaces, '.', '_' or '-'")
same_type = bool(previous and previous["type"] == body.type)
# Secrets of another type never carry over
keep = previous["secrets"] if same_type else {}
given = {k: v for k, v in body.secrets.items() if isinstance(v, str) and v and v != store.MASK}
# A pinned host key comes only from the trust call, never from the client
client_params = {k: v for k, v in body.params.items() if k not in cls.PIN_PARAMS}
try:
params, secrets = cls.validate(client_params, given, keep)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
if same_type and cls.PIN_PARAMS:
old = previous["params"]
if all(old.get(k) == params.get(k) for k in cls.PIN_DEPENDS): # same server: the pin stays
params.update({k: old[k] for k in cls.PIN_PARAMS if old.get(k)})
retention = body.retention_count or (previous["retention_count"] if previous else store.default_retention())
return name, params, secrets, retention
@router.post("/backup/destinations", status_code=201)
def create_destination(body: DestinationIn):
name, params, secrets, retention = _prepare(body, None)
try:
dest_id = store.save_destination(None, name, body.type, body.enabled, retention, params, secrets)
except BackupError as e:
raise HTTPException(status_code=409, detail=str(e))
return store.get_destination(dest_id)
@router.put("/backup/destinations/{dest_id}")
def update_destination(dest_id: int, body: DestinationIn):
if engine.is_running():
raise HTTPException(status_code=409, detail="A backup or restore is running")
previous = store.get_destination(dest_id, with_secrets=True)
if not previous:
raise HTTPException(status_code=404, detail="Destination not found")
name, params, secrets, retention = _prepare(body, previous)
try:
store.save_destination(dest_id, name, body.type, body.enabled, retention, params, secrets)
except BackupError as e:
raise HTTPException(status_code=409, detail=str(e))
return store.get_destination(dest_id)
@router.delete("/backup/destinations/{dest_id}")
def delete_destination(dest_id: int):
if engine.is_running():
raise HTTPException(status_code=409, detail="A backup or restore is running")
if not store.delete_destination(dest_id):
raise HTTPException(status_code=404, detail="Destination not found")
return {"message": "Destination deleted"}
@router.post("/backup/destinations/{dest_id}/test")
def test_destination(dest_id: int):
try:
return engine.test_destination(dest_id)
except BackupError as e:
_fail(e)
@router.post("/backup/destinations/{dest_id}/trust-host-key")
def trust_host_key(dest_id: int, body: TrustIn):
if engine.is_running():
raise HTTPException(status_code=409, detail="A backup or restore is running")
try:
return engine.trust_host_key(dest_id, body.fingerprint.strip())
except BackupError as e:
_fail(e)
@router.get("/backup/destinations/{dest_id}/packages")
def list_packages(dest_id: int):
try:
return {"packages": engine.list_packages(dest_id)}
except BackupError as e:
_fail(e)
@router.post("/backup/run", status_code=202)
def run_backup(body: RunIn = RunIn()):
try:
engine.start_backup(body.destination_ids)
except BackupError as e:
_fail(e)
return {"state": "running"}
@router.post("/backup/restore", status_code=202)
def run_restore(body: RestoreIn):
try:
engine.start_restore(body.destination_id, body.package, body.passphrase)
except BackupError as e:
_fail(e)
return {"state": "running"}
@router.get("/backup/status")
def get_status():
return engine.status()
@router.get("/backup/history")
def get_history(limit: int = Query(20, ge=1, le=100)):
return store.history_list(limit)
+4 -3
View File
@@ -4,6 +4,7 @@ from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
from database import get_db
from utils.auth import verify_token
from utils.guards import forbid_during_restore
from models import UserProfile
from schemas import UserProfile as UserProfileSchema, UserProfileCreate, UserProfileNoteUpdate
from services import pki, generator
@@ -69,7 +70,7 @@ def list_profiles(db: Session = Depends(get_db)):
return updated_profiles
@router.post("/profiles", response_model=UserProfileSchema)
@router.post("/profiles", response_model=UserProfileSchema, dependencies=[Depends(forbid_during_restore)])
def create_profile(
profile_in: UserProfileCreate,
db: Session = Depends(get_db)
@@ -123,7 +124,7 @@ def create_profile(
db.refresh(new_profile)
return new_profile
@router.put("/profiles/{profile_id}/note", response_model=UserProfileSchema)
@router.put("/profiles/{profile_id}/note", response_model=UserProfileSchema, dependencies=[Depends(forbid_during_restore)])
def update_profile_note(profile_id: int, body: UserProfileNoteUpdate, db: Session = Depends(get_db)):
profile = db.query(UserProfile).filter(UserProfile.id == profile_id).first()
if not profile:
@@ -134,7 +135,7 @@ def update_profile_note(profile_id: int, body: UserProfileNoteUpdate, db: Sessio
db.refresh(profile)
return profile
@router.delete("/profiles/{profile_id}")
@router.delete("/profiles/{profile_id}", dependencies=[Depends(forbid_during_restore)])
def revoke_profile(profile_id: int, db: Session = Depends(get_db)):
profile = db.query(UserProfile).filter(UserProfile.id == profile_id).first()
if not profile:
+2 -1
View File
@@ -4,13 +4,14 @@ from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from utils.auth import verify_token
from utils.guards import forbid_during_restore
from services import generator, process, config, pki
logger = logging.getLogger(__name__)
router = APIRouter(dependencies=[Depends(verify_token)])
@router.post("/server/configure")
@router.post("/server/configure", dependencies=[Depends(forbid_during_restore)])
def configure_server(db: Session = Depends(get_db)):
try:
pki.require_server_ready(db)
+2 -1
View File
@@ -4,6 +4,7 @@ from services import process, pki
from database import get_db
from sqlalchemy.orm import Session
from utils.auth import verify_token
from utils.guards import forbid_during_restore
from typing import Optional
from fastapi import Depends
@@ -22,7 +23,7 @@ class ProcessStats(BaseModel):
memory_mb: float
uptime: Optional[str] = None
@router.post("/server/process/{action}", response_model=ProcessActionResponse)
@router.post("/server/process/{action}", response_model=ProcessActionResponse, dependencies=[Depends(forbid_during_restore)])
def manage_process(action: str, db: Session = Depends(get_db)):
"""
Control the OpenVPN server process.
+4 -3
View File
@@ -2,6 +2,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from database import get_db
from utils.auth import verify_token
from utils.guards import forbid_during_restore
from schemas import (
ConfigResponse, SystemSettings, PKISetting,
SystemSettingsUpdate, PKISettingUpdate
@@ -22,14 +23,14 @@ def get_config(
response.pki = config.get_pki_settings(db)
return response
@router.put("/config/server", response_model=SystemSettings)
@router.put("/config/server", response_model=SystemSettings, dependencies=[Depends(forbid_during_restore)])
def update_server_config(
settings: SystemSettingsUpdate,
db: Session = Depends(get_db)
):
return config.update_system_settings(db, settings)
@router.put("/config/pki", response_model=PKISetting)
@router.put("/config/pki", response_model=PKISetting, dependencies=[Depends(forbid_during_restore)])
def update_pki_config(
settings: PKISettingUpdate,
db: Session = Depends(get_db)
@@ -48,7 +49,7 @@ def init_system_pki(db: Session = Depends(get_db)):
def get_init_status(db: Session = Depends(get_db)):
return pki.init_status(db)
@router.delete("/system/pki")
@router.delete("/system/pki", dependencies=[Depends(forbid_during_restore)])
def clear_system_pki(db: Session = Depends(get_db)):
if pki.is_init_running():
raise HTTPException(status_code=409, detail="PKI initialization is running")