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.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Replace nine per-app access helpers with one
Juan Denis6068b099dc05
diff --git a/backend/app/api/_access.py b/backend/app/api/_access.pynew file mode 100644index 00000000..b700bc17--- /dev/null+++ b/backend/app/api/_access.py@@ -0,0 +1,13 @@+"""Per-app access for routes: the one way a view loads "the app this caller+may touch". Raises the typed 404/403 the global error handler renders."""+from app.services.resource_grant_service import ResourceGrantService+from app.middleware.rbac import get_current_user+++def require_app(app_id, *, write=False, conceal=False):+ """The live application the current user may read, or edit with ``write``.++ ``conceal`` answers a denied caller with the same 404 as a missing app.+ """+ return ResourceGrantService.get_app_for(+ get_current_user(), app_id, write=write, conceal=conceal)diff --git a/backend/app/api/app_slots.py b/backend/app/api/app_slots.pyindex 6de823e3..bf94487a 100644--- a/backend/app/api/app_slots.py+++ b/backend/app/api/app_slots.py@@ -19,35 +19,25 @@"""from flask import Blueprint, jsonify, request-from app.exceptions import ValidationError, not_found+from app.exceptions import ValidationErrorfrom app.middleware.rbac import developer_required, get_current_user, viewer_required-from app.services.resource_grant_service import ResourceGrantServicefrom app.services.slot_deploy_service import SlotDeployService+from app.api._access import require_appapp_slots_bp = Blueprint('app_slots', __name__)-def _app(app_id, write=False):- app = SlotDeployService.live_app(app_id)- user = get_current_user()- allowed = (ResourceGrantService.can_edit_app if write- else ResourceGrantService.can_access_app)- if app is None or not allowed(user, app):- raise not_found('service')- return app, user--@app_slots_bp.route('/<int:app_id>/slots', methods=['GET'])@viewer_requireddef get_slots(app_id):- app, _ = _app(app_id)+ app = require_app(app_id, conceal=True)return jsonify(SlotDeployService.status(app))@app_slots_bp.route('/<int:app_id>/slots', methods=['PUT'])@developer_requireddef set_slots(app_id):- app, _ = _app(app_id, write=True)+ app = require_app(app_id, write=True, conceal=True)data = request.get_json(silent=True) or {}enabled = data.get('enabled')if not isinstance(enabled, bool):@@ -61,8 +51,8 @@ def set_slots(app_id):@app_slots_bp.route('/<int:app_id>/slots/switch-back', methods=['POST'])@developer_requireddef switch_back(app_id):- app, user = _app(app_id, write=True)- result = SlotDeployService.switch_back(app, user_id=user.id)+ app = require_app(app_id, write=True, conceal=True)+ result = SlotDeployService.switch_back(app, user_id=get_current_user().id)if not result.get('success'):return jsonify(result), 409return jsonify(result)@@ -71,7 +61,7 @@ def switch_back(app_id):@app_slots_bp.route('/<int:app_id>/slots/restore-db', methods=['POST'])@developer_requireddef restore_db(app_id):- app, _ = _app(app_id, write=True)+ app = require_app(app_id, write=True, conceal=True)data = request.get_json(silent=True) or {}deployment_id = data.get('deployment_id')if not isinstance(deployment_id, int) or isinstance(deployment_id, bool):@@ -85,7 +75,7 @@ def restore_db(app_id):@app_slots_bp.route('/<int:app_id>/slots/compose-split', methods=['GET'])@viewer_requireddef compose_split_preview(app_id):- app, _ = _app(app_id)+ app = require_app(app_id, conceal=True)result = SlotDeployService.compose_split_preview(app)if not result.get('success'):return jsonify(result), 409@@ -95,7 +85,7 @@ def compose_split_preview(app_id):@app_slots_bp.route('/<int:app_id>/slots/compose-split', methods=['POST'])@developer_requireddef compose_split_apply(app_id):- app, _ = _app(app_id, write=True)+ app = require_app(app_id, write=True, conceal=True)data = request.get_json(silent=True) or {}if data.get('confirm') is not True:raise ValidationError("Moving the stateful services stops the service once; send "diff --git a/backend/app/api/app_volumes.py b/backend/app/api/app_volumes.pyindex ebe1f7b0..bee7a595 100644--- a/backend/app/api/app_volumes.py+++ b/backend/app/api/app_volumes.py@@ -7,34 +7,16 @@ apps blueprint (routes are ``/<app_id>/volumes*``).from flask import Blueprint, request, jsonifyfrom flask_jwt_extended import jwt_required-from app.models import Application-from app.services.resource_grant_service import ResourceGrantServicefrom app.services.volume_service import VolumeService, VolumeError-from app.middleware.rbac import get_current_user-from app.exceptions import not_found, permission_denied+from app.api._access import require_appapp_volumes_bp = Blueprint('app_volumes', __name__)-def _load_app_for(app_id, *, write):- """Resolve (user, app) with the right ACL, or an (error_response, status)."""- user = get_current_user()- app = Application.query_active().filter_by(id=app_id).first()- if not app:- raise not_found('service')- allowed = (ResourceGrantService.can_edit_app(user, app) if write- else ResourceGrantService.can_access_app(user, app))- if not allowed:- raise permission_denied()- return user, app, None--@app_volumes_bp.route('/<int:app_id>/volumes', methods=['GET'])@jwt_required()def list_volumes(app_id):- _user, app, err = _load_app_for(app_id, write=False)- if err:- return err+ app = require_app(app_id)volumes = [v.to_dict(live=live) for v, live in VolumeService.list_for_app(app)]return jsonify({'volumes': volumes})@@ -42,9 +24,7 @@ def list_volumes(app_id):@app_volumes_bp.route('/<int:app_id>/volumes', methods=['POST'])@jwt_required()def attach_volume(app_id):- _user, app, err = _load_app_for(app_id, write=True)- if err:- return err+ app = require_app(app_id, write=True)data = request.get_json() or {}try:volume = VolumeService.create(@@ -63,9 +43,7 @@ def attach_volume(app_id):@app_volumes_bp.route('/<int:app_id>/volumes/<int:volume_id>', methods=['DELETE'])@jwt_required()def detach_volume(app_id, volume_id):- _user, app, err = _load_app_for(app_id, write=True)- if err:- return err+ app = require_app(app_id, write=True)volume = VolumeService.get(volume_id)if not volume or volume.application_id != app.id:return jsonify({'error': 'Volume not found'}), 404@@ -83,9 +61,7 @@ def convert_bind_mount(app_id):"""Create a managed volume and copy an existing host directory's contentsinto it. (Deviates from the plan's ``/<vid>/convert`` — a convert creates anew volume, so there is no prior vid.)"""- _user, app, err = _load_app_for(app_id, write=True)- if err:- return err+ app = require_app(app_id, write=True)data = request.get_json() or {}host_path = data.get('host_path')mount_path = data.get('mount_path')diff --git a/backend/app/api/apps.py b/backend/app/api/apps.pyindex 10cc4e63..c068d228 100644--- a/backend/app/api/apps.py+++ b/backend/app/api/apps.py@@ -48,6 +48,7 @@ from app.error_reporting import unexpected_responsefrom app.exceptions import (PermissionDeniedError, ValidationError, field_required, not_found, permission_denied,)+from app.api._access import require_appapps_bp = Blueprint('apps', __name__)@@ -2200,25 +2201,11 @@ def get_app_status(app_id):# ==================== BACKUP PROTECTION (policy + runs) ====================-def _load_app_for_backup(app_id, edit=False):- """Load an app the current user may access (or edit). Returns (app, error)."""- user = get_current_user()- app = Application.query_active().filter_by(id=app_id).first()- if not app:- raise not_found('service')- allowed = _can_edit_app(user, app) if edit else _can_access_app(user, app)- if not allowed:- raise permission_denied()- return app, None--@apps_bp.route('/<int:app_id>/backup-policy', methods=['GET'])@jwt_required()def get_app_backup_policy(app_id):"""Return the protection policy + status for an app (creating a default)."""- app, err = _load_app_for_backup(app_id)- if err:- return err+ app = require_app(app_id)policy = BackupPolicyService.get_or_create_policy('application', app_id)return jsonify(BackupPolicyService.serialize_policy_view(policy))@@ -2227,9 +2214,7 @@ def get_app_backup_policy(app_id):@jwt_required()def update_app_backup_policy(app_id):"""Update the protection policy and re-sync its schedule."""- app, err = _load_app_for_backup(app_id, edit=True)- if err:- return err+ app = require_app(app_id, write=True)policy = BackupPolicyService.get_or_create_policy('application', app_id)try:BackupPolicyService.update_policy(policy, request.get_json() or {})@@ -2242,9 +2227,7 @@ def update_app_backup_policy(app_id):@jwt_required()def trigger_app_backup(app_id):"""Enqueue a one-off backup for the app."""- app, err = _load_app_for_backup(app_id, edit=True)- if err:- return err+ app = require_app(app_id, write=True)policy = BackupPolicyService.get_or_create_policy('application', app_id)try:job = BackupPolicyService.run_policy_now(policy, manual=True)@@ -2257,9 +2240,7 @@ def trigger_app_backup(app_id):@jwt_required()def list_app_backups(app_id):"""List backup runs for the app."""- app, err = _load_app_for_backup(app_id)- if err:- return err+ app = require_app(app_id)policy = BackupPolicyService.get_or_create_policy('application', app_id)return jsonify({'runs': BackupPolicyService.list_runs(policy)})@@ -2268,9 +2249,7 @@ def list_app_backups(app_id):@jwt_required()def restore_app_backup(app_id, run_id):"""Enqueue a restore from a specific backup run."""- app, err = _load_app_for_backup(app_id, edit=True)- if err:- return err+ app = require_app(app_id, write=True)policy = BackupPolicyService.get_or_create_policy('application', app_id)try:job = BackupPolicyService.request_restore(policy, run_id, request.get_json() or {})@@ -2283,9 +2262,7 @@ def restore_app_backup(app_id, run_id):@jwt_required()def verify_app_backup(app_id, run_id):"""Verify the remote copy of a backup run."""- app, err = _load_app_for_backup(app_id, edit=True)- if err:- return err+ app = require_app(app_id, write=True)policy = BackupPolicyService.get_or_create_policy('application', app_id)try:result = BackupPolicyService.verify_run(policy, run_id)@@ -2298,9 +2275,7 @@ def verify_app_backup(app_id, run_id):@jwt_required()def delete_app_backup(app_id, run_id):"""Delete a backup run (local + remote + record)."""- app, err = _load_app_for_backup(app_id, edit=True)- if err:- return err+ app = require_app(app_id, write=True)policy = BackupPolicyService.get_or_create_policy('application', app_id)try:BackupPolicyService.delete_run(policy, run_id)@@ -2328,9 +2303,7 @@ def _wp_site_for_app(app):def app_wordpress_info(app_id):"""Whether this app is a WordPress site, and the linked site id. Lets thegeneric Services surface discover the WordPress extension."""- app, err = _load_app_for_backup(app_id)- if err:- return err+ app = require_app(app_id)site = _wp_site_for_app(app)if not site:return jsonify({'is_wordpress': False, 'site_id': None}), 200@@ -2347,9 +2320,7 @@ def app_wordpress_info(app_id):@jwt_required()def list_app_db_snapshots(app_id):"""List the WordPress DB snapshots for an app (unified app-id surface)."""- app, err = _load_app_for_backup(app_id)- if err:- return err+ app = require_app(app_id)from app.models.wordpress_site import DatabaseSnapshotsite = _wp_site_for_app(app)if not site:@@ -2363,9 +2334,7 @@ def list_app_db_snapshots(app_id):@jwt_required()def create_app_db_snapshot(app_id):"""Create a WordPress DB snapshot for an app."""- app, err = _load_app_for_backup(app_id, edit=True)- if err:- return err+ app = require_app(app_id, write=True)from app.models.wordpress_site import DatabaseSnapshotfrom app.services.db_sync_service import DatabaseSyncServicesite = _wp_site_for_app(app)@@ -2413,9 +2382,7 @@ def create_app_db_snapshot(app_id):@jwt_required()def delete_app_db_snapshot(app_id, snapshot_id):"""Delete a WordPress DB snapshot for an app."""- app, err = _load_app_for_backup(app_id, edit=True)- if err:- return err+ app = require_app(app_id, write=True)from app.models.wordpress_site import DatabaseSnapshotfrom app.services.db_sync_service import DatabaseSyncServicesite = _wp_site_for_app(app)diff --git a/backend/app/api/database_engines.py b/backend/app/api/database_engines.pyindex 1fc62649..20953dfe 100644--- a/backend/app/api/database_engines.py+++ b/backend/app/api/database_engines.py@@ -23,14 +23,12 @@ import loggingfrom flask import Blueprint, jsonify, requestfrom flask_jwt_extended import get_jwt_identity, jwt_required-from app.middleware.rbac import admin_required, get_current_user-from app.models import Application-from app.services.resource_grant_service import ResourceGrantService+from app.middleware.rbac import admin_requiredfrom app.services import database_engine_extension_service as extensionsfrom app.services import database_engine_service as enginesfrom app.services.deployment_job_service import DeploymentJobServicefrom app.services.template_service import TemplateService-from app.exceptions import not_found, permission_denied+from app.api._access import require_applogger = logging.getLogger(__name__)@@ -127,25 +125,6 @@ def list_engine_extensions():'family': TemplateService.EXTENSION_FAMILY}), 200-def _require_app_access(app_id):- """Ensure the caller may see this app, mirroring the per-app docker DB read.-- Returns an (error_body, status) tuple to return, or None when allowed. The- extension listing names an instance's image, its databases and what it can- load — all facts about someone's application, so a bare `@jwt_required()`- would have let any signed-in user enumerate them across the whole panel.- """- user = get_current_user()- if not user:- return {'error': 'Unauthorized'}, 401- app = Application.query_active().filter_by(id=app_id).first()- if not app:- raise not_found('service')- if not ResourceGrantService.can_access_app(user, app):- raise permission_denied()- return None--@database_engines_bp.route('/<int:app_id>/extensions', methods=['GET'])@jwt_required()def list_instance_extensions(app_id):@@ -155,9 +134,7 @@ def list_instance_extensions(app_id):inferring it from the image name -- slower (a docker exec per extension),authoritative, and the only way to see what is already installed."""- denied = _require_app_access(app_id)- if denied:- return jsonify(denied[0]), denied[1]+ require_app(app_id)probe = request.args.get('probe', 'false').lower() == 'true'result = extensions.instance_extensions(app_id, probe=probe)diff --git a/backend/app/api/deployments.py b/backend/app/api/deployments.pyindex e943fcdc..f087a943 100644--- a/backend/app/api/deployments.py+++ b/backend/app/api/deployments.py@@ -12,35 +12,21 @@ history instead of merging two sources.from flask import Blueprint, request, jsonifyfrom flask_jwt_extended import jwt_required-from app.models import Applicationfrom app.models.deployment import Deploymentfrom app.models.webhook import GitDeployment-from app.middleware.rbac import get_current_user-from app.exceptions import not_found, permission_denied+from app.exceptions import not_found+from app.api._access import require_appdeployments_bp = Blueprint('deployments', __name__)-def _access(app_id):- from app.services.resource_grant_service import ResourceGrantService- user = get_current_user()- app = Application.query_active().filter_by(id=app_id).first()- if not app:- raise not_found('service')- if not ResourceGrantService.can_access_app(user, app):- raise permission_denied()- return app, None--@deployments_bp.route('/apps/<int:app_id>/history', methods=['GET'])@jwt_required()def app_history(app_id):"""Federated deploy history for an app: versioned build Deployments +webhook GitDeployments, each tagged with ``source``, newest first.Query: ?source=build|webhook|all (default all), ?limit= (<=500)."""- app, err = _access(app_id)- if err:- return err+ app = require_app(app_id)source = (request.args.get('source') or 'all').lower()try:limit = min(int(request.args.get('limit', 100)), 500)@@ -72,7 +58,5 @@ def get_deployment(deployment_id):d = Deployment.query.get(deployment_id)if not d:raise not_found('deployment')- _, err = _access(d.app_id)- if err:- return err+ require_app(d.app_id)return jsonify({'deployment': d.to_dict(include_logs=True)}), 200diff --git a/backend/app/api/env_vars.py b/backend/app/api/env_vars.pyindex a0c47d23..c0c3d101 100644--- a/backend/app/api/env_vars.py+++ b/backend/app/api/env_vars.py@@ -10,43 +10,20 @@ All values are encrypted at rest.from flask import Blueprint, request, jsonifyfrom flask_jwt_extended import jwt_required, get_jwt_identity-from app.models import Application, Userfrom app.services.env_service import EnvServicefrom app.services.resource_grant_service import ResourceGrantService-from app.exceptions import not_found, permission_denied+from app.api._access import require_app+from app.middleware.rbac import get_current_userenv_vars_bp = Blueprint('env_vars', __name__)-def check_app_access(app_id, user_id, write=False):- """Check that the user may access the application's env vars.-- Reads (``write=False``) require can_access_app (owner/admin/any grant);- writes require can_edit_app (owner/admin/editor grant — a viewer grant is- read-only). Returns ``(user, app, None, None)`` on success or- ``(None, None, error_response, status)`` on failure."""- user = User.query.get(user_id)- app = Application.query_active().filter_by(id=app_id).first()-- if not app:- raise not_found('service')-- ok = (ResourceGrantService.can_edit_app(user, app) if write- else ResourceGrantService.can_access_app(user, app))- if not ok:- raise permission_denied()-- return user, app, None, None--@env_vars_bp.route('/<int:app_id>/env', methods=['GET'])@jwt_required()def get_env_vars(app_id):"""Get all environment variables for an application."""- current_user_id = get_jwt_identity()- user, app, error, status = check_app_access(app_id, current_user_id)- if error:- return error, status+ user = get_current_user()+ app = require_app(app_id)# A read-only grant never sees secret values, whatever ?mask says.mask_secrets = (request.args.get('mask', 'false').lower() == 'true'@@ -65,9 +42,7 @@ def get_env_vars(app_id):def create_env_var(app_id):"""Create a new environment variable."""current_user_id = get_jwt_identity()- user, app, error, status = check_app_access(app_id, current_user_id, write=True)- if error:- return error, status+ app = require_app(app_id, write=True)data = request.get_json()if not data:@@ -101,10 +76,8 @@ def create_env_var(app_id):@jwt_required()def get_env_var(app_id, key):"""Get a single environment variable by key."""- current_user_id = get_jwt_identity()- user, app, error, status = check_app_access(app_id, current_user_id)- if error:- return error, status+ user = get_current_user()+ app = require_app(app_id)env_var = EnvService.get_env_var(app_id, key)@@ -122,9 +95,7 @@ def get_env_var(app_id, key):def update_env_var(app_id, key):"""Update an existing environment variable."""current_user_id = get_jwt_identity()- user, app, error, status = check_app_access(app_id, current_user_id, write=True)- if error:- return error, status+ app = require_app(app_id, write=True)data = request.get_json()if not data:@@ -159,9 +130,7 @@ def update_env_var(app_id, key):def delete_env_var(app_id, key):"""Delete an environment variable."""current_user_id = get_jwt_identity()- user, app, error, status = check_app_access(app_id, current_user_id, write=True)- if error:- return error, status+ app = require_app(app_id, write=True)success, err = EnvService.delete_env_var(app_id, key, current_user_id)@@ -179,9 +148,7 @@ def delete_env_var(app_id, key):def bulk_set_env_vars(app_id):"""Set multiple environment variables at once."""current_user_id = get_jwt_identity()- user, app, error, status = check_app_access(app_id, current_user_id, write=True)- if error:- return error, status+ app = require_app(app_id, write=True)data = request.get_json()if not data or 'env_vars' not in data:@@ -203,9 +170,7 @@ def bulk_set_env_vars(app_id):def import_env_file(app_id):"""Import environment variables from .env file content."""current_user_id = get_jwt_identity()- user, app, error, status = check_app_access(app_id, current_user_id, write=True)- if error:- return error, status+ app = require_app(app_id, write=True)data = request.get_json()if not data or 'content' not in data:@@ -243,10 +208,8 @@ def import_env_file(app_id):@jwt_required()def export_env_file(app_id):"""Export environment variables as .env file content."""- current_user_id = get_jwt_identity()- user, app, error, status = check_app_access(app_id, current_user_id)- if error:- return error, status+ user = get_current_user()+ app = require_app(app_id)include_secrets = (request.args.get('include_secrets', 'true').lower() == 'true'and ResourceGrantService.can_edit_app(user, app))@@ -263,10 +226,7 @@ def export_env_file(app_id):@jwt_required()def get_env_history(app_id):"""Get change history for environment variables."""- current_user_id = get_jwt_identity()- user, app, error, status = check_app_access(app_id, current_user_id)- if error:- return error, status+ app = require_app(app_id)limit = request.args.get('limit', 50, type=int)history = EnvService.get_history(app_id, limit=limit)@@ -282,9 +242,7 @@ def get_env_history(app_id):def clear_all_env_vars(app_id):"""Delete all environment variables for an application."""current_user_id = get_jwt_identity()- user, app, error, status = check_app_access(app_id, current_user_id, write=True)- if error:- return error, status+ app = require_app(app_id, write=True)count = EnvService.clear_all(app_id, current_user_id)diff --git a/backend/app/api/previews.py b/backend/app/api/previews.pyindex 424955f4..17562e2d 100644--- a/backend/app/api/previews.py+++ b/backend/app/api/previews.py@@ -9,39 +9,19 @@ application id, e.g. ``GET /api/v1/apps/<app_id>/previews``.from flask import Blueprint, request, jsonifyfrom flask_jwt_extended import jwt_required-from app.models import Applicationfrom app.models.application_preview import ApplicationPreviewfrom app.services.preview_service import PreviewService-from app.services.resource_grant_service import ResourceGrantService-from app.middleware.rbac import get_current_userfrom app.error_reporting import unexpected_response-from app.exceptions import not_found+from app.api._access import require_apppreviews_bp = Blueprint('previews', __name__)-def _get_app_or_404(app_id, write=False):- """Resolve the app and enforce per-app access. ``write`` requires- can_edit_app (owner/admin/editor); otherwise can_access_app (adds workspace- members). A caller without the needed tier gets a sealed 404 (no leak)."""- app = Application.query_active().filter_by(id=app_id).first()- if not app:- raise not_found('service')- user = get_current_user()- ok = ResourceGrantService.can_edit_app(user, app) if write \- else ResourceGrantService.can_access_app(user, app)- if not ok:- raise not_found('service')- return app, None--@previews_bp.route('/<int:app_id>/previews', methods=['GET'])@jwt_required()def list_previews(app_id):"""List the non-destroyed previews for an application (newest first)."""- app, err = _get_app_or_404(app_id)- if err:- return err+ app = require_app(app_id, conceal=True)previews = ApplicationPreview.query.filter(ApplicationPreview.application_id == app_id,ApplicationPreview.status != ApplicationPreview.STATUS_DESTROYED,@@ -53,9 +33,7 @@ def list_previews(app_id):@jwt_required()def get_preview_settings(app_id):"""Return the per-app preview settings (defaults when never configured)."""- app, err = _get_app_or_404(app_id)- if err:- return err+ app = require_app(app_id, conceal=True)settings = PreviewService.get_settings(app_id)return jsonify(settings.to_dict()), 200@@ -64,9 +42,7 @@ def get_preview_settings(app_id):@jwt_required()def update_preview_settings(app_id):"""Enable/disable previews and set the domain template + TTL for an app."""- app, err = _get_app_or_404(app_id, write=True)- if err:- return err+ app = require_app(app_id, write=True, conceal=True)data = request.get_json(silent=True) or {}try:result = PreviewService.enable_previews(app_id, data)@@ -80,9 +56,7 @@ def update_preview_settings(app_id):@jwt_required()def sync_previews(app_id):"""Reconcile this app's previews against its open PRs (best-effort)."""- app, err = _get_app_or_404(app_id, write=True)- if err:- return err+ app = require_app(app_id, write=True, conceal=True)result = PreviewService.sync_previews(app_id)status = 400 if result.get('error') else 200return jsonify(result), status@@ -92,9 +66,7 @@ def sync_previews(app_id):@jwt_required()def redeploy_preview(app_id, preview_id):"""Re-provision a preview for the same PR (idempotent update-in-place)."""- app, err = _get_app_or_404(app_id, write=True)- if err:- return err+ app = require_app(app_id, write=True, conceal=True)preview = ApplicationPreview.query.filter_by(id=preview_id, application_id=app_id).first()if not preview:@@ -113,9 +85,7 @@ def redeploy_preview(app_id, preview_id):@jwt_required()def destroy_preview(app_id, preview_id):"""Tear down and mark a preview destroyed."""- app, err = _get_app_or_404(app_id, write=True)- if err:- return err+ app = require_app(app_id, write=True, conceal=True)preview = ApplicationPreview.query.filter_by(id=preview_id, application_id=app_id).first()if not preview:diff --git a/backend/app/api/snapshots.py b/backend/app/api/snapshots.pyindex c53f2bfc..b6549eff 100644--- a/backend/app/api/snapshots.py+++ b/backend/app/api/snapshots.py@@ -14,30 +14,14 @@ from flask import Blueprint, request, jsonifyfrom flask_jwt_extended import jwt_required, get_jwt_identityfrom app.middleware.rbac import developer_required, get_current_user-from app.models.application import Applicationfrom app.models.deployment_snapshot import DeploymentSnapshotfrom app.services.configuration_service import ConfigurationService-from app.services.resource_grant_service import ResourceGrantService-from app.exceptions import not_found, permission_denied+from app.exceptions import not_found+from app.api._access import require_appsnapshots_bp = Blueprint('snapshots', __name__)-def _get_app_or_404(app_id, write=False):- """Resolve the app and enforce per-app access. ``write`` requires- can_edit_app (owner/admin/editor); otherwise can_access_app. A caller without- the needed tier gets a 403 (the resource itself exists)."""- app = Application.query_active().filter_by(id=app_id).first()- if not app:- raise not_found('service')- user = get_current_user()- ok = (ResourceGrantService.can_edit_app(user, app) if write- else ResourceGrantService.can_access_app(user, app))- if not ok:- raise permission_denied()- return app, None--def _get_snapshot_or_404(app_id, snap_id):"""Return (snapshot, None) or (None, error_response). Scoped to the app."""snap = DeploymentSnapshot.query.filter_by(@@ -56,9 +40,7 @@ def _get_snapshot_or_404(app_id, snap_id):@jwt_required()def list_snapshots(app_id):"""List config snapshots for an app, newest first."""- app, err = _get_app_or_404(app_id)- if err:- return err+ app = require_app(app_id)try:limit = min(int(request.args.get('limit', 50)), 200)@@ -82,9 +64,7 @@ def list_snapshots(app_id):@jwt_required()def get_snapshot(app_id, snap_id):"""Fetch a single snapshot, including its resolved config."""- _, err = _get_app_or_404(app_id)- if err:- return err+ require_app(app_id)snap, err = _get_snapshot_or_404(app_id, snap_id)if err:return err@@ -100,9 +80,7 @@ def diff_snapshot(app_id, snap_id):Query param ``against`` accepts another snapshot id or the literal``previous`` (default)."""- _, err = _get_app_or_404(app_id)- if err:- return err+ require_app(app_id)snap, err = _get_snapshot_or_404(app_id, snap_id)if err:return err@@ -145,9 +123,7 @@ def diff_snapshot(app_id, snap_id):@developer_requireddef restore_snapshot(app_id, snap_id):"""Restore a snapshot's config (env/domains) and trigger a redeploy."""- _, err = _get_app_or_404(app_id, write=True)- if err:- return err+ require_app(app_id, write=True)snap, err = _get_snapshot_or_404(app_id, snap_id)if err:return errdiff --git a/backend/app/api/waf.py b/backend/app/api/waf.pyindex 7921ed30..8b95c9ea 100644--- a/backend/app/api/waf.py+++ b/backend/app/api/waf.py@@ -9,33 +9,17 @@ Service ``ValueError``s map to HTTP 400.from flask import Blueprint, request, jsonifyfrom flask_jwt_extended import jwt_required-from app.models.application import Applicationfrom app.services.waf_service import WafService-from app.services.resource_grant_service import ResourceGrantService-from app.middleware.rbac import get_current_user, require_admin_user-from app.exceptions import not_found+from app.middleware.rbac import require_admin_user+from app.api._access import require_appwaf_bp = Blueprint('waf', __name__)-def _get_application_or_404(app_id):- """Resolve the app and enforce read access: owner / admin / grant /- workspace member. A caller who can't access it gets the same 404 as a missing- app (sealed-from-open, no existence leak)."""- application = Application.query_active().filter_by(id=app_id).first()- if not application:- raise not_found('service')- if not ResourceGrantService.can_access_app(get_current_user(), application):- raise not_found('service')- return application, None--@waf_bp.route('/applications/<int:app_id>/policy', methods=['GET'])@jwt_required()def get_policy(app_id):- _, err = _get_application_or_404(app_id)- if err:- return err+ require_app(app_id, conceal=True)policy = WafService.get_or_create_policy(app_id)return jsonify(policy.to_dict())@@ -44,9 +28,7 @@ def get_policy(app_id):@jwt_required()def update_policy(app_id):require_admin_user()- _, err = _get_application_or_404(app_id)- if err:- return err+ require_app(app_id, conceal=True)data = request.get_json() or {}try:@@ -76,9 +58,7 @@ def update_policy(app_id):@jwt_required()def apply_policy(app_id):require_admin_user()- _, err = _get_application_or_404(app_id)- if err:- return err+ require_app(app_id, conceal=True)result = WafService.apply(app_id)status = 200 if result.get('success') else 400return jsonify(result), status@@ -87,9 +67,7 @@ def apply_policy(app_id):@waf_bp.route('/applications/<int:app_id>/events', methods=['GET'])@jwt_required()def get_events(app_id):- _, err = _get_application_or_404(app_id)- if err:- return err+ require_app(app_id, conceal=True)try:limit = int(request.args.get('limit', 50))except (TypeError, ValueError):diff --git a/backend/app/services/resource_grant_service.py b/backend/app/services/resource_grant_service.pyindex 22af226b..32f87147 100644--- a/backend/app/services/resource_grant_service.py+++ b/backend/app/services/resource_grant_service.py@@ -57,6 +57,24 @@ class ResourceGrantService:return Truereturn ResourceGrantService.grant_role(user.id, 'application', app.id) == 'editor'+ @classmethod+ def get_app_for(cls, user, app_id, *, write=False, conceal=False):+ """The live application ``user`` may read (or edit, with ``write``).++ A missing app is a 404. A denied caller gets a 403, or the same 404 as+ a missing app when ``conceal`` is set, for surfaces that must not+ reveal that the app exists.+ """+ from app.exceptions import not_found, permission_denied+ from app.models.application import Application+ app = Application.query_active().filter_by(id=app_id).first()+ if app is None:+ raise not_found('service')+ allowed = cls.can_edit_app if write else cls.can_access_app+ if user is None or not allowed(user, app):+ raise not_found('service') if conceal else permission_denied()+ return app+@staticmethoddef can_operate_app(user, app):"""Operate (member+) access to an application. Folds every path to thediff --git a/backend/tests/api_controller_boundary_baseline.json b/backend/tests/api_controller_boundary_baseline.jsonindex 2767fd32..4e594988 100644--- a/backend/tests/api_controller_boundary_baseline.json+++ b/backend/tests/api_controller_boundary_baseline.json@@ -3,7 +3,7 @@"policy": "Exact reviewed inventory of direct persistence, subprocess, and filesystem mutation calls in Flask API controllers. New calls are forbidden; remove entries as controllers delegate to services.","counts": {"filesystem": 8,- "persistence": 480+ "persistence": 471},"owners": {"api/admin.py": {@@ -14,10 +14,6 @@"owner": "ServerKit backend / ai domain","rationale": "Legacy ai controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."},- "api/app_volumes.py": {- "owner": "ServerKit backend / app volumes domain",- "rationale": "Legacy app volumes controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."- },"api/apps.py": {"owner": "ServerKit backend / apps domain","rationale": "Legacy apps controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."@@ -46,10 +42,6 @@"owner": "ServerKit backend / cron domain","rationale": "Legacy cron controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."},- "api/database_engines.py": {- "owner": "ServerKit backend / database engines domain",- "rationale": "Legacy database engines controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."- },"api/databases.py": {"owner": "ServerKit backend / databases domain","rationale": "Legacy databases controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."@@ -78,10 +70,6 @@"owner": "ServerKit backend / domains domain","rationale": "Legacy domains controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."},- "api/env_vars.py": {- "owner": "ServerKit backend / env vars domain",- "rationale": "Legacy env vars controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."- },"api/environments.py": {"owner": "ServerKit backend / environments domain","rationale": "Legacy environments controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."@@ -186,10 +174,6 @@"owner": "ServerKit backend / two factor domain","rationale": "Legacy two factor controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."},- "api/waf.py": {- "owner": "ServerKit backend / waf domain",- "rationale": "Legacy waf controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."- },"api/webhooks.py": {"owner": "ServerKit backend / webhooks domain","rationale": "Legacy webhooks controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."@@ -250,8 +234,6 @@"api/ai.py::delete_conversation::persistence::db.session.delete(row)::1","api/ai.py::list_conversations::persistence::AiConversation.query.filter_by(user_id=user.id).order_by(AiConversation.updated_at.desc()).limit(100).all()::1","api/ai.py::rename_conversation::persistence::db.session.commit()::1",- "api/app_volumes.py::_load_app_for::persistence::Application.query_active().filter_by(id=app_id).first()::1",- "api/apps.py::_load_app_for_backup::persistence::Application.query_active().filter_by(id=app_id).first()::1","api/apps.py::_resolve_project_env::persistence::Environment.query.get(environment_id)::1","api/apps.py::_resolve_project_env::persistence::Project.query.get(project_id)::1","api/apps.py::_sync_manual_app_status::persistence::db.session.commit()::1",@@ -424,7 +406,6 @@"api/cron.py::_notify_run_transition::persistence::Application.query.get(int(aid))::1","api/cron.py::_notify_run_transition::persistence::Workspace.query.get(app.workspace_id)::1","api/cron.py::_validate_application_id::persistence::Application.query_active().filter_by(id=aid).first()::1",- "api/database_engines.py::_require_app_access::persistence::Application.query_active().filter_by(id=app_id).first()::1","api/databases.py::get_app_databases::persistence::Application.query_active().filter_by(id=app_id).first()::1","api/databases.py::get_app_databases::persistence::User.query.get(current_user_id)::1","api/databases.py::list_all_docker_databases::persistence::Application.query_active().filter_by(app_type='docker')::1",@@ -454,7 +435,6 @@"api/deployment_jobs.py::list_deployment_jobs::persistence::Application.query_active().filter_by(id=app_id).first()::1","api/deployment_jobs.py::list_deployment_jobs::persistence::User.query.get(current_user_id)::1","api/deployment_jobs.py::retry_deployment_job::persistence::DeploymentJob.query.get(job_id)::1",- "api/deployments.py::_access::persistence::Application.query_active().filter_by(id=app_id).first()::1","api/deployments.py::app_history::persistence::Deployment.query.filter_by(app_id=app_id).order_by(Deployment.created_at.desc()).limit(limit).all()::1","api/deployments.py::app_history::persistence::GitDeployment.query.filter_by(app_id=app_id).order_by(GitDeployment.created_at.desc()).limit(limit).all()::1","api/deployments.py::get_deployment::persistence::Deployment.query.get(deployment_id)::1",@@ -509,8 +489,6 @@"api/domains.py::update_domain::persistence::User.query.get(current_user_id)::1","api/domains.py::update_domain::persistence::db.session.commit()::1","api/domains.py::verify_domain::persistence::Domain.query_active().filter_by(id=domain_id).first()::1",- "api/env_vars.py::check_app_access::persistence::Application.query_active().filter_by(id=app_id).first()::1",- "api/env_vars.py::check_app_access::persistence::User.query.get(user_id)::1","api/environments.py::_accessible_workspace_ids::persistence::Workspace.query.all()::1","api/environments.py::create_environment::persistence::db.session.commit()::1","api/files.py::upload_file::filesystem::os.makedirs(parent)::1",@@ -542,7 +520,6 @@"api/notifications.py::test_user_notification::persistence::User.query.get(current_user_id)::1","api/notifications.py::unmute_own_email::persistence::User.query.get(current_user_id)::1","api/notifications.py::update_user_preferences::persistence::db.session.commit()::1",- "api/previews.py::_get_app_or_404::persistence::Application.query_active().filter_by(id=app_id).first()::1","api/previews.py::destroy_preview::persistence::ApplicationPreview.query.filter_by(id=preview_id, application_id=app_id).first()::1","api/previews.py::list_previews::persistence::ApplicationPreview.query.filter(ApplicationPreview.application_id == app_id, ApplicationPreview.status != ApplicationPreview.STATUS_DESTROYED).order_by(ApplicationPreview.pr_number.desc()).all()::1","api/previews.py::redeploy_preview::persistence::ApplicationPreview.query.filter_by(id=preview_id, application_id=app_id).first()::1",@@ -648,7 +625,6 @@"api/shared_resources.py::delete_variable::persistence::SharedVariable.query.get(variable_id)::1","api/shared_resources.py::update_variable::persistence::SharedVariable.query.get(variable_id)::1","api/site_imports.py::run_import::persistence::db.session.commit()::1",- "api/snapshots.py::_get_app_or_404::persistence::Application.query_active().filter_by(id=app_id).first()::1","api/snapshots.py::_get_snapshot_or_404::persistence::DeploymentSnapshot.query.filter_by(id=snap_id, application_id=app_id).first()::1","api/snapshots.py::diff_snapshot::persistence::DeploymentSnapshot.query.filter(DeploymentSnapshot.application_id == app_id, DeploymentSnapshot.created_at < snap.created_at).order_by(DeploymentSnapshot.created_at.desc(), DeploymentSnapshot.id.desc()).first()::1","api/snapshots.py::list_snapshots::persistence::DeploymentSnapshot.query.filter_by(application_id=app_id).order_by(DeploymentSnapshot.created_at.desc(), DeploymentSnapshot.id.desc()).limit(limit).all()::1",@@ -681,7 +657,6 @@"api/two_factor.py::verify_2fa_code::persistence::db.session.commit()::1","api/two_factor.py::verify_2fa_code::persistence::db.session.commit()::2","api/two_factor.py::verify_2fa_code::persistence::db.session.commit()::3",- "api/waf.py::_get_application_or_404::persistence::Application.query_active().filter_by(id=app_id).first()::1","api/webhooks.py::receive_pull_request::persistence::ApplicationPreview.query.filter_by(application_id=webhook.app_id, pr_number=pr.get('pr_number')).first()::1","api/webhooks.py::receive_pull_request::persistence::GitWebhook.query.filter_by(webhook_token=token).first()::1"]diff --git a/backend/tests/test_authz_structural_sweep.py b/backend/tests/test_authz_structural_sweep.pyindex 453b710f..1f8fd5a0 100644--- a/backend/tests/test_authz_structural_sweep.py+++ b/backend/tests/test_authz_structural_sweep.py@@ -14,10 +14,9 @@ converter form) it enforces:(``admin_required`` / ``require_app_member``) or a gate CALL in its body.Gate calls are recognised robustly: the canonical family-(``can_access_app`` / ``can_operate_app`` / ``can_edit_app`` / ``can_admin_app``-and the WP ``_guard_app`` / ``_guard_sealed_app``), PLUS any *local* helper in the-same file whose own body reaches one of those (env_vars' ``check_app_access``,-previews' ``_get_app_or_404``, waf's ``_get_application_or_404`` …) or performs an+(``require_app``, ``can_access_app`` / ``can_operate_app`` / ``can_edit_app`` /+``can_admin_app`` and the WP ``_guard_app`` / ``_guard_sealed_app``), PLUS any+*local* helper in the same file whose own body reaches one of those or performs anexplicit admin check (``is_admin``). Auto-discovering wrappers means the sweepfollows the code instead of a brittle hand-maintained name list.@@ -68,6 +67,7 @@ def _route_files():# Canonical per-app gates + WP guards. A handler (or a helper it calls) that# references any of these is authorization-gated for the target app.CANONICAL_GATES = {+ 'require_app', # app/api/_access.py: the shared per-app loader'can_access_app', 'can_operate_app', 'can_edit_app', 'can_admin_app','_guard_app', '_guard_sealed_app',}@@ -116,7 +116,7 @@ def _is_per_app(paths):def _discover_gate_helpers(source, tree):"""Names of functions in this module that themselves reach a gate — either acanonical gate call or an explicit admin check. These are the file-local- wrappers (check_app_access, _get_app_or_404, _require_admin, …) that callers+ wrappers (e.g. a file's ``_require_admin``) that callersdelegate to; recognising them lets the sweep follow the code."""helpers = set()for node in ast.walk(tree):diff --git a/backend/tests/test_require_app.py b/backend/tests/test_require_app.pynew file mode 100644index 00000000..5caf9e59--- /dev/null+++ b/backend/tests/test_require_app.py@@ -0,0 +1,61 @@+"""One per-app loader replaces nine copies.++Each copy loaded the live app and checked access, but they disagreed on+the answer for a denied caller, on return shapes, and on docstrings that+promised error tuples while the code raised. ``get_app_for`` keeps each+surface's choice explicit: 403 for a denied caller, or the same 404 as a+missing app with ``conceal``.+"""+import pytest++from app.exceptions import NotFoundError, PermissionDeniedError+from app.services.resource_grant_service import ResourceGrantService+from factories import make_application, make_user+++def people(app):+ from app import db+ owner = make_user(db, 'ra_owner')+ viewer = make_user(db, 'ra_viewer')+ stranger = make_user(db, 'ra_stranger')+ admin = make_user(db, 'ra_admin', 'admin')+ application = make_application(db, name='ra-app', user_id=owner.id)+ ResourceGrantService.grant(viewer.id, 'application', application.id, role='viewer')+ return {'owner': owner, 'viewer': viewer, 'stranger': stranger,+ 'admin': admin, 'app': application}+++def get(user, app_id, **kw):+ return ResourceGrantService.get_app_for(user, app_id, **kw)+++def test_missing_app_is_404(people):+ with pytest.raises(NotFoundError):+ get(people['admin'], 999999)+++def test_denied_caller_is_403_or_a_concealed_404(people):+ app_id = people['app'].id+ with pytest.raises(PermissionDeniedError):+ get(people['stranger'], app_id)+ with pytest.raises(NotFoundError):+ get(people['stranger'], app_id, conceal=True)+++def test_viewer_grant_reads_but_cannot_write(people):+ app_id = people['app'].id+ assert get(people['viewer'], app_id).id == app_id+ with pytest.raises(PermissionDeniedError):+ get(people['viewer'], app_id, write=True)+++def test_owner_and_admin_write(people):+ app_id = people['app'].id+ assert get(people['owner'], app_id, write=True).id == app_id+ assert get(people['admin'], app_id, write=True).id == app_id+++def test_no_user_is_denied(people):+ with pytest.raises(PermissionDeniedError):+ get(None, people['app'].id)diff --git a/backend/tests/test_route_authz_static.py b/backend/tests/test_route_authz_static.pyindex a3b7898a..a7a1e24d 100644--- a/backend/tests/test_route_authz_static.py+++ b/backend/tests/test_route_authz_static.py@@ -58,7 +58,8 @@ AUTHORIZATION_PRIMITIVES = frozenset({'require_workspace_role',# workspace / app / server access checks'get_user_role',- 'check_app_access',+ 'require_app', # app/api/_access.py+ 'get_app_for','can_access_app','can_edit_app','can_operate_app',@@ -74,7 +75,6 @@ AUTHORIZATION_PRIMITIVES = frozenset({'_endpoint_gate','_vault_gate','_ensure_group_accessible',- '_load_app_for','_require_admin',})@@ -298,7 +298,7 @@ def test_every_mutating_route_carries_an_authorization_decision(app):'\n - add a gate decorator (@admin_required / @developer_required /'' @permission_required), or''\n - call an inline authorization primitive (require_admin_user,'- ' check_app_access, _check_scope, ...), or'+ ' require_app, _check_scope, ...), or''\n - if the route is genuinely self-scoped / public-with-alt-auth /'' stateless, add it to the matching allowlist in this file with a'' specific justification.'diff --git a/docs/MIGRATION_INVENTORY.md b/docs/MIGRATION_INVENTORY.mdindex b2464064..b115c012 100644--- a/docs/MIGRATION_INVENTORY.md+++ b/docs/MIGRATION_INVENTORY.md@@ -16,12 +16,12 @@ debt. Regenerate with `python scripts/generate-migration-inventory.py`.| 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 |+| Hand-shaped {'error': ...} bodies in app/api | typed errors + the global handler | 849 | 850 | migrate when touched; new endpoints raise || 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 | 488 | 488 | migrate when touched (first-wave ratchet) |+| Controller-boundary violations (routes doing service work) | service layer extraction | 479 | 479 | 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 |-| hand-rolled form-group blocks | F2: FormField/useForm | 320 | 321 | migrate when touched |+| hand-rolled form-group blocks | F2: FormField/useForm | 316 | 321 | migrate when touched || unencoded ?k=${v} query interpolations in services/api | C4: buildQuery/encoding template | 0 | 0 | INVARIANT at 0 || raw setInterval pollers | E2: usePolling/refetchInterval | 7 | 7 | DELIBERATE RESIDUE: clock ticks, socket-fallback hooks, and sibling-repo extension timers - each listed per file || direct navigator.clipboard call sites | F3: copyToClipboard | 0 | 0 | INVARIANT at 0 |