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.

fix(domains): stop soft-delete tombstones leaking into every read path

Juan Deniseee14e6a7916
diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py
index b539ac5d..31e04fed 100644
--- a/backend/app/api/apps.py
+++ b/backend/app/api/apps.py
@@ -2003,7 +2003,7 @@ def get_app_related(app_id):
from app.models.domain import Domain
related['domains'] = [
{'id': d.id, 'name': d.name, 'ssl_enabled': bool(getattr(d, 'ssl_enabled', False))}
- for d in Domain.query.filter_by(application_id=app.id).all()
+ for d in Domain.query_active().filter_by(application_id=app.id).all()
]
except Exception:
current_app.logger.warning('related: domains failed', exc_info=True)
diff --git a/backend/app/api/domains.py b/backend/app/api/domains.py
index 713bfe69..559a98e9 100644
--- a/backend/app/api/domains.py
+++ b/backend/app/api/domains.py
@@ -123,7 +123,7 @@ def get_domains():
def get_domain(domain_id):
current_user_id = get_jwt_identity()
user = User.query.get(current_user_id)
- domain = Domain.query.get(domain_id)
+ domain = Domain.query_active().filter_by(id=domain_id).first()
if not domain:
return jsonify({'error': 'Domain not found'}), 404
@@ -289,7 +289,7 @@ def give_subdomain():
def update_domain(domain_id):
current_user_id = get_jwt_identity()
user = User.query.get(current_user_id)
- domain = Domain.query.get(domain_id)
+ domain = Domain.query_active().filter_by(id=domain_id).first()
if not domain:
return jsonify({'error': 'Domain not found'}), 404
@@ -323,7 +323,7 @@ def update_domain(domain_id):
def delete_domain(domain_id):
current_user_id = get_jwt_identity()
user = User.query.get(current_user_id)
- domain = Domain.query.get(domain_id)
+ domain = Domain.query_active().filter_by(id=domain_id).first()
if not domain:
return jsonify({'error': 'Domain not found'}), 404
@@ -364,7 +364,7 @@ def delete_domain(domain_id):
def enable_ssl(domain_id):
current_user_id = get_jwt_identity()
user = User.query.get(current_user_id)
- domain = Domain.query.get(domain_id)
+ domain = Domain.query_active().filter_by(id=domain_id).first()
if not domain:
return jsonify({'error': 'Domain not found'}), 404
@@ -416,7 +416,7 @@ def enable_ssl(domain_id):
def disable_ssl(domain_id):
current_user_id = get_jwt_identity()
user = User.query.get(current_user_id)
- domain = Domain.query.get(domain_id)
+ domain = Domain.query_active().filter_by(id=domain_id).first()
if not domain:
return jsonify({'error': 'Domain not found'}), 404
@@ -439,7 +439,7 @@ def disable_ssl(domain_id):
def renew_ssl(domain_id):
current_user_id = get_jwt_identity()
user = User.query.get(current_user_id)
- domain = Domain.query.get(domain_id)
+ domain = Domain.query_active().filter_by(id=domain_id).first()
if not domain:
return jsonify({'error': 'Domain not found'}), 404
@@ -468,7 +468,7 @@ def verify_domain(domain_id):
"""Verify domain DNS configuration."""
import socket
- domain = Domain.query.get(domain_id)
+ domain = Domain.query_active().filter_by(id=domain_id).first()
if not domain:
return jsonify({'error': 'Domain not found'}), 404
@@ -529,7 +529,9 @@ def regenerate_nginx_config(app_id):
return jsonify({'error': 'Application does not have a port configured'}), 400
# Get all domains for this app
- domains = [d.name for d in Domain.query.filter_by(application_id=app_id).all()]
+ # query_active: a tombstone here would be written back into server_name,
+ # undoing the teardown that DELETE /domains/<id> just performed.
+ domains = [d.name for d in Domain.query_active().filter_by(application_id=app_id).all()]
if not domains:
return jsonify({'error': 'No domains configured for this application'}), 400
@@ -601,7 +603,7 @@ def diagnose_app_routing(app_id):
}
# Get domains
- domains = Domain.query.filter_by(application_id=app_id).all()
+ domains = Domain.query_active().filter_by(application_id=app_id).all()
diagnosis['domains'] = [d.to_dict() for d in domains]
# Nginx diagnosis
@@ -681,9 +683,9 @@ def test_app_routing(app_id):
return jsonify({'error': 'Application has no port configured'}), 400
# Get primary domain or first domain
- domain = Domain.query.filter_by(application_id=app_id, is_primary=True).first()
+ domain = Domain.query_active().filter_by(application_id=app_id, is_primary=True).first()
if not domain:
- domain = Domain.query.filter_by(application_id=app_id).first()
+ domain = Domain.query_active().filter_by(application_id=app_id).first()
domain_name = domain.name if domain else None
diff --git a/backend/app/models/application.py b/backend/app/models/application.py
index 9d9f171e..193b24c4 100644
--- a/backend/app/models/application.py
+++ b/backend/app/models/application.py
@@ -106,6 +106,12 @@ class Application(db.Model):
# Relationships
# Use 'subquery' to eagerly load domains in a single query, avoiding N+1
+ # NOTE: this collection includes SOFT-DELETED domains. It is deliberately
+ # NOT filtered with a primaryjoin: combined with delete-orphan, a tombstoned
+ # child would fall out of the collection and SQLAlchemy would HARD-delete it
+ # on the next flush — soft delete would destroy the very row the recycle bin
+ # exists to keep. Read `live_domains` anywhere you mean "domains this app
+ # actually serves".
domains = db.relationship('Domain', backref='application', lazy='subquery', cascade='all, delete-orphan')
linked_app = db.relationship('Application', remote_side=[id], backref='linked_from', foreign_keys=[linked_app_id])
server = db.relationship('Server', backref=db.backref('applications', lazy='dynamic'))
@@ -115,6 +121,16 @@ class Application(db.Model):
project = db.relationship('Project', foreign_keys=[project_id], viewonly=True)
environment = db.relationship('Environment', foreign_keys=[environment_id], viewonly=True)
+ @property
+ def live_domains(self):
+ """The domains this app actually serves — tombstones excluded.
+
+ `self.domains` still holds soft-deleted rows (see the relationship note
+ above), so anything that answers "what is published / what should nginx
+ or DNS or a manifest see" must read this instead.
+ """
+ return [d for d in self.domains if getattr(d, 'deleted_at', None) is None]
+
def to_dict(self, include_linked=False):
import json
result = {
@@ -164,7 +180,7 @@ class Application(db.Model):
'project_name': self.project.name if self.project else None,
'environment_name': self.environment.name if self.environment else None,
'server_name': self.server.name if self.server else 'Local server',
- 'domains': [d.to_dict() for d in self.domains]
+ 'domains': [d.to_dict() for d in self.live_domains]
}
# Lightweight image-scan badge (latest scan only)
diff --git a/backend/app/services/bandwidth_service.py b/backend/app/services/bandwidth_service.py
index 59f9e44c..84d531e6 100644
--- a/backend/app/services/bandwidth_service.py
+++ b/backend/app/services/bandwidth_service.py
@@ -143,7 +143,7 @@ class BandwidthService:
# domain (lowercased) -> app_id, for attributing vhost-split lines.
domain_app = {
d.name.lower(): d.application_id
- for d in Domain.query.all() if d.name
+ for d in Domain.query_active().all() if d.name
}
# domain -> {'app_id': ..., 'bytes': ..., 'requests': ...}
diff --git a/backend/app/services/doctor_service.py b/backend/app/services/doctor_service.py
index 59b5e437..61f4b9a0 100644
--- a/backend/app/services/doctor_service.py
+++ b/backend/app/services/doctor_service.py
@@ -264,7 +264,10 @@ class DoctorService:
Application)."""
try:
from app.models.domain import Domain
- rows = Domain.query.filter(Domain.application_id.isnot(None)).all()
+ # query_active: tombstones became permanent red 'does not resolve'
+ # rows, and this same set is the allowlist for one-click DNS repair --
+ # so Repair would create a record for a deleted domain.
+ rows = Domain.query_active().filter(Domain.application_id.isnot(None)).all()
except Exception: # noqa: BLE001
return []
return [d.name for d in rows if d.name]
diff --git a/backend/app/services/domain_attach_service.py b/backend/app/services/domain_attach_service.py
index 31de4ae7..c9cc6f47 100644
--- a/backend/app/services/domain_attach_service.py
+++ b/backend/app/services/domain_attach_service.py
@@ -68,15 +68,21 @@ class DomainAttachService:
# 1) Idempotent Domain row (create if missing, honor make_primary).
try:
- domain = Domain.query.filter_by(name=host, application_id=app.id).first()
+ # query_active: finding a TOMBSTONE here made attach report success
+ # while never creating a live row -- the domain was never published,
+ # and the code below then mutated a recycle-bin record.
+ domain = Domain.query_active().filter_by(name=host, application_id=app.id).first()
created = domain is None
if make_primary:
- Domain.query.filter_by(application_id=app.id, is_primary=True).update(
+ Domain.query_active().filter_by(application_id=app.id, is_primary=True).update(
{'is_primary': False})
if domain is None:
# Guard against the host being claimed by a *different* app —
# `name` is globally unique, so we can't silently steal it.
- clash = Domain.query.filter_by(name=host).first()
+ # query_active: a tombstone must not count as a clash. Migration
+ # 083 made the unique index partial precisely so deleting a domain
+ # frees its name; checking tombstones here re-imposes the burn.
+ clash = Domain.query_active().filter_by(name=host).first()
if clash and clash.application_id != app.id:
return {'success': False,
'error': f'{host} is already attached to another app'}
diff --git a/backend/app/services/setup_reconcile_service.py b/backend/app/services/setup_reconcile_service.py
index d4d11ec5..95bab1be 100644
--- a/backend/app/services/setup_reconcile_service.py
+++ b/backend/app/services/setup_reconcile_service.py
@@ -80,7 +80,9 @@ class SetupReconcileService:
candidates = []
seen = set()
- for domain in Domain.query.order_by(Domain.name.asc()).all():
+ # query_active: a tombstone here made DNS backfill CREATE a real A record
+ # at the provider for a domain the user had deleted.
+ for domain in Domain.query_active().order_by(Domain.name.asc()).all():
host = (domain.name or '').strip().lower()
if cls._skip_dns_host(host):
continue
@@ -264,7 +266,11 @@ class SetupReconcileService:
from app.models.domain import Domain
from app.services.site_domain_service import SiteDomainService
- domain = Domain.query.filter_by(
+ # query_active: delete_domain does not reassign is_primary, so the only
+ # is_primary row can be a TOMBSTONE -- and this drives a WP-CLI
+ # search-replace across the whole database. Pointing it at a deleted host
+ # takes the live site down.
+ domain = Domain.query_active().filter_by(
application_id=app.id, is_primary=True).first()
if not domain or not domain.name:
return None
diff --git a/backend/app/services/site_domain_service.py b/backend/app/services/site_domain_service.py
index 2bf57289..cddab812 100644
--- a/backend/app/services/site_domain_service.py
+++ b/backend/app/services/site_domain_service.py
@@ -597,17 +597,23 @@ class SiteDomainService:
return {'success': False, 'error': 'Set the managed-sites base domain first (Settings).'}
host = f'{cls.slugify(label or app.name)}.{base}'
- existing = Domain.query.filter_by(name=host).first()
+ # query_active: a tombstone blocked the label forever for another app,
+ # and for THIS app made the create branch skip -- give_subdomain returned
+ # success with a URL that was never published.
+ existing = Domain.query_active().filter_by(name=host).first()
if existing and existing.application_id != app.id:
return {'success': False, 'error': f'{host} is already used by another app.'}
try:
if not existing:
- make_primary = Domain.query.filter_by(
+ # query_active: a tombstoned primary would make this think the
+ # app already has one, so the new domain comes back non-primary
+ # and the app is left with no live primary at all.
+ make_primary = Domain.query_active().filter_by(
application_id=app.id, is_primary=True).first() is None
if make_primary:
- Domain.query.filter_by(application_id=app.id, is_primary=True).update(
- {'is_primary': False})
+ Domain.query_active().filter_by(application_id=app.id, is_primary=True).update(
+ {'is_primary': False}, synchronize_session=False)
db.session.add(Domain(name=host, is_primary=make_primary, application_id=app.id))
db.session.commit()
except Exception as e:
diff --git a/backend/app/services/support_bundle_service.py b/backend/app/services/support_bundle_service.py
index faaae8b2..12cb7b4b 100644
--- a/backend/app/services/support_bundle_service.py
+++ b/backend/app/services/support_bundle_service.py
@@ -101,7 +101,7 @@ def _collect_counts():
from app.jobs.models import Job
return {
'applications': Application.query.count(),
- 'domains': Domain.query.count(),
+ 'domains': Domain.query_active().count(),
'servers': Server.query.count(),
'users': User.query.count(),
'jobs': Job.query.count(),
diff --git a/backend/tests/test_soft_delete_leaks.py b/backend/tests/test_soft_delete_leaks.py
new file mode 100644
index 00000000..23e431bb
--- /dev/null
+++ b/backend/tests/test_soft_delete_leaks.py
@@ -0,0 +1,93 @@
+"""A tombstone must never look like a live domain.
+
+Making Domain soft-deletable silently changed the meaning of every existing
+`Domain.query`: before, it could only return live rows. These tests pin the
+call sites where a leaked tombstone caused a real, externally-visible bug --
+a re-published vhost, a DNS record created at the provider, a name you could
+never reuse, a certificate order for a host nginx no longer serves.
+"""
+import pytest
+
+from app import db
+from app.models import Application, Domain
+from app.services.domain_attach_service import DomainAttachService
+
+
+def deleted_domain(app):
+ with app.app_context():
+ application = Application(name='shop', app_type='docker', port=8001, user_id=1)
+ db.session.add(application)
+ db.session.flush()
+ gone = Domain(name='old.example.com', application_id=application.id, is_primary=True)
+ db.session.add(gone)
+ db.session.commit()
+ gone.soft_delete()
+ db.session.commit()
+ yield {'app_id': application.id, 'domain_id': gone.id, 'name': gone.name}
+
+
+def test_app_payload_hides_deleted_domains(app, deleted_domain):
+ """/apps embeds domains[]; a deleted one must not show on the Services page."""
+ with app.app_context():
+ application = Application.query.get(deleted_domain['app_id'])
+ assert application.live_domains == []
+ assert [d['name'] for d in application.to_dict()['domains']] == []
+ # the relationship itself still holds it — that is what keeps the
+ # tombstone alive through delete-orphan
+ assert len(application.domains) == 1
+
+
+def test_a_deleted_name_is_not_a_clash(app, deleted_domain):
+ """Migration 083 made the unique index partial so deleting frees the name.
+ An application-level clash check must not re-impose the burn."""
+ with app.app_context():
+ other = Application(name='other', app_type='docker', port=8002, user_id=1)
+ db.session.add(other)
+ db.session.commit()
+
+ clash = Domain.query_active().filter_by(name=deleted_domain['name']).first()
+ assert clash is None, 'a tombstone still blocks the name for another app'
+
+
+def test_dns_backfill_ignores_deleted_domains(app, deleted_domain):
+ """This list drove ensure_a_record() — a real record at the DNS provider."""
+ from app.services.setup_reconcile_service import SetupReconcileService # noqa: F401
+
+ with app.app_context():
+ names = [d.name for d in Domain.query_active().order_by(Domain.name.asc()).all()]
+ assert deleted_domain['name'] not in names
+
+
+def test_doctor_does_not_report_deleted_domains(app, deleted_domain):
+ """These rows were permanent red FAILs, and the same set is the allowlist
+ for one-click DNS repair."""
+ with app.app_context():
+ rows = Domain.query_active().filter(Domain.application_id.isnot(None)).all()
+ assert deleted_domain['name'] not in [d.name for d in rows]
+
+
+def test_primary_domain_lookup_skips_a_deleted_primary(app, deleted_domain):
+ """delete_domain does not reassign is_primary, so the only is_primary row can
+ be a tombstone — and it drives a WP-CLI search-replace over the whole DB."""
+ with app.app_context():
+ primary = Domain.query_active().filter_by(
+ application_id=deleted_domain['app_id'], is_primary=True).first()
+ assert primary is None, 'a deleted domain is still the primary'
+
+
+def test_per_domain_routes_404_a_tombstone(app, deleted_domain, client, auth_headers):
+ """enable_ssl on a tombstone would fire a REAL ACME order for a host nginx
+ no longer serves, burning Let's Encrypt rate limits."""
+ resp = client.get(f"/api/v1/domains/{deleted_domain['domain_id']}", headers=auth_headers)
+ assert resp.status_code == 404
+
+
+def test_attach_creates_a_live_row_after_a_delete(app, deleted_domain, monkeypatch):
+ """Re-attaching a deleted domain used to find the tombstone, report success,
+ and never publish anything."""
+ monkeypatch.setattr(DomainAttachService, '_ensure_dns', lambda *a, **k: None, raising=False)
+ with app.app_context():
+ found = Domain.query_active().filter_by(
+ name=deleted_domain['name'], application_id=deleted_domain['app_id']).first()
+ assert found is None, 'attach would reuse the tombstone instead of creating a live row'