mirror of
https://github.com/jhd3197/ServerKit.git
synced 2026-11-09 05:24:49 +09:00
Plan 70. Domain went through this and TEN read paths were wrong, four with
effects outside the panel. Application has 211 call sites across 68 files and
drives more -- container lifecycles, nginx, backups, registry pulls, the OS
crontab -- so it was audited in full first (docs/plans/70_...md). 180 sites are
now query_active(); the 35 left unfiltered are each commented in place.
**The delete / purge split is what makes the tombstone honest.** delete_app used
to run compose_down(volumes=True) and rmtree(). Keeping a tombstone AND doing
that would put a Restore button next to a row whose data the delete had already
destroyed -- the one promise a recycle bin cannot break. So:
DELETE containers down (VOLUMES KEPT), vhost removed, firewall closed,
cron suspended, row tombstoned. All reversible.
RESTORE vhost rewritten, firewall reopened, cron resumed. Containers left
STOPPED -- "put it back" must not silently start processes or open
ports, the same reasoning that stops domain restore re-issuing certs.
PURGE volumes removed, uploaded source deleted, cron detached.
register() gained on_purge for that, wired into BOTH purge paths. And
purge_expired had NO scheduler -- fine when a tombstone was just a row, not fine
when it holds data volumes and a source tree, so a daily builtin job now runs
it. Without that, "kept until purge" would have meant kept forever and delete
would have quietly stopped reclaiming disk.
A side effect worth naming: the old _remove_data_flag protection for database
engines is now the DEFAULT for every app, and the flag is carried into
?purge=true so an explicit skip-the-bin delete still honours it.
**Cron was the blocker with no mechanical answer.** before_delete never fires on
a soft delete, and clear_application is LOSSY -- it nulls the association
without recording it, so nothing could put it back. suspend_for_application
instead disables only the jobs that were CURRENTLY ENABLED and stamps each
suspended_by_app; resume re-enables exactly those. That flag is the whole point:
without it a restore switches back on jobs the user deliberately turned off.
clear_application survives as purge-only, where lossiness is correct.
**The indirect reach (audit 3.1) is the class that grep cannot find.**
ContainerSleepPolicy, BackupPolicy, DeploymentJob and WafPolicy are enumerated
on a SCHEDULE and resolve application_id afterwards, so they never appear in a
search for Application.query. Left alone, a tombstoned app's sleep policy is
swept forever and wake_app restarts the containers the delete tore down. Those
loops test Application.deleted_ids().
Deliberately NOT scoped: reservation checks (port, name, directory) -- a
tombstone must keep holding those or a new app takes them and the restore is
refused; api/git.py's webhook VISIBILITY gate, which falls through to
"panel-wide visible" so hiding a tombstone would WIDEN access; and cron
attribution, which only labels a row.
Verified: 15 new tests, the migration replayed on a fresh DB (a tombstone frees
its private_slug, two live rows still collide), and a full delete -> restore
round trip. The 20 remaining full-suite failures are the known
serverkit-wordpress-not-installed class and are identical on a clean tree.
Two traps caught by testing, both recorded in the plan: a bad import made the
ENTIRE purge cleanup silently no-op while purge() still reported success
(_run_purge_hook swallows by design, so assert on the warning, not just ok), and
private_slug had to lose unique=True at the MODEL level or a models-built
database burns the slug regardless of the migration.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
133 lines
4.2 KiB
Python
133 lines
4.2 KiB
Python
# Bucket: PER-APP (plan 29 #9). Reads are scoped to callers who can access the
|
|
# app (can_access_app); mutations + install stay admin-only.
|
|
"""Per-application WAF (ModSecurity v3 + OWASP CRS) API.
|
|
|
|
Routes are mounted at ``/api/v1/waf``. Reads require access to the target app;
|
|
mutations and install require an admin user (mirrors ``app/api/dns_zones.py``).
|
|
Service ``ValueError``s map to HTTP 400.
|
|
"""
|
|
from flask import Blueprint, request, jsonify
|
|
from flask_jwt_extended import jwt_required
|
|
|
|
from app.models.application import Application
|
|
from app.services.waf_service import WafService
|
|
from app.services.resource_grant_service import ResourceGrantService
|
|
|
|
waf_bp = Blueprint('waf', __name__)
|
|
|
|
|
|
def get_current_user():
|
|
from flask_jwt_extended import get_jwt_identity
|
|
from app.models.user import User
|
|
return User.query.get(get_jwt_identity())
|
|
|
|
|
|
def _require_admin():
|
|
"""Return None if the caller is an admin, else a (response, status) tuple."""
|
|
user = get_current_user()
|
|
if not user or not user.is_admin:
|
|
return jsonify({'error': 'Admin access required'}), 403
|
|
return None
|
|
|
|
|
|
def _get_application_or_404(app_id):
|
|
"""Resolve the app and enforce read access (plan 29 #9): 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:
|
|
return None, (jsonify({'error': 'Application not found'}), 404)
|
|
if not ResourceGrantService.can_access_app(get_current_user(), application):
|
|
return None, (jsonify({'error': 'Application not found'}), 404)
|
|
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
|
|
policy = WafService.get_or_create_policy(app_id)
|
|
return jsonify(policy.to_dict())
|
|
|
|
|
|
@waf_bp.route('/applications/<int:app_id>/policy', methods=['PUT'])
|
|
@jwt_required()
|
|
def update_policy(app_id):
|
|
admin_err = _require_admin()
|
|
if admin_err:
|
|
return admin_err
|
|
_, err = _get_application_or_404(app_id)
|
|
if err:
|
|
return err
|
|
|
|
data = request.get_json() or {}
|
|
try:
|
|
policy = WafService.set_policy(
|
|
app_id,
|
|
mode=data.get('mode'),
|
|
paranoia_level=data.get('paranoia_level'),
|
|
anomaly_threshold=data.get('anomaly_threshold'),
|
|
disabled_rule_ids=data.get('disabled_rule_ids'),
|
|
)
|
|
except ValueError as e:
|
|
return jsonify({'error': str(e)}), 400
|
|
|
|
# Best-effort enforcement: never fail the policy write because nginx /
|
|
# ModSecurity isn't present on the host.
|
|
try:
|
|
apply_result = WafService.apply(app_id)
|
|
except Exception as e: # pragma: no cover - defensive
|
|
apply_result = {'success': False, 'error': str(e)}
|
|
|
|
response = policy.to_dict()
|
|
response['apply'] = apply_result
|
|
return jsonify(response)
|
|
|
|
|
|
@waf_bp.route('/applications/<int:app_id>/apply', methods=['POST'])
|
|
@jwt_required()
|
|
def apply_policy(app_id):
|
|
admin_err = _require_admin()
|
|
if admin_err:
|
|
return admin_err
|
|
_, err = _get_application_or_404(app_id)
|
|
if err:
|
|
return err
|
|
result = WafService.apply(app_id)
|
|
status = 200 if result.get('success') else 400
|
|
return jsonify(result), status
|
|
|
|
|
|
@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
|
|
try:
|
|
limit = int(request.args.get('limit', 50))
|
|
except (TypeError, ValueError):
|
|
limit = 50
|
|
limit = max(1, min(500, limit))
|
|
events = WafService.events(app_id, limit=limit)
|
|
return jsonify({'events': events, 'count': len(events)})
|
|
|
|
|
|
@waf_bp.route('/status', methods=['GET'])
|
|
@jwt_required()
|
|
def status():
|
|
return jsonify({'installed': WafService.modsecurity_installed()})
|
|
|
|
|
|
@waf_bp.route('/install', methods=['POST'])
|
|
@jwt_required()
|
|
def install():
|
|
admin_err = _require_admin()
|
|
if admin_err:
|
|
return admin_err
|
|
result = WafService.install_modsecurity()
|
|
status_code = 200 if result.get('success') else 400
|
|
return jsonify(result), status_code
|