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.

Drop route try/excepts the 500 handler duplicates

Juan Denisd134af25ae15
diff --git a/backend/app/api/bandwidth.py b/backend/app/api/bandwidth.py
index b93cd5ef..1c61ee42 100644
--- a/backend/app/api/bandwidth.py
+++ b/backend/app/api/bandwidth.py
@@ -23,12 +23,9 @@ bandwidth_bp = Blueprint('bandwidth', __name__)
def get_apps_bandwidth():
"""Month totals + 30-day sparkline series for every app with traffic —
one call for the Services list."""
- try:
- data = BandwidthService.overview(days=30)
- # JSON object keys must be strings.
- return jsonify({'apps': {str(k): v for k, v in data.items()}})
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ data = BandwidthService.overview(days=30)
+ # JSON object keys must be strings.
+ return jsonify({'apps': {str(k): v for k, v in data.items()}})
@bandwidth_bp.route('/apps/<int:app_id>', methods=['GET'])
@@ -40,17 +37,14 @@ def get_app_bandwidth(app_id):
user = get_current_user()
if app is None or not ResourceGrantService.can_access_app(user, app):
return jsonify({'error': 'Not found'}), 404
- try:
- days = request.args.get('days', 90, type=int)
- series = BandwidthService.series(app_id=app_id, days=days)
- return jsonify({
- 'app_id': app_id,
- 'days': len(series),
- 'series': series,
- 'month_bytes': BandwidthService.monthly_total(app_id),
- })
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ days = request.args.get('days', 90, type=int)
+ series = BandwidthService.series(app_id=app_id, days=days)
+ return jsonify({
+ 'app_id': app_id,
+ 'days': len(series),
+ 'series': series,
+ 'month_bytes': BandwidthService.monthly_total(app_id),
+ })
@bandwidth_bp.route('/apps/<int:app_id>/requests', methods=['GET'])
diff --git a/backend/app/api/doctor.py b/backend/app/api/doctor.py
index f534cc79..5915bdd1 100644
--- a/backend/app/api/doctor.py
+++ b/backend/app/api/doctor.py
@@ -13,7 +13,6 @@ Contract (the CLI codes against this too):
{'items': [{kind, type?, id?, name?}]}
"""
from flask import Blueprint, jsonify, request
-from app.error_reporting import unexpected_response
from ..middleware.rbac import admin_required
from ..services.doctor_service import DOCTOR_REPAIR_JOB_KIND, DoctorService
@@ -30,22 +29,16 @@ doctor_bp = Blueprint('doctor', __name__)
@admin_required
def get_drift_report():
"""Last stored drift report (null when no sweep has run yet)."""
- try:
- return jsonify({'report': DriftService.get_last_report()})
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ return jsonify({'report': DriftService.get_last_report()})
@doctor_bp.route('/drift/check', methods=['POST'])
@admin_required
def run_drift_check():
"""Enqueue a one-off drift sweep job."""
- try:
- from app.jobs.service import JobService
- job = JobService.enqueue(DRIFT_JOB_KIND, payload={}, max_attempts=1)
- return jsonify({'job_id': job.id}), 202
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ from app.jobs.service import JobService
+ job = JobService.enqueue(DRIFT_JOB_KIND, payload={}, max_attempts=1)
+ return jsonify({'job_id': job.id}), 202
@doctor_bp.route('/drift/<check_type>/<resource_id>/repair', methods=['POST'])
@@ -55,13 +48,10 @@ def repair_drift(check_type, resource_id):
data = request.get_json(silent=True) or {}
if data.get('confirm') is not True:
return jsonify({'error': 'Confirmation required: pass {"confirm": true}.'}), 400
- try:
- rid = int(resource_id) if resource_id.isdigit() else resource_id
- result = DriftService.repair(check_type, rid)
- status = 200 if result.get('success') else 400
- return jsonify(result), status
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ rid = int(resource_id) if resource_id.isdigit() else resource_id
+ result = DriftService.repair(check_type, rid)
+ status = 200 if result.get('success') else 400
+ return jsonify(result), status
# --------------------------------------------------------------------------- #
@@ -73,10 +63,7 @@ def repair_drift(check_type, resource_id):
@admin_required
def get_doctor_report():
"""Last stored doctor report (null when the doctor has never run)."""
- try:
- return jsonify({'report': DoctorService.get_last_report()})
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ return jsonify({'report': DoctorService.get_last_report()})
@doctor_bp.route('/run', methods=['POST'])
@@ -84,11 +71,8 @@ def get_doctor_report():
def run_doctor():
"""Run the sweep synchronously (the doctor is interactive; every internal
probe is time-capped) and return the fresh report."""
- try:
- report = DoctorService.run()
- return jsonify({'report': report})
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ report = DoctorService.run()
+ return jsonify({'report': report})
@doctor_bp.route('/repair', methods=['POST'])
@@ -103,17 +87,14 @@ def repair_items():
items = data.get('items')
if not isinstance(items, list) or not items:
return jsonify({'error': "Body must carry a non-empty 'items' list."}), 400
- try:
- if request.args.get('wait', 'true').lower() == 'false':
- from app.jobs.service import JobService
- job = JobService.enqueue(
- DOCTOR_REPAIR_JOB_KIND,
- payload={'items': items},
- max_attempts=1,
- owner_type='doctor',
- owner_id='host',
- )
- return jsonify({'job_id': job.id, 'kind': job.kind}), 202
- return jsonify({'results': DoctorService.repair(items)})
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ if request.args.get('wait', 'true').lower() == 'false':
+ from app.jobs.service import JobService
+ job = JobService.enqueue(
+ DOCTOR_REPAIR_JOB_KIND,
+ payload={'items': items},
+ max_attempts=1,
+ owner_type='doctor',
+ owner_id='host',
+ )
+ return jsonify({'job_id': job.id, 'kind': job.kind}), 202
+ return jsonify({'results': DoctorService.repair(items)})
diff --git a/backend/app/api/files.py b/backend/app/api/files.py
index 3423a2d2..476428ff 100644
--- a/backend/app/api/files.py
+++ b/backend/app/api/files.py
@@ -293,14 +293,11 @@ def download_file():
if os.path.isdir(path):
return jsonify({'error': 'Cannot download directory'}), 400
- try:
- return send_file(
- path,
- as_attachment=True,
- download_name=os.path.basename(path)
- )
- except Exception as e: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(e)
+ return send_file(
+ path,
+ as_attachment=True,
+ download_name=os.path.basename(path)
+ )
@files_bp.route('/upload', methods=['POST'])
diff --git a/backend/app/api/fleet_doctor.py b/backend/app/api/fleet_doctor.py
index a237aa6e..c2b9399a 100644
--- a/backend/app/api/fleet_doctor.py
+++ b/backend/app/api/fleet_doctor.py
@@ -20,7 +20,6 @@ layer only authenticates, shapes the batch, and reports refusals as results
rather than errors.
"""
from flask import Blueprint, jsonify, request
-from app.error_reporting import unexpected_response
from ..middleware.rbac import admin_required, get_current_user
from ..services.fleet_doctor_service import FLEET_DOCTOR_JOB_KIND, FleetDoctorService
@@ -43,22 +42,16 @@ def get_fleet_report():
(or manually enqueued) job wrote. Servers with no rows yet are still listed
so a freshly paired box is visible before its first sweep.
"""
- try:
- return jsonify({'report': FleetDoctorService.fleet_report()})
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ return jsonify({'report': FleetDoctorService.fleet_report()})
@fleet_doctor_bp.route('/run', methods=['POST'])
@admin_required
def run_fleet_sweep():
"""Enqueue the fleet sweep. 202 + job id — never synchronous."""
- try:
- from app.jobs.service import JobService
- job = JobService.enqueue(FLEET_DOCTOR_JOB_KIND, payload={}, max_attempts=1)
- return jsonify({'job_id': job.id}), 202
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ from app.jobs.service import JobService
+ job = JobService.enqueue(FLEET_DOCTOR_JOB_KIND, payload={}, max_attempts=1)
+ return jsonify({'job_id': job.id}), 202
@fleet_doctor_bp.route('/repair', methods=['POST'])
@@ -81,13 +74,10 @@ def repair_fleet_items():
user = get_current_user()
user_id = user.id if user else None
results = []
- try:
- for item in items:
- if not isinstance(item, dict):
- results.append({'success': False, 'error': 'Each item must be an object',
- 'code': 'BAD_REQUEST'})
- continue
- results.append(FleetRepairService.repair(item, user_id=user_id))
- return jsonify({'results': results})
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ for item in items:
+ if not isinstance(item, dict):
+ results.append({'success': False, 'error': 'Each item must be an object',
+ 'code': 'BAD_REQUEST'})
+ continue
+ results.append(FleetRepairService.repair(item, user_id=user_id))
+ return jsonify({'results': results})
diff --git a/backend/app/api/notifications.py b/backend/app/api/notifications.py
index 0218061d..3d0afb35 100644
--- a/backend/app/api/notifications.py
+++ b/backend/app/api/notifications.py
@@ -12,7 +12,6 @@ from app.services.settings_service import SettingsService
from app.services.bounce_service import BounceService
from app.notifications.service import NotificationBusService
from app.notifications.providers import EmailProviderService, SUPPORTED as EMAIL_PROVIDERS
-from app.error_reporting import unexpected_response
# Header carrying the provider's HMAC-SHA256 of the raw request body, formatted
# as ``sha256=<hexdigest>`` (GitHub-style). The shared secret is
@@ -225,11 +224,8 @@ def update_user_preferences():
if 'end' in qh:
prefs.quiet_hours_end = qh['end']
- try:
- db.session.commit()
- return jsonify({'success': True, 'preferences': prefs.to_dict()}), 200
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc) # rolls the session back itself
+ db.session.commit()
+ return jsonify({'success': True, 'preferences': prefs.to_dict()}), 200
@notifications_bp.route('/preferences/test', methods=['POST'])
diff --git a/backend/app/api/previews.py b/backend/app/api/previews.py
index 17562e2d..ad5c2f54 100644
--- a/backend/app/api/previews.py
+++ b/backend/app/api/previews.py
@@ -11,7 +11,6 @@ from flask_jwt_extended import jwt_required
from app.models.application_preview import ApplicationPreview
from app.services.preview_service import PreviewService
-from app.error_reporting import unexpected_response
from app.api._access import require_app
previews_bp = Blueprint('previews', __name__)
@@ -44,11 +43,7 @@ def update_preview_settings(app_id):
"""Enable/disable previews and set the domain template + TTL for an app."""
app = require_app(app_id, write=True, conceal=True)
data = request.get_json(silent=True) or {}
- try:
- result = PreviewService.enable_previews(app_id, data)
- except Exception as exc: # pragma: no cover - defensive
- # Only a failed commit lands here: a crash, not the caller's mistake.
- return unexpected_response(exc)
+ result = PreviewService.enable_previews(app_id, data)
return jsonify(result), 200
diff --git a/backend/app/api/setup_health.py b/backend/app/api/setup_health.py
index a0c48372..64b33e09 100644
--- a/backend/app/api/setup_health.py
+++ b/backend/app/api/setup_health.py
@@ -13,7 +13,6 @@ ref}``). The doctor report carries the same items as its ``setup.*`` section, so
this endpoint and Monitoring → Doctor stay in lockstep.
"""
from flask import Blueprint, jsonify, request
-from app.error_reporting import unexpected_response
from ..middleware.rbac import admin_required, auth_required, get_current_user
from ..services.setup_health_service import SetupHealthService
@@ -32,10 +31,7 @@ setup_health_bp = Blueprint('setup_health', __name__)
def get_setup_health():
"""Evaluate the setup-health registry (panel scope) and return items +
summary. Cheap — DB/settings probes only, no host calls."""
- try:
- return jsonify(SetupHealthService.evaluate(scope='panel'))
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ return jsonify(SetupHealthService.evaluate(scope='panel'))
@setup_health_bp.route('/account', methods=['GET'])
@@ -43,13 +39,10 @@ def get_setup_health():
def get_account_security():
"""The requesting user's own setup-health items (scope 'user') — e.g. the
'secure your account' nudge. Any authenticated user, about themselves."""
- try:
- user = get_current_user()
- if not user:
- return jsonify({'error': 'User not found'}), 404
- return jsonify(SetupHealthService.evaluate(scope='user', user=user))
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ user = get_current_user()
+ if not user:
+ return jsonify({'error': 'User not found'}), 404
+ return jsonify(SetupHealthService.evaluate(scope='user', user=user))
# --------------------------------------------------------------------------- #
@@ -82,10 +75,7 @@ def snooze_item():
user, err = _snooze_guard(key)
if err:
return err
- try:
- return jsonify(SetupHealthService.snooze(key, days=data.get('days', 30), user=user))
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ return jsonify(SetupHealthService.snooze(key, days=data.get('days', 30), user=user))
@setup_health_bp.route('/snooze', methods=['DELETE'])
@@ -99,10 +89,7 @@ def unsnooze_item():
user, err = _snooze_guard(key)
if err:
return err
- try:
- return jsonify(SetupHealthService.unsnooze(key, user=user))
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ return jsonify(SetupHealthService.unsnooze(key, user=user))
# --------------------------------------------------------------------------- #
@@ -114,22 +101,16 @@ def unsnooze_item():
@admin_required
def dns_backfill_preview():
"""Dry-run: the managed hosts a DNS backfill would ensure records for."""
- try:
- return jsonify(SetupReconcileService.dns_backfill_preview())
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ return jsonify(SetupReconcileService.dns_backfill_preview())
@setup_health_bp.route('/reconcile/dns/apply', methods=['POST'])
@admin_required
def dns_backfill_apply():
"""Enqueue the DNS backfill job (loops ensure_a_record, ownership-guarded)."""
- try:
- from app.jobs.service import JobService
- job = JobService.enqueue(DNS_BACKFILL_JOB_KIND, payload={}, max_attempts=1)
- return jsonify({'job_id': job.id}), 202
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ from app.jobs.service import JobService
+ job = JobService.enqueue(DNS_BACKFILL_JOB_KIND, payload={}, max_attempts=1)
+ return jsonify({'job_id': job.id}), 202
@setup_health_bp.route('/reconcile/url-fix/preview', methods=['POST'])
@@ -137,19 +118,13 @@ def dns_backfill_apply():
def url_fix_preview():
"""Dry-run: WordPress sites whose siteurl/home still point at localhost or a
stale IP, with the per-site swap they'd get."""
- try:
- return jsonify(SetupReconcileService.url_fix_preview())
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ return jsonify(SetupReconcileService.url_fix_preview())
@setup_health_bp.route('/reconcile/url-fix/apply', methods=['POST'])
@admin_required
def url_fix_apply():
"""Enqueue the WordPress URL-fix job (loops change_site_url)."""
- try:
- from app.jobs.service import JobService
- job = JobService.enqueue(URL_FIX_JOB_KIND, payload={}, max_attempts=1)
- return jsonify({'job_id': job.id}), 202
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ from app.jobs.service import JobService
+ job = JobService.enqueue(URL_FIX_JOB_KIND, payload={}, max_attempts=1)
+ return jsonify({'job_id': job.id}), 202
diff --git a/backend/app/api/speed_test.py b/backend/app/api/speed_test.py
index f2ac8259..70ff7574 100644
--- a/backend/app/api/speed_test.py
+++ b/backend/app/api/speed_test.py
@@ -3,7 +3,6 @@
Mounted at /api/v1/speedtest (registered in app/__init__.py).
"""
from flask import Blueprint, jsonify
-from app.error_reporting import unexpected_response
from ..middleware.rbac import admin_required, viewer_required
from ..services.speed_test_service import SPEEDTEST_JOB_KIND, SpeedTestService
@@ -16,21 +15,15 @@ speedtest_bp = Blueprint('speedtest', __name__)
@viewer_required
def get_speed_test():
"""Last stored result + status of any in-flight speed test job."""
- try:
- return jsonify(SpeedTestService.get_status())
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ return jsonify(SpeedTestService.get_status())
@speedtest_bp.route('/run', methods=['POST'])
@admin_required
def run_speed_test():
"""Enqueue a one-off speed test job. Rejects if one is already in flight."""
- try:
- if SpeedTestService.is_running():
- return jsonify({'error': 'A speed test is already in progress.'}), 409
- from app.jobs.service import JobService
- job = JobService.enqueue(SPEEDTEST_JOB_KIND, payload={}, max_attempts=1)
- return jsonify({'job_id': job.id}), 202
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ if SpeedTestService.is_running():
+ return jsonify({'error': 'A speed test is already in progress.'}), 409
+ from app.jobs.service import JobService
+ job = JobService.enqueue(SPEEDTEST_JOB_KIND, payload={}, max_attempts=1)
+ return jsonify({'job_id': job.id}), 202
diff --git a/backend/app/api/sso.py b/backend/app/api/sso.py
index 223a4463..ec7e63c1 100644
--- a/backend/app/api/sso.py
+++ b/backend/app/api/sso.py
@@ -12,7 +12,8 @@ from app.services.settings_service import SettingsService
from app.services.audit_service import AuditService
from app.middleware.rbac import admin_required, get_current_user
from app.middleware.session_auth import issue_session_tokens
-from app.error_reporting import record_unexpected, unexpected_response
+from app.error_reporting import record_unexpected
+from app.exceptions import NotFoundError
sso_bp = Blueprint('sso', __name__)
@@ -108,28 +109,32 @@ def saml_callback():
@sso_bp.route('/saml/metadata', methods=['GET'])
def saml_metadata():
"""Return SP metadata XML."""
+ from onelogin.saml2.auth import OneLogin_Saml2_Auth
+ from onelogin.saml2.errors import OneLogin_Saml2_Error
+ cfg = sso_service.get_provider_config('saml')
+ request_data = {
+ 'https': request.scheme == 'https',
+ 'http_host': request.host,
+ 'script_name': request.path,
+ 'acs_url': request.url_root.rstrip('/') + '/api/v1/sso/saml/callback',
+ 'sp_entity_id': request.host_url.rstrip('/'),
+ }
+ settings = sso_service.get_saml_settings(cfg, request_data)
+ saml_req = {
+ 'https': 'on' if request_data.get('https') else 'off',
+ 'http_host': request_data.get('http_host', ''),
+ 'script_name': request_data.get('script_name', ''),
+ }
try:
- from onelogin.saml2.auth import OneLogin_Saml2_Auth
- cfg = sso_service.get_provider_config('saml')
- request_data = {
- 'https': request.scheme == 'https',
- 'http_host': request.host,
- 'script_name': request.path,
- 'acs_url': request.url_root.rstrip('/') + '/api/v1/sso/saml/callback',
- 'sp_entity_id': request.host_url.rstrip('/'),
- }
- settings = sso_service.get_saml_settings(cfg, request_data)
- saml_req = {
- 'https': 'on' if request_data.get('https') else 'off',
- 'http_host': request_data.get('http_host', ''),
- 'script_name': request_data.get('script_name', ''),
- }
auth = OneLogin_Saml2_Auth(saml_req, settings)
- metadata = auth.get_settings().get_sp_metadata()
- from flask import Response
- return Response(metadata, mimetype='application/xml')
- except Exception as e: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(e)
+ except OneLogin_Saml2_Error as exc:
+ # An unconfigured IdP is not a crash: this route is public and gets
+ # probed, and each hit used to land in the error log.
+ raise NotFoundError('SAML is not configured',
+ code='sso.saml_not_configured') from exc
+ metadata = auth.get_settings().get_sp_metadata()
+ from flask import Response
+ return Response(metadata, mimetype='application/xml')
# ------------------------------------------------------------------
diff --git a/backend/app/api/support_bundle.py b/backend/app/api/support_bundle.py
index f83b967a..10ad70d0 100644
--- a/backend/app/api/support_bundle.py
+++ b/backend/app/api/support_bundle.py
@@ -11,7 +11,6 @@ from flask import Blueprint, jsonify, send_file
from app.middleware.rbac import admin_required
from app.services import support_bundle_service
-from app.error_reporting import unexpected_response
support_bundle_bp = Blueprint('support_bundle', __name__)
@@ -20,10 +19,7 @@ support_bundle_bp = Blueprint('support_bundle', __name__)
@admin_required
def build_support_bundle():
"""Build a diagnostic support bundle and return it as a zip download."""
- try:
- path = support_bundle_service.build()
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ path = support_bundle_service.build()
if not os.path.isfile(path):
return jsonify({'error': 'Support bundle was not created'}), 500
diff --git a/backend/app/api/system.py b/backend/app/api/system.py
index 89f52851..2c4d1dd3 100644
--- a/backend/app/api/system.py
+++ b/backend/app/api/system.py
@@ -4,7 +4,6 @@ import urllib.request
import json
from flask import Blueprint, jsonify, request, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity
-from app.error_reporting import unexpected_response
from app.exceptions import ValidationError
from app.models import User
from app.middleware.rbac import admin_required, get_current_user, viewer_required
@@ -115,10 +114,7 @@ def get_panel_update_status():
log file (see panel_update_service).
"""
from app.services import panel_update_service as svc
- try:
- return jsonify(svc.get_status()), 200
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ return jsonify(svc.get_status()), 200
@system_bp.route('/update', methods=['POST'])
@@ -197,10 +193,7 @@ def get_storage_overview():
bound ServerKit's own share. Reads only."""
from app.services import storage_overview_service
- try:
- return jsonify(storage_overview_service.overview()), 200
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ return jsonify(storage_overview_service.overview()), 200
@system_bp.route('/disk/reclaim/report', methods=['GET'])
@@ -209,10 +202,7 @@ def get_disk_reclaim_report():
"""Measure every safe reclaim candidate. Reads only — deletes nothing."""
from app.services import disk_reclaim_service as svc
- try:
- return jsonify(svc.scan()), 200
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ return jsonify(svc.scan()), 200
@system_bp.route('/disk/reclaim', methods=['POST'])
@@ -236,34 +226,28 @@ def reclaim_disk_space():
user = get_current_user()
from app.services import disk_reclaim_service as svc
- try:
- keys, error = svc.validate_reclaim_keys(keys)
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ keys, error = svc.validate_reclaim_keys(keys)
if error:
raise ValidationError(error)
- try:
- wait = request.args.get('wait', 'true').lower() != 'false'
- if not wait:
- from app.jobs.service import JobService
- job = JobService.enqueue(
- svc.DISK_RECLAIM_JOB_KIND,
- payload={'keys': keys},
- max_attempts=1,
- owner_type='system',
- owner_id='disk',
- )
- _audit('disk.reclaim', user.id, target_type='job',
- target_id=str(job.id), details={'keys': keys, 'queued': True})
- return jsonify({'job_id': job.id, 'kind': svc.DISK_RECLAIM_JOB_KIND}), 202
-
- result = svc.reclaim(keys)
- _audit('disk.reclaim', user.id, target_type='host', target_id='disk',
- details={'keys': keys, 'freed_bytes': result.get('freed_bytes')})
- return jsonify(result), 200
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ wait = request.args.get('wait', 'true').lower() != 'false'
+ if not wait:
+ from app.jobs.service import JobService
+ job = JobService.enqueue(
+ svc.DISK_RECLAIM_JOB_KIND,
+ payload={'keys': keys},
+ max_attempts=1,
+ owner_type='system',
+ owner_id='disk',
+ )
+ _audit('disk.reclaim', user.id, target_type='job',
+ target_id=str(job.id), details={'keys': keys, 'queued': True})
+ return jsonify({'job_id': job.id, 'kind': svc.DISK_RECLAIM_JOB_KIND}), 202
+
+ result = svc.reclaim(keys)
+ _audit('disk.reclaim', user.id, target_type='host', target_id='disk',
+ details={'keys': keys, 'freed_bytes': result.get('freed_bytes')})
+ return jsonify(result), 200
def _audit(action, user_id, target_type=None, target_id=None, details=None):
diff --git a/backend/app/api/templates.py b/backend/app/api/templates.py
index 945efc50..6ef0b120 100644
--- a/backend/app/api/templates.py
+++ b/backend/app/api/templates.py
@@ -19,7 +19,6 @@ from app.services.template_service import TemplateService
from app.services.repository_manifest_service import RepositoryManifestService
from app.services.resource_grant_service import ResourceGrantService
from app.utils.slug import app_name_clash_error, validate_app_name
-from app.error_reporting import unexpected_response
from app.exceptions import not_found, permission_denied
templates_bp = Blueprint('templates', __name__)
@@ -315,50 +314,44 @@ def catalog_schema():
@admin_required
def install_template(template_id):
"""Install a template as a new application."""
- try:
- current_user_id = get_jwt_identity()
- data = request.get_json()
-
- if not data:
- return jsonify({'error': 'No data provided'}), 400
-
- app_name = data.get('app_name')
- if not app_name:
- return jsonify({'error': 'app_name is required'}), 400
+ current_user_id = get_jwt_identity()
+ data = request.get_json()
- # Validate app name
- valid, error = validate_app_name(app_name, min_length=3)
- if not valid:
- return jsonify({'error': error}), 400
-
- user_variables = data.get('variables', {})
- server_id = data.get('server_id') or data.get('target_server_id')
- wait = bool(data.get('wait', False))
- # The deploy drawer sends true when it showed the operator a
- # <name>.<base> hostname — that promise must not depend on the
- # template YAML having opted in. Absent means the template decides.
- auto_domain = data.get('auto_domain')
-
- result = DeploymentJobService.install_template(
- template_id=template_id,
- app_name=app_name,
- user_variables=user_variables,
- user_id=current_user_id,
- server_id=server_id,
- wait=wait,
- auto_domain=None if auto_domain is None else bool(auto_domain),
- )
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
- if not result.get('success'):
- return jsonify(result), 400
+ app_name = data.get('app_name')
+ if not app_name:
+ return jsonify({'error': 'app_name is required'}), 400
+
+ # Validate app name
+ valid, error = validate_app_name(app_name, min_length=3)
+ if not valid:
+ return jsonify({'error': error}), 400
+
+ user_variables = data.get('variables', {})
+ server_id = data.get('server_id') or data.get('target_server_id')
+ wait = bool(data.get('wait', False))
+ # The deploy drawer sends true when it showed the operator a
+ # <name>.<base> hostname — that promise must not depend on the
+ # template YAML having opted in. Absent means the template decides.
+ auto_domain = data.get('auto_domain')
+
+ result = DeploymentJobService.install_template(
+ template_id=template_id,
+ app_name=app_name,
+ user_variables=user_variables,
+ user_id=current_user_id,
+ server_id=server_id,
+ wait=wait,
+ auto_domain=None if auto_domain is None else bool(auto_domain),
+ )
- status = result.get('job', {}).get('status')
- return jsonify(result), 201 if status == 'succeeded' else 202
+ if not result.get('success'):
+ return jsonify(result), 400
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- # Was returning the full traceback to the caller and print()ing it.
- # The door logs it and files it under a request id instead.
- return unexpected_response(exc)
+ status = result.get('job', {}).get('status')
+ return jsonify(result), 201 if status == 'succeeded' else 202
@templates_bp.route('/<template_id>/capacity', methods=['GET'])
@@ -383,77 +376,73 @@ def template_capacity(template_id):
@jwt_required()
def validate_installation():
"""Validate template installation parameters before installing."""
- try:
- data = request.get_json()
+ data = request.get_json()
- if not data:
- return jsonify({'error': 'No data provided'}), 400
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
- template_id = data.get('template_id')
- app_name = data.get('app_name')
- user_variables = data.get('variables', {})
- server_id = data.get('server_id') or data.get('target_server_id')
+ template_id = data.get('template_id')
+ app_name = data.get('app_name')
+ user_variables = data.get('variables', {})
+ server_id = data.get('server_id') or data.get('target_server_id')
- errors = []
- capacity = None
+ errors = []
+ capacity = None
- # Validate app name
- if not app_name:
- errors.append('App name is required')
+ # Validate app name
+ if not app_name:
+ errors.append('App name is required')
+ else:
+ valid, error = validate_app_name(app_name, min_length=2)
+ if not valid:
+ errors.append(error)
+
+ # Check if app name is taken
+ # Deliberately unfiltered: a tombstone keeps RESERVING its name, or a
+ # new app takes it and the restore is refused (_live_name_clash).
+ if app_name:
+ existing = Application.query.filter_by(name=app_name).first()
+ if existing:
+ errors.append(app_name_clash_error(existing, app_name))
+
+ # Validate template exists and check required variables
+ if template_id:
+ result = TemplateService.get_template(template_id)
+ if not result.get('success'):
+ errors.append('Template not found')
else:
- valid, error = validate_app_name(app_name, min_length=2)
- if not valid:
- errors.append(error)
-
- # Check if app name is taken
- # Deliberately unfiltered: a tombstone keeps RESERVING its name, or a
- # new app takes it and the restore is refused (_live_name_clash).
- if app_name:
- existing = Application.query.filter_by(name=app_name).first()
- if existing:
- errors.append(app_name_clash_error(existing, app_name))
-
- # Validate template exists and check required variables
- if template_id:
- result = TemplateService.get_template(template_id)
- if not result.get('success'):
- errors.append('Template not found')
- else:
- template = result['template']
- raw_vars = template.get('variables', [])
-
- # Handle both list and dict formats
- if isinstance(raw_vars, list):
- for var in raw_vars:
- if isinstance(var, dict) and var.get('required', False):
- var_name = var.get('name', '')
- if var_name and var_name not in user_variables:
- errors.append(f'Required variable "{var_name}" is not provided')
- elif isinstance(raw_vars, dict):
- for var_name, var_config in raw_vars.items():
- if var_config.get('required', False) and var_name not in user_variables:
+ template = result['template']
+ raw_vars = template.get('variables', [])
+
+ # Handle both list and dict formats
+ if isinstance(raw_vars, list):
+ for var in raw_vars:
+ if isinstance(var, dict) and var.get('required', False):
+ var_name = var.get('name', '')
+ if var_name and var_name not in user_variables:
errors.append(f'Required variable "{var_name}" is not provided')
+ elif isinstance(raw_vars, dict):
+ for var_name, var_config in raw_vars.items():
+ if var_config.get('required', False) and var_name not in user_variables:
+ errors.append(f'Required variable "{var_name}" is not provided')
+
+ # Does the target have room? Advisory: it rides alongside
+ # `errors` rather than in it, so a tight server informs the
+ # operator without refusing the install. Never fatal — a
+ # capacity probe that throws must not block a deploy.
+ try:
+ from app.services.capacity_service import check_fit
+ capacity = check_fit(template, server_id)
+ except Exception: # noqa: BLE001
+ current_app.logger.warning('capacity check failed', exc_info=True)
+ else:
+ errors.append('Template ID is required')
- # Does the target have room? Advisory: it rides alongside
- # `errors` rather than in it, so a tight server informs the
- # operator without refusing the install. Never fatal — a
- # capacity probe that throws must not block a deploy.
- try:
- from app.services.capacity_service import check_fit
- capacity = check_fit(template, server_id)
- except Exception: # noqa: BLE001
- current_app.logger.warning('capacity check failed', exc_info=True)
- else:
- errors.append('Template ID is required')
-
- if errors:
- return jsonify({'valid': False, 'errors': errors,
- 'capacity': capacity}), 400
-
- return jsonify({'valid': True, 'capacity': capacity}), 200
+ if errors:
+ return jsonify({'valid': False, 'errors': errors,
+ 'capacity': capacity}), 400
- except Exception as exc: # noqa: BLE001 - reported, not swallowed
- return unexpected_response(exc)
+ return jsonify({'valid': True, 'capacity': capacity}), 200
@templates_bp.route('/test-db-connection', methods=['POST'])
diff --git a/backend/tests/test_saml_metadata_unconfigured.py b/backend/tests/test_saml_metadata_unconfigured.py
new file mode 100644
index 00000000..d474b60f
--- /dev/null
+++ b/backend/tests/test_saml_metadata_unconfigured.py
@@ -0,0 +1,11 @@
+"""SAML metadata on a panel without SAML is a 404, not a recorded crash.
+
+The route is public, so probes against unconfigured panels used to fill
+the error log with an "unexpected" OneLogin settings error each time.
+"""
+
+
+def test_unconfigured_saml_metadata_is_404(client):
+ resp = client.get('/api/v1/sso/saml/metadata')
+ assert resp.status_code == 404
+ assert resp.get_json()['code'] == 'sso.saml_not_configured'