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
feat(recycle-bin): on_restore for domains -- put the vhost back too
Juan Denise54f467a5c1a
diff --git a/backend/app/services/domain_restore.py b/backend/app/services/domain_restore.pynew file mode 100644index 00000000..d26725e6--- /dev/null+++ b/backend/app/services/domain_restore.py@@ -0,0 +1,89 @@+"""Recycle-bin hooks for Domain.++Deleting a domain does two things: it tombstones the row, and it rewrites (or+tears down) the parent app's nginx vhost so traffic stops being served. Putting+the row back only undoes the first. These hooks undo the second, and refuse the+restore up front in the cases where putting the row back would be wrong.+"""+import logging++from app import db+from app.models import Application, Domain+from app.services.nginx_service import NginxService++logger = logging.getLogger(__name__)+++def pre_restore_domain(domain):+ """Return an error string to refuse the restore, or None to allow it.++ The one that actually happens: deleting a domain FREES its name (the unique+ index only covers live rows), so someone can re-add it. Clearing the+ tombstone would then leave two live rows with the same name and blow up on+ the index at commit — a 500 for what is really an explainable conflict.+ """+ clash = (Domain.query_active()+ .filter(Domain.name == domain.name, Domain.id != domain.id)+ .first())+ if clash:+ return (f'“{domain.name}” has been added again since this was deleted '+ f'(app #{clash.application_id}). Remove the current one first, '+ f'or leave this in the bin.')++ app = Application.query.get(domain.application_id)+ if app is None:+ return ('the application this domain belonged to no longer exists, '+ 'so there is nothing to attach it back to')+ return None+++def on_restore_domain(domain):+ """Re-serve the domain: rewrite the app's vhost from its LIVE domains.++ Mirrors what delete_domain does in reverse — same NginxService.create_site+ call over the same live-domain set, which now includes this one again.+ """+ app = Application.query.get(domain.application_id)+ if app is None:+ return++ # A restored domain must not create a second primary. The one that stayed+ # live keeps the role; this row comes back as an alias.+ if domain.is_primary:+ other_primary = (Domain.query_active()+ .filter(Domain.application_id == app.id,+ Domain.is_primary.is_(True),+ Domain.id != domain.id)+ .first())+ if other_primary:+ domain.is_primary = False+ db.session.commit()++ # Only Docker apps get a generated vhost (see delete_domain / create_domain);+ # anything else has no nginx state to put back.+ if app.app_type != 'docker' or not app.port:+ return++ domains = [d.name for d in+ Domain.query_active().filter_by(application_id=app.id).all()]+ if not domains:+ return++ result = NginxService.create_site(+ name=app.name,+ app_type='docker',+ domains=domains,+ root_path=app.root_path or '',+ port=app.port,+ )+ if not result or not result.get('success'):+ # Surfaced to the caller as a restore warning: the row IS back, it just+ # is not being served yet.+ raise RuntimeError((result or {}).get('error') or 'nginx config could not be written')+ NginxService.reload()++ # NOTE: the certificate is deliberately NOT re-issued. ssl_enabled may still+ # be True with cert files that expired or were cleaned up while the domain+ # sat in the bin, and silently talking to Let's Encrypt during a restore is+ # not something a "put it back" button should do. The domain returns on+ # HTTP; re-enable SSL explicitly.diff --git a/backend/app/services/recycle_bin_service.py b/backend/app/services/recycle_bin_service.pyindex 1729ee25..6265eee2 100644--- a/backend/app/services/recycle_bin_service.py+++ b/backend/app/services/recycle_bin_service.py@@ -27,8 +27,17 @@ _REGISTRY = {}DEFAULT_RETENTION_DAYS = 30-def register(kind, model, *, label, description=None, on_restore=None, noun=None):- """Make a soft-deletable model visible to the Recycle Bin."""+def register(kind, model, *, label, description=None, on_restore=None,+ pre_restore=None, noun=None):+ """Make a soft-deletable model visible to the Recycle Bin.++ `pre_restore(row)` runs BEFORE the tombstone is cleared and returns an error+ string to refuse the restore. It exists because a partial unique index makes+ "restorable" a moving target: deleting a domain frees its name, so something+ live may hold it by the time you press Restore. Clearing the tombstone then+ violates the index and raises IntegrityError at commit — a 500 for what is+ really a normal, explainable conflict.+ """if not hasattr(model, 'deleted_at'):raise TypeError(f'{model.__name__} does not use SoftDeleteMixin')_REGISTRY[kind] = {@@ -36,6 +45,7 @@ def register(kind, model, *, label, description=None, on_restore=None, noun=None'label': label,'description': description,'on_restore': on_restore,+ 'pre_restore': pre_restore,'noun': noun or kind.replace('_', ' '),}@@ -87,6 +97,10 @@ def restore(kind, record_id):return None, 'not found'if row.deleted_at is None:return _serialize(kind, entry, row), None # already active; idempotent+ if entry['pre_restore']:+ blocked = entry['pre_restore'](row)+ if blocked:+ return None, blockedrow.restore()db.session.commit()if entry['on_restore']:@@ -134,12 +148,15 @@ def register_builtin_types():"""Wire the models that ship with the panel. Called from create_app."""from app.models.domain import Domainfrom app.models.saved_view import SavedView+ from app.services.domain_restore import on_restore_domain, pre_restore_domainregister('domain', Domain, noun='domain',label=lambda d: d.name,description=lambda d: (f'linked to app #{d.application_id}'if d.application_id else None),+ pre_restore=pre_restore_domain,+ on_restore=on_restore_domain,)register('saved_view', SavedView, noun='saved view',diff --git a/backend/tests/test_recycle_bin.py b/backend/tests/test_recycle_bin.pyindex 7709aa25..90223c40 100644--- a/backend/tests/test_recycle_bin.py+++ b/backend/tests/test_recycle_bin.py@@ -56,7 +56,13 @@ def test_a_deleted_name_can_be_reused(app, app_with_domain):assert Domain.query.filter_by(name='shop.example.com').count() == 2-def test_restore_is_idempotent(app, app_with_domain):+def test_restore_is_idempotent(app, app_with_domain, monkeypatch):+ # Domain now has an on_restore hook that rewrites the vhost; stub the nginx+ # side so this test stays about restore semantics.+ from app.services import domain_restore+ monkeypatch.setattr(domain_restore.NginxService, 'create_site', lambda **kw: {'success': True})+ monkeypatch.setattr(domain_restore.NginxService, 'reload', lambda: True)+with app.app_context():Domain.query.get(app_with_domain['domain_id']).soft_delete()db.session.commit()@@ -151,3 +157,88 @@ def test_a_deleted_view_frees_its_name_and_slug(app):assert err is Noneassert again['slug'] == 'triage' # not 'triage-2'assert saved_view_service.get_by_slug(1, 'domains', 'triage')['id'] == again['id']+++# ---- domain restore hooks ---------------------------------------------------++def test_restoring_a_domain_rewrites_the_vhost(app, app_with_domain, monkeypatch):+ """Deleting tore the domain out of the app's vhost; restoring must put it+ back, or the record is 'restored' while still not being served."""+ from app.services import domain_restore++ calls = []+ monkeypatch.setattr(domain_restore.NginxService, 'create_site',+ lambda **kw: calls.append(kw) or {'success': True})+ monkeypatch.setattr(domain_restore.NginxService, 'reload', lambda: True)++ with app.app_context():+ Domain.query.get(app_with_domain['domain_id']).soft_delete()+ db.session.commit()++ item, err = recycle_bin_service.restore('domain', app_with_domain['domain_id'])+ assert err is None and item is not None+ assert len(calls) == 1+ assert 'shop.example.com' in calls[0]['domains']+++def test_restore_is_refused_when_the_name_was_taken_again(app, app_with_domain):+ """Deleting frees the name (the unique index covers live rows only), so the+ conflict is reachable — and must be a readable refusal, not an+ IntegrityError at commit."""+ with app.app_context():+ Domain.query.get(app_with_domain['domain_id']).soft_delete()+ db.session.commit()+ db.session.add(Domain(name='shop.example.com',+ application_id=app_with_domain['app_id']))+ db.session.commit()++ item, err = recycle_bin_service.restore('domain', app_with_domain['domain_id'])+ assert item is None+ assert 'added again' in err+ # still tombstoned — a refused restore must not half-apply+ assert Domain.query.get(app_with_domain['domain_id']).deleted_at is not None+++def test_restore_is_refused_when_the_app_is_gone(app, app_with_domain):+ with app.app_context():+ Domain.query.get(app_with_domain['domain_id']).soft_delete()+ db.session.query(Application).filter_by(id=app_with_domain['app_id']).delete()+ db.session.commit()++ item, err = recycle_bin_service.restore('domain', app_with_domain['domain_id'])+ assert item is None and 'no longer exists' in err+++def test_restored_domain_does_not_become_a_second_primary(app, app_with_domain, monkeypatch):+ from app.services import domain_restore+ monkeypatch.setattr(domain_restore.NginxService, 'create_site', lambda **kw: {'success': True})+ monkeypatch.setattr(domain_restore.NginxService, 'reload', lambda: True)++ with app.app_context():+ first = Domain.query.get(app_with_domain['domain_id'])+ first.is_primary = True+ first.soft_delete()+ db.session.add(Domain(name='new-primary.example.com', is_primary=True,+ application_id=app_with_domain['app_id']))+ db.session.commit()++ recycle_bin_service.restore('domain', app_with_domain['domain_id'])+ primaries = Domain.query_active().filter_by(+ application_id=app_with_domain['app_id'], is_primary=True).count()+ assert primaries == 1+++def test_a_failing_vhost_rewrite_warns_but_keeps_the_restore(app, app_with_domain, monkeypatch):+ from app.services import domain_restore+ monkeypatch.setattr(domain_restore.NginxService, 'create_site',+ lambda **kw: {'success': False, 'error': 'nginx -t failed'})++ with app.app_context():+ Domain.query.get(app_with_domain['domain_id']).soft_delete()+ db.session.commit()++ item, err = recycle_bin_service.restore('domain', app_with_domain['domain_id'])+ # The row IS back; only the side effect failed. Say so, don't roll back.+ assert item is not None+ assert 'nginx -t failed' in err+ assert Domain.query.get(app_with_domain['domain_id']).deleted_at is None