Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(backups): client-side encryption (opt-in, reuses the Fernet key)

Juan Denis007c4b984acf
diff --git a/backend/app/services/backup_service.py b/backend/app/services/backup_service.py
index 32f1d694..80209057 100644
--- a/backend/app/services/backup_service.py
+++ b/backend/app/services/backup_service.py
@@ -4,6 +4,7 @@ import subprocess
import shutil
import tarfile
import gzip
+import tempfile
from datetime import datetime, timedelta
from typing import Dict, List, Optional
from pathlib import Path
@@ -13,6 +14,7 @@ import uuid
import schedule
from app import paths
+from app.utils import backup_crypto
from app.utils.system import is_command_available
@@ -59,6 +61,7 @@ class BackupService:
return {
'enabled': False,
'retention_days': 30,
+ 'encrypt_backups': False,
'schedules': [],
'notifications': {
'on_success': False,
@@ -118,12 +121,18 @@ class BackupService:
backup_info['database_backup'] = db_backup['path']
backup_info['database_type'] = db_config.get('type')
+ # Encrypt the archive in place if configured (updates 'path'/'size').
+ # backup_info['path'] is the archive; the upload target is the dir.
+ backup_info['path'] = files_backup
+ cls._finalize_backup(files_backup, backup_info)
+ backup_info['files_backup'] = backup_info['path']
+
# Save backup metadata
meta_path = os.path.join(backup_dir, 'backup.json')
with open(meta_path, 'w') as f:
json.dump(backup_info, f, indent=2)
- # Auto-upload to remote if configured
+ # Auto-upload to remote if configured (whole directory)
cls._auto_upload(backup_dir, backup_info)
return {
@@ -226,6 +235,9 @@ class BackupService:
'remote_status': 'local'
}
+ # Encrypt in place if configured (updates backup_info path/size)
+ backup_path = cls._finalize_backup(backup_path, backup_info)
+
# Auto-upload to remote if configured
cls._auto_upload(backup_path, backup_info)
@@ -273,7 +285,10 @@ class BackupService:
'remote_status': 'local'
}
- # Save metadata alongside the archive
+ # Encrypt in place if configured (updates backup_info path/size)
+ backup_file = cls._finalize_backup(backup_file, backup_info)
+
+ # Save metadata alongside the archive (sidecar keyed off backup_name)
meta_path = os.path.join(cls.BACKUP_BASE_DIR, 'files', f'{backup_name}.json')
with open(meta_path, 'w') as f:
json.dump(backup_info, f, indent=2)
@@ -300,6 +315,7 @@ class BackupService:
if not os.path.exists(meta_path):
return {'success': False, 'error': 'Invalid backup: metadata not found'}
+ tmp_decrypted = None
try:
with open(meta_path, 'r') as f:
backup_info = json.load(f)
@@ -308,6 +324,9 @@ class BackupService:
if not files_backup or not os.path.exists(files_backup):
return {'success': False, 'error': 'Backup files not found'}
+ # Decrypt to a temp file first if the archive is encrypted
+ files_backup, tmp_decrypted = cls._resolve_for_restore(files_backup)
+
# Determine restore path
if not restore_path:
restore_path = f"/var/www/{backup_info['app_name']}"
@@ -330,6 +349,9 @@ class BackupService:
except Exception as e:
return {'success': False, 'error': str(e)}
+ finally:
+ if tmp_decrypted and os.path.exists(tmp_decrypted):
+ os.remove(tmp_decrypted)
@classmethod
def restore_database(cls, backup_path: str, db_type: str, db_name: str,
@@ -339,7 +361,11 @@ class BackupService:
if not os.path.exists(backup_path):
return {'success': False, 'error': 'Backup file not found'}
+ tmp_decrypted = None
try:
+ # Decrypt to a temp file first if the dump is encrypted
+ backup_path, tmp_decrypted = cls._resolve_for_restore(backup_path)
+
if db_type == 'mysql':
if not is_command_available('mysql'):
return {'success': False, 'error': 'mysql client not installed'}
@@ -383,6 +409,32 @@ class BackupService:
except Exception as e:
return {'success': False, 'error': str(e)}
+ finally:
+ if tmp_decrypted and os.path.exists(tmp_decrypted):
+ os.remove(tmp_decrypted)
+
+ @classmethod
+ def _resolve_for_restore(cls, backup_path: str):
+ """Return a (usable_path, tmp_to_cleanup) pair for restore.
+
+ If ``backup_path`` is an encrypted artifact (or a sibling ``.enc``
+ exists when the plaintext is gone), decrypt it to a temp file and return
+ that path plus the temp path to clean up. Otherwise the original path is
+ returned with ``None`` (nothing to clean up).
+ """
+ enc_path = None
+ if backup_crypto.is_encrypted_backup(backup_path):
+ enc_path = backup_path
+ elif not os.path.exists(backup_path) and os.path.exists(backup_path + backup_crypto.ENC_SUFFIX):
+ enc_path = backup_path + backup_crypto.ENC_SUFFIX
+
+ if not enc_path:
+ return backup_path, None
+
+ fd, tmp_path = tempfile.mkstemp(suffix='.restore')
+ os.close(fd)
+ backup_crypto.decrypt_file(enc_path, dest=tmp_path)
+ return tmp_path, tmp_path
@classmethod
def list_backups(cls, backup_type: str = None) -> List[Dict]:
@@ -614,6 +666,28 @@ class BackupService:
'remote_size_human': remote_stats.get('remote_size_human', '0 B')
}
+ @classmethod
+ def _finalize_backup(cls, path: str, backup_info: Dict) -> str:
+ """Encrypt the backup artifact in place when configured.
+
+ When ``encrypt_backups`` is enabled in config and an encryption key is
+ available, the artifact at ``path`` is Fernet-encrypted (the plaintext
+ is removed) and ``backup_info`` is updated to point at the encrypted
+ file. Returns the (possibly new) path so callers can hand it to
+ :meth:`_auto_upload`. A no-op (returns ``path`` unchanged) when
+ encryption is disabled or unavailable.
+ """
+ if cls.get_config().get('encrypt_backups') and backup_crypto.encryption_available():
+ enc_path = backup_crypto.encrypt_file(path)
+ backup_info['encrypted'] = True
+ backup_info['path'] = enc_path
+ if 'size' in backup_info:
+ backup_info['size'] = os.path.getsize(enc_path)
+ return enc_path
+
+ backup_info['encrypted'] = False
+ return path
+
@classmethod
def _auto_upload(cls, backup_path: str, backup_info: Dict) -> None:
"""Auto-upload backup to remote storage if configured."""
diff --git a/backend/app/utils/backup_crypto.py b/backend/app/utils/backup_crypto.py
new file mode 100644
index 00000000..8de9f7e2
--- /dev/null
+++ b/backend/app/utils/backup_crypto.py
@@ -0,0 +1,102 @@
+"""
+File-level backup encryption for ServerKit.
+
+Client-side encryption of backup artifacts (DB dumps, config archives, file
+bundles) using Fernet with the same ``SERVERKIT_ENCRYPTION_KEY`` that protects
+secrets at rest. Encrypting here means a backup is already ciphertext before it
+is auto-uploaded to remote storage, so the panel never trusts the remote with
+plaintext data.
+
+Reuses :mod:`app.utils.crypto` — no new crypto dependencies. Key loss means the
+encrypted backups are unrecoverable, so the key must be backed up out of band.
+"""
+
+import os
+
+from cryptography.fernet import Fernet
+
+from app.utils.crypto import get_encryption_key, is_encryption_configured
+
+# Suffix appended to an encrypted backup artifact.
+ENC_SUFFIX = '.enc'
+
+
+def encryption_available() -> bool:
+ """Return True when backup encryption can be performed.
+
+ Delegates to :func:`app.utils.crypto.is_encryption_configured`, i.e. true
+ only when ``SERVERKIT_ENCRYPTION_KEY`` is set. The derived development key
+ is intentionally not treated as "available" so dev backups are not silently
+ encrypted with a non-secret key.
+ """
+ return is_encryption_configured()
+
+
+def encrypt_file(path: str) -> str:
+ """Encrypt a file in place, returning the path of the encrypted artifact.
+
+ Reads the file bytes, Fernet-encrypts them, writes the ciphertext to
+ ``path + '.enc'``, removes the original plaintext file, and returns the new
+ path.
+
+ Note: this loads the entire file into memory. That is fine for typical
+ database dumps and config archives; streaming encryption for very large
+ archives is a follow-up.
+
+ Args:
+ path: Path to the plaintext file to encrypt.
+
+ Returns:
+ str: Path to the encrypted file (``path + '.enc'``).
+ """
+ f = Fernet(get_encryption_key())
+
+ with open(path, 'rb') as src:
+ data = src.read()
+
+ token = f.encrypt(data)
+
+ enc_path = path + ENC_SUFFIX
+ with open(enc_path, 'wb') as dst:
+ dst.write(token)
+
+ os.remove(path)
+ return enc_path
+
+
+def decrypt_file(path: str, dest: str = None) -> str:
+ """Decrypt a ``.enc`` backup file, returning the path of the plaintext.
+
+ Args:
+ path: Path to the encrypted ``.enc`` file.
+ dest: Optional destination path. If None, the trailing ``.enc`` is
+ stripped from ``path`` to form the destination.
+
+ Returns:
+ str: Path to the decrypted file.
+
+ Raises:
+ cryptography.fernet.InvalidToken: If the key is wrong or data corrupted.
+ """
+ if dest is None:
+ if path.endswith(ENC_SUFFIX):
+ dest = path[:-len(ENC_SUFFIX)]
+ else:
+ dest = path + '.dec'
+
+ f = Fernet(get_encryption_key())
+
+ with open(path, 'rb') as src:
+ token = src.read()
+
+ data = f.decrypt(token)
+
+ with open(dest, 'wb') as dst:
+ dst.write(data)
+
+ return dest
+
+
+def is_encrypted_backup(path: str) -> bool:
+ """Return True when ``path`` looks like an encrypted backup artifact."""
+ return bool(path) and path.endswith(ENC_SUFFIX)
diff --git a/backend/tests/test_backup_crypto.py b/backend/tests/test_backup_crypto.py
new file mode 100644
index 00000000..3e735d83
--- /dev/null
+++ b/backend/tests/test_backup_crypto.py
@@ -0,0 +1,190 @@
+"""Proving tests for client-side backup encryption.
+
+Backup artifacts can be Fernet-encrypted with ``SERVERKIT_ENCRYPTION_KEY`` before
+they ever touch remote storage. These tests prove:
+ (a) encrypt/decrypt round-trips the exact original bytes, replacing the
+ plaintext with a ``.enc`` artifact,
+ (b) a wrong key cannot decrypt (key loss = unrecoverable backups),
+ (c) ``encryption_available`` and ``is_encrypted_backup`` report correctly,
+ (d) BackupService.backup_files with encryption enabled writes an encrypted
+ artifact (unreadable as gzip) whose metadata records ``encrypted: True``,
+ (e) ``_finalize_backup`` is a no-op when encryption is disabled.
+
+A valid Fernet key for the env is produced with ``Fernet.generate_key()``.
+"""
+import gzip
+import json
+import os
+import tarfile
+
+import pytest
+from cryptography.fernet import Fernet, InvalidToken
+
+from app.utils import backup_crypto
+
+
+# ── file-level crypto primitives ────────────────────────────────────────────
+
+def test_encrypt_decrypt_roundtrip(tmp_path, monkeypatch):
+ monkeypatch.setenv('SERVERKIT_ENCRYPTION_KEY', Fernet.generate_key().decode())
+
+ src = tmp_path / 'dump.sql'
+ original = os.urandom(4096) + b'\n-- some sql --\n'
+ src.write_bytes(original)
+
+ enc_path = backup_crypto.encrypt_file(str(src))
+
+ # plaintext is gone, replaced by the .enc artifact
+ assert enc_path == str(src) + '.enc'
+ assert os.path.exists(enc_path)
+ assert not os.path.exists(str(src))
+ # ciphertext on disk is not the original bytes
+ assert open(enc_path, 'rb').read() != original
+
+ dec_path = backup_crypto.decrypt_file(enc_path)
+ assert dec_path == str(src) # trailing .enc stripped
+ assert os.path.exists(dec_path)
+ assert open(dec_path, 'rb').read() == original
+ # decrypt leaves the source .enc in place
+ assert os.path.exists(enc_path)
+
+
+def test_decrypt_to_explicit_dest(tmp_path, monkeypatch):
+ monkeypatch.setenv('SERVERKIT_ENCRYPTION_KEY', Fernet.generate_key().decode())
+
+ src = tmp_path / 'config.tar.gz'
+ src.write_bytes(b'payload-bytes')
+ enc_path = backup_crypto.encrypt_file(str(src))
+
+ dest = tmp_path / 'out.bin'
+ out = backup_crypto.decrypt_file(enc_path, dest=str(dest))
+ assert out == str(dest)
+ assert dest.read_bytes() == b'payload-bytes'
+
+
+def test_decrypt_with_wrong_key_raises(tmp_path, monkeypatch):
+ monkeypatch.setenv('SERVERKIT_ENCRYPTION_KEY', Fernet.generate_key().decode())
+
+ src = tmp_path / 'secret.sql'
+ src.write_bytes(b'sensitive backup contents')
+ enc_path = backup_crypto.encrypt_file(str(src))
+
+ # rotate to a different valid Fernet key -> decryption must fail
+ monkeypatch.setenv('SERVERKIT_ENCRYPTION_KEY', Fernet.generate_key().decode())
+ with pytest.raises(InvalidToken):
+ backup_crypto.decrypt_file(enc_path, dest=str(tmp_path / 'out.bin'))
+
+
+def test_encryption_available_reflects_env(monkeypatch):
+ monkeypatch.delenv('SERVERKIT_ENCRYPTION_KEY', raising=False)
+ assert backup_crypto.encryption_available() is False
+
+ monkeypatch.setenv('SERVERKIT_ENCRYPTION_KEY', Fernet.generate_key().decode())
+ assert backup_crypto.encryption_available() is True
+
+
+def test_is_encrypted_backup():
+ assert backup_crypto.is_encrypted_backup('/var/backups/db.sql.gz.enc') is True
+ assert backup_crypto.is_encrypted_backup('/var/backups/db.sql.gz') is False
+ assert backup_crypto.is_encrypted_backup('') is False
+
+
+# ── BackupService integration ───────────────────────────────────────────────
+
+def backup_dirs(tmp_path, monkeypatch):
+ """Point BackupService at a throwaway base/config dir and stub uploads."""
+ from app.services.backup_service import BackupService
+
+ base = tmp_path / 'backups'
+ cfg = tmp_path / 'config'
+ base.mkdir()
+ cfg.mkdir()
+
+ monkeypatch.setattr(BackupService, 'BACKUP_BASE_DIR', str(base))
+ monkeypatch.setattr(BackupService, 'CONFIG_DIR', str(cfg))
+ monkeypatch.setattr(BackupService, 'BACKUP_CONFIG', str(cfg / 'backups.json'))
+ # never reach out to remote storage in tests
+ monkeypatch.setattr(BackupService, '_auto_upload', classmethod(lambda cls, p, info: None))
+ return BackupService
+
+
+def test_backup_files_encrypts_artifact_and_metadata(backup_dirs, tmp_path, monkeypatch):
+ monkeypatch.setenv('SERVERKIT_ENCRYPTION_KEY', Fernet.generate_key().decode())
+ BackupService = backup_dirs
+
+ BackupService.save_config({'encrypt_backups': True})
+
+ # something to back up
+ payload = tmp_path / 'data.txt'
+ payload.write_text('hello world ' * 100)
+
+ res = BackupService.backup_files([str(payload)], backup_name='enc')
+ assert res['success'] is True
+
+ artifact = res['backup']['path']
+ assert artifact.endswith('.enc')
+ assert os.path.exists(artifact)
+ assert res['backup']['encrypted'] is True
+
+ # the artifact is NOT a readable gzip/tar until decrypted
+ with pytest.raises(Exception):
+ with tarfile.open(artifact, 'r:gz'):
+ pass
+
+ # metadata sidecar records encryption + the encrypted path.
+ # backup_name is suffixed with a timestamp; find the sidecar dynamically.
+ files_dir = os.path.join(BackupService.BACKUP_BASE_DIR, 'files')
+ sidecars = [f for f in os.listdir(files_dir) if f.endswith('.json')]
+ assert len(sidecars) == 1
+ meta = json.loads(open(os.path.join(files_dir, sidecars[0])).read())
+ assert meta['encrypted'] is True
+ assert meta['path'].endswith('.enc')
+
+ # decrypting yields a valid gzip tar again
+ dec = backup_crypto.decrypt_file(artifact)
+ with tarfile.open(dec, 'r:gz') as tar:
+ names = tar.getnames()
+ assert 'data.txt' in names
+
+
+def test_finalize_backup_noop_when_disabled(backup_dirs, tmp_path):
+ BackupService = backup_dirs
+ BackupService.save_config({'encrypt_backups': False})
+
+ f = tmp_path / 'plain.sql.gz'
+ f.write_bytes(b'not encrypted')
+ info = {'path': str(f), 'size': f.stat().st_size}
+
+ out = BackupService._finalize_backup(str(f), info)
+ assert out == str(f)
+ assert info['encrypted'] is False
+ assert os.path.exists(str(f))
+
+
+def test_finalize_backup_encrypts_when_enabled(backup_dirs, tmp_path, monkeypatch):
+ monkeypatch.setenv('SERVERKIT_ENCRYPTION_KEY', Fernet.generate_key().decode())
+ BackupService = backup_dirs
+ BackupService.save_config({'encrypt_backups': True})
+
+ f = tmp_path / 'plain.sql.gz'
+ f.write_bytes(b'db dump bytes')
+ info = {'path': str(f), 'size': f.stat().st_size}
+
+ out = BackupService._finalize_backup(str(f), info)
+ assert out.endswith('.enc')
+ assert info['encrypted'] is True
+ assert info['path'] == out
+ assert info['size'] == os.path.getsize(out)
+ assert not os.path.exists(str(f))
+
+
+def test_encrypt_backups_default_roundtrips_through_config(backup_dirs):
+ BackupService = backup_dirs
+ # default config exposes the flag (False)
+ assert BackupService.get_config()['encrypt_backups'] is False
+ # and it persists through save/get
+ cfg = BackupService.get_config()
+ cfg['encrypt_backups'] = True
+ BackupService.save_config(cfg)
+ assert BackupService.get_config()['encrypt_backups'] is True