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.

Raise typed errors from the new auth checks

Juan Denisbd850adfb307
diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py
index 40a6338c..a18d860d 100644
--- a/backend/app/api/apps.py
+++ b/backend/app/api/apps.py
@@ -45,7 +45,9 @@ from app.services.upload_service import (
from app import paths
from app.middleware.rbac import get_current_user, require_admin_user
from app.error_reporting import unexpected_response
-from app.exceptions import field_required, not_found, permission_denied
+from app.exceptions import (
+ PermissionDeniedError, ValidationError, field_required, not_found, permission_denied,
+)
apps_bp = Blueprint('apps', __name__)
@@ -918,15 +920,16 @@ _HOST_BINDING_FIELDS = ('root_path', 'compose_file', 'systemd_unit', 'managed_by
@apps_bp.route('', methods=['POST'])
@jwt_required()
def create_app():
- current_user_id = get_jwt_identity()
+ user = get_current_user()
+ current_user_id = user.id
data = request.get_json()
if not data:
return jsonify({'error': 'No data provided'}), 400
host_fields = [f for f in _HOST_BINDING_FIELDS if data.get(f)]
- if host_fields and not User.query.get(current_user_id).is_admin:
- return jsonify({'error': f"Only an admin can set {', '.join(host_fields)}"}), 403
+ if host_fields and not user.is_admin:
+ raise PermissionDeniedError(f"Only an admin can set {', '.join(host_fields)}")
# The name becomes the nginx vhost name and its file path.
name = _service_slug(data.get('name'))
@@ -941,11 +944,10 @@ def create_app():
clash = app_name_clash_error(Application.query.filter_by(name=name).first(), name)
if clash:
- return jsonify({'error': clash}), 400
+ raise ValidationError(clash)
# Stamp the workspace (#33): the requested one (membership-checked) or the default.
from app.services.workspace_service import WorkspaceService
- user = User.query.get(current_user_id)
ws_id = WorkspaceService.resolve_workspace_id(
user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id'))
# Role reconciliation (#33): a workspace 'viewer' member has read-only access to
@@ -1327,16 +1329,15 @@ def update_app(app_id):
# untouched rather than half-updated in the session.
host_fields = [f for f in _HOST_BINDING_FIELDS if f in data]
if host_fields and not user.is_admin:
- return jsonify({'error': f"Only an admin can change {', '.join(host_fields)}"}), 403
+ raise PermissionDeniedError(f"Only an admin can change {', '.join(host_fields)}")
if 'name' in data and data['name'] != app.name:
if not data['name'] or _service_slug(data['name']) != data['name']:
- return jsonify({'error': 'Service name must be lowercase letters, digits and hyphens'}), 400
+ raise ValidationError('Service name must be lowercase letters, digits and hyphens')
clash = app_name_clash_error(
Application.query.filter_by(name=data['name']).first(), data['name'])
if clash:
- return jsonify({'error': clash}), 400
+ raise ValidationError(clash)
if 'deploy_settings' in data:
- from app.exceptions import ValidationError
from app.services import deploy_settings
_, error = deploy_settings.validate(data['deploy_settings'])
if error:
diff --git a/backend/app/api/servers.py b/backend/app/api/servers.py
index 67485740..67fddd7b 100644
--- a/backend/app/api/servers.py
+++ b/backend/app/api/servers.py
@@ -26,7 +26,9 @@ from app.services.discovery_service import discovery_service
from app.services import connection_string as connection_string_codec
from app.middleware.rbac import admin_required, auth_required, developer_required, get_current_user
from app.middleware.api_scope_middleware import require_scope
-from app.exceptions import ValidationError, agent_offline, field_required, not_found
+from app.exceptions import (
+ PermissionDeniedError, ValidationError, agent_offline, field_required, not_found,
+)
# Default token lifetime when the caller doesn't specify one. 7 days is
@@ -447,7 +449,7 @@ def set_server_workspace(server_id):
user = get_current_user()
server = _get_operable_server(server_id)
if server.workspace_id and not WorkspaceService.can_write_in_workspace(user, server.workspace_id):
- return jsonify({'error': "You have read-only access to this server's workspace"}), 403
+ raise PermissionDeniedError("You have read-only access to this server's workspace")
target = (request.get_json() or {}).get('workspace_id')
if target in (None, '', 'default'):
diff --git a/backend/app/api/two_factor.py b/backend/app/api/two_factor.py
index cfa1581e..335ec72a 100644
--- a/backend/app/api/two_factor.py
+++ b/backend/app/api/two_factor.py
@@ -15,7 +15,7 @@ from app.models import User
from app.services.totp_service import TOTPService, TwoFactorSetup
from app.services import auth_throttle_service
from app.utils.client_ip import get_client_ip
-from app.exceptions import not_found
+from app.exceptions import AuthenticationError, RateLimitedError, not_found
logger = logging.getLogger(__name__)
@@ -241,7 +241,7 @@ def verify_2fa_code():
# The lockout login enforces applies here too: failed codes count
# toward it, so it must also stop the guessing.
if user.is_locked:
- return jsonify({'error': 'Account is locked. Try again later.'}), 429
+ raise RateLimitedError('Account is locked. Try again later.')
jti = token_data.get('jti') or temp_token
normalized = str(code).replace(' ', '').replace('-', '')
@@ -250,7 +250,7 @@ def verify_2fa_code():
if (TOTPService.verify_code(user.totp_secret, code)
and _spend_once(('totp', user.id, normalized), _TOTP_REPLAY_SECONDS)):
if not _spend_once(('temp', jti), _TEMP_TOKEN_SECONDS):
- return jsonify({'error': 'Invalid or expired token'}), 401
+ raise AuthenticationError('Invalid or expired token')
# Success - issue real tokens
auth_throttle_service.reset(client_ip)
user.reset_failed_login()
@@ -270,7 +270,7 @@ def verify_2fa_code():
if matched_hash:
if not _spend_once(('temp', jti), _TEMP_TOKEN_SECONDS):
- return jsonify({'error': 'Invalid or expired token'}), 401
+ raise AuthenticationError('Invalid or expired token')
# Valid backup code - remove it (one-time use)
auth_throttle_service.reset(client_ip)
user.use_backup_code(matched_hash)
diff --git a/backend/app/exceptions.py b/backend/app/exceptions.py
index 3d64d0f3..2b43389b 100644
--- a/backend/app/exceptions.py
+++ b/backend/app/exceptions.py
@@ -69,6 +69,12 @@ class ConflictError(ApplicationError):
default_message = 'Resource conflict'
+class RateLimitedError(ApplicationError):
+ status_code = 429
+ code = 'rate_limited'
+ default_message = 'Too many requests'
+
+
class DependencyUnavailableError(ApplicationError):
status_code = 503
code = 'dependency_unavailable'
diff --git a/backend/tests/IDENTITY_DOOR_CEILING b/backend/tests/IDENTITY_DOOR_CEILING
index b5489e5e..38b10c1b 100644
--- a/backend/tests/IDENTITY_DOOR_CEILING
+++ b/backend/tests/IDENTITY_DOOR_CEILING
@@ -1 +1 @@
-69
+68
diff --git a/docs/MIGRATION_INVENTORY.md b/docs/MIGRATION_INVENTORY.md
index ec4fd02c..95cde31a 100644
--- a/docs/MIGRATION_INVENTORY.md
+++ b/docs/MIGRATION_INVENTORY.md
@@ -12,12 +12,12 @@ debt. Regenerate with `python scripts/generate-migration-inventory.py`.
| Concern | Door | Remaining | Ceiling | Policy |
|---|---|---:|---:|---|
-| Identity lookups outside rbac.get_current_user() | rbac.get_current_user() | 69 | 69 | JWT-only routes; the API-key-capable population is held at 0 by a companion assertion |
+| Identity lookups outside rbac.get_current_user() | rbac.get_current_user() | 68 | 68 | JWT-only routes; the API-key-capable population is held at 0 by a companion assertion |
| Routes on bare @jwt_required() | auth_required() / role decorators | 600 | 600 | REGISTERED EXCEPTION: JWT-only is the deliberate default; conversion grants API-key access and happens per route, on decision |
| HTTP statuses chosen by sniffing error text | typed errors from app.exceptions | 0 | 0 | INVARIANT at 0 - migration completed 2026-08-19 |
| API crashes swallowed without recording | app.error_reporting | 0 | 0 | INVARIANT at 0 |
| Hand-shaped {'error': ...} bodies in app/api | typed errors + the global handler | 850 | 850 | migrate when touched; new endpoints raise |
-| Raw subprocess calls outside the runners | app/utils/system.py runners | 24 | 24 | migrate when touched |
+| Raw subprocess calls outside the runners | app/utils/system.py runners | 23 | 23 | migrate when touched |
| Controller-boundary violations (routes doing service work) | service layer extraction | 491 | 491 | migrate when touched (first-wave ratchet) |
| raw api.* calls in pages/ | E1: useServerQuery/useServerMutation | 396 | 398 | migrate when touched |
| per-page toast.error extractions in pages/ | E1: query-layer error presentation | 200 | 206 | migrate when touched |