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(models): EncryptedSecret descriptor; server.py stops swallowing encrypt failures (plan 77 C1)

Juan Denisa3f1cc9766dc
diff --git a/backend/app/models/mixins.py b/backend/app/models/mixins.py
index c03883ac..f04c1605 100644
--- a/backend/app/models/mixins.py
+++ b/backend/app/models/mixins.py
@@ -26,10 +26,13 @@ just deleted). Those constraints have to become PARTIAL unique indexes with a
`deleted_at IS NULL` predicate — supported by both SQLite (3.8+) and Postgres.
See migration 083 for the pattern.
"""
+import logging
from datetime import datetime
from app import db
+logger = logging.getLogger(__name__)
+
class SoftDeleteMixin:
"""Adds a tombstone (`deleted_at`) plus who did it, and restore/purge."""
@@ -79,3 +82,65 @@ class SoftDeleteMixin:
'deleted_by_id': self.deleted_by_id,
'is_active': self.is_active,
}
+
+
+class EncryptedSecret:
+ """Descriptor giving a model ONE way to handle a Fernet-encrypted column.
+
+ Usage::
+
+ class Server(db.Model):
+ api_secret_encrypted = db.Column(db.Text)
+ api_secret = EncryptedSecret('api_secret_encrypted')
+
+ server.api_secret = 'plaintext' # encrypts via utils/crypto — RAISES on failure
+ server.api_secret # decrypts; None when empty or undecryptable
+ Server.api_secret.is_set(server) # has-a-secret masking for to_dict()
+
+ Contracts (plan 77 C1):
+
+ - **Assignment raises on encrypt failure.** The historical hand-rolled
+ accessors caught the exception and ``print()``-ed it, silently storing
+ nothing — a data-loss path (an agent that "paired" but can never verify
+ a signature). A failed encrypt must fail the request that carried the
+ secret.
+ - **Read is tolerant.** A row written under a lost/rotated key returns
+ ``None`` (with a real log line, not print) so auth paths degrade the
+ same way they always have instead of 500ing every reader.
+ - Assigning ``None`` (or ``''``) clears the column.
+ """
+
+ def __init__(self, column_name: str):
+ self.column_name = column_name
+ self.attr_name = column_name # overwritten by __set_name__
+
+ def __set_name__(self, owner, name):
+ self.attr_name = f'{owner.__name__}.{name}'
+
+ def __get__(self, obj, objtype=None):
+ if obj is None:
+ return self
+ raw = getattr(obj, self.column_name)
+ if not raw:
+ return None
+ from app.utils.crypto import decrypt_secret
+ try:
+ return decrypt_secret(raw)
+ except Exception:
+ logger.warning(
+ "Failed to decrypt %s (wrong key or corrupt ciphertext); returning None",
+ self.attr_name, exc_info=True,
+ )
+ return None
+
+ def __set__(self, obj, value):
+ if value is None or value == '':
+ setattr(obj, self.column_name, None)
+ return
+ from app.utils.crypto import encrypt_secret
+ # No try/except: an encrypt failure must propagate, never be swallowed.
+ setattr(obj, self.column_name, encrypt_secret(value))
+
+ def is_set(self, obj) -> bool:
+ """True when ciphertext is stored — the `has_secret` masking flag."""
+ return bool(getattr(obj, self.column_name))
diff --git a/backend/app/models/server.py b/backend/app/models/server.py
index ab585ee8..6723fa13 100644
--- a/backend/app/models/server.py
+++ b/backend/app/models/server.py
@@ -3,6 +3,7 @@ import secrets
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from app import db
+from app.models.mixins import EncryptedSecret
from app.models.json_column_mixin import JsonColumnMixin
@@ -138,6 +139,12 @@ class Server(JsonColumnMixin, db.Model):
api_key_pending_hash = db.Column(db.String(256)) # Hash of pending new API key
api_key_pending_prefix = db.Column(db.String(12)) # Prefix of pending new API key
api_secret_pending_encrypted = db.Column(db.Text) # Encrypted pending new API secret
+
+ # One crypto path (plan 77 C1): descriptor-backed accessors over the
+ # *_encrypted columns. Encrypt failures RAISE (the old accessors printed
+ # and silently stored nothing — a data-loss path).
+ api_secret = EncryptedSecret('api_secret_encrypted')
+ api_secret_pending = EncryptedSecret('api_secret_pending_encrypted')
api_key_rotation_expires = db.Column(db.DateTime) # When pending key rotation expires
api_key_rotation_id = db.Column(db.String(36)) # Unique ID for current rotation
api_key_last_rotated = db.Column(db.DateTime) # Last successful rotation timestamp
@@ -206,24 +213,16 @@ class Server(JsonColumnMixin, db.Model):
return check_password_hash(self.api_key_hash, api_key)
def set_api_secret_encrypted(self, api_secret):
- """Encrypt and store the API secret for signature verification"""
- try:
- from app.utils.crypto import encrypt_secret
- self.api_secret_encrypted = encrypt_secret(api_secret)
- except Exception as e:
- print(f"Error encrypting API secret: {e}")
- # Don't fail - system can work without signature verification
+ """Encrypt and store the API secret for signature verification.
+
+ Raises if encryption fails — silently storing nothing would leave an
+ agent "paired" but unable to ever verify a signature.
+ """
+ self.api_secret = api_secret
def get_api_secret(self):
- """Decrypt and return the API secret"""
- if not self.api_secret_encrypted:
- return None
- try:
- from app.utils.crypto import decrypt_secret
- return decrypt_secret(self.api_secret_encrypted)
- except Exception as e:
- print(f"Error decrypting API secret: {e}")
- return None
+ """Decrypt and return the API secret (None if unset/undecryptable)."""
+ return self.api_secret
def get_pending_api_secret(self):
"""Decrypt and return the pending API secret used during key rotation.
@@ -233,14 +232,7 @@ class Server(JsonColumnMixin, db.Model):
window can have its signature verified against the right secret.
Returns None when there is no pending secret or it can't be decrypted.
"""
- if not self.api_secret_pending_encrypted:
- return None
- try:
- from app.utils.crypto import decrypt_secret
- return decrypt_secret(self.api_secret_pending_encrypted)
- except Exception as e:
- print(f"Error decrypting pending API secret: {e}")
- return None
+ return self.api_secret_pending
def start_key_rotation(self):
"""
@@ -257,11 +249,7 @@ class Server(JsonColumnMixin, db.Model):
self.api_key_pending_hash = generate_password_hash(new_api_key)
self.api_key_pending_prefix = new_api_key[:12] if len(new_api_key) >= 12 else new_api_key
- try:
- from app.utils.crypto import encrypt_secret
- self.api_secret_pending_encrypted = encrypt_secret(new_api_secret)
- except Exception as e:
- print(f"Error encrypting pending API secret: {e}")
+ self.api_secret_pending = new_api_secret
self.api_key_rotation_id = rotation_id
self.api_key_rotation_expires = datetime.utcnow() + timedelta(minutes=5)
diff --git a/backend/tests/test_encrypted_secret.py b/backend/tests/test_encrypted_secret.py
new file mode 100644
index 00000000..1f84e9d4
--- /dev/null
+++ b/backend/tests/test_encrypted_secret.py
@@ -0,0 +1,87 @@
+"""Plan 77 C1 — the EncryptedSecret descriptor is the one crypto path for
+model-owned ``*_encrypted`` columns.
+
+Contracts proven here:
+- round-trip: assignment encrypts (ciphertext lands in the backing column,
+ not plaintext), read decrypts.
+- an ENCRYPT failure raises — never swallowed, never silently stored as
+ nothing (the historical server.py accessor printed and dropped the secret).
+- a DECRYPT failure (wrong key / corrupt ciphertext) returns None so auth
+ paths degrade instead of 500ing.
+- ``is_set`` provides the has_secret masking flag without decrypting.
+"""
+import pytest
+
+import app.utils.crypto as crypto
+from app.models.mixins import EncryptedSecret
+from app.models.server import Server
+
+
+class _Box:
+ """Plain object with a backing attribute — descriptor works on any class."""
+ secret_encrypted = None
+ secret = EncryptedSecret('secret_encrypted')
+
+
+def test_round_trip_encrypts_backing_column(app):
+ box = _Box()
+ box.secret = 'hunter2'
+ assert box.secret_encrypted, 'ciphertext must be stored'
+ assert box.secret_encrypted != 'hunter2', 'plaintext must never be stored'
+ assert box.secret == 'hunter2'
+
+
+def test_assigning_none_clears_column(app):
+ box = _Box()
+ box.secret = 'hunter2'
+ box.secret = None
+ assert box.secret_encrypted is None
+ assert box.secret is None
+
+
+def test_encrypt_failure_raises(app, monkeypatch):
+ def boom(_):
+ raise RuntimeError('no key material')
+ monkeypatch.setattr(crypto, 'encrypt_secret', boom)
+ box = _Box()
+ with pytest.raises(RuntimeError):
+ box.secret = 'hunter2'
+ assert box.secret_encrypted is None, 'a failed encrypt must not store anything'
+
+
+def test_decrypt_failure_returns_none(app):
+ box = _Box()
+ box.secret_encrypted = 'not-real-fernet-ciphertext'
+ assert box.secret is None
+
+
+def test_is_set_masks_without_decrypting(app):
+ box = _Box()
+ assert _Box.secret.is_set(box) is False
+ box.secret = 'hunter2'
+ assert _Box.secret.is_set(box) is True
+
+
+def test_server_accessors_ride_the_descriptor(app, monkeypatch):
+ """server.py's legacy method names delegate to the descriptor: encrypt
+ failures now RAISE out of set_api_secret_encrypted (regression: they were
+ print()-swallowed, silently leaving the server secretless)."""
+ server = Server(name='c1', agent_id='agent-c1')
+ server.set_api_secret_encrypted('s3cret')
+ assert server.api_secret_encrypted != 's3cret'
+ assert server.get_api_secret() == 's3cret'
+
+ def boom(_):
+ raise RuntimeError('no key material')
+ monkeypatch.setattr(crypto, 'encrypt_secret', boom)
+ with pytest.raises(RuntimeError):
+ server.set_api_secret_encrypted('other')
+
+
+def test_server_key_rotation_round_trip(app):
+ server = Server(name='c1-rot', agent_id='agent-c1-rot')
+ key, secret, rotation_id = server.start_key_rotation()
+ assert server.get_pending_api_secret() == secret
+ assert server.complete_key_rotation(rotation_id) is True
+ assert server.get_api_secret() == secret
+ assert server.get_pending_api_secret() is None