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): adding or removing one domain no longer drops the site to HTTP

Juan Deniscb1580214a9b
diff --git a/backend/app/api/domains.py b/backend/app/api/domains.py
index 6317dbc0..713bfe69 100644
--- a/backend/app/api/domains.py
+++ b/backend/app/api/domains.py
@@ -14,6 +14,23 @@ from app.services.resource_grant_service import ResourceGrantService
domains_bp = Blueprint('domains', __name__)
+def _publish_app_vhost(app):
+ """(Re)write and enable an app's vhost from its LIVE domains.
+
+ One seam for both add and remove, so the two can never disagree about what
+ the served config should look like. Returns the shape these routes already
+ put under the response's ``nginx`` key; never raises.
+ """
+ from app.services.site_domain_service import SiteDomainService
+
+ result = SiteDomainService.write_app_vhost(app) or {}
+ nginx = result.get('nginx')
+ warning = result.get('warning')
+ if warning:
+ nginx = dict(nginx or {}, warning=warning)
+ return nginx
+
+
def validate_and_sanitize_domain(domain_name: str) -> tuple:
"""Validate and sanitize a domain name for nginx server_name.
@@ -186,26 +203,16 @@ def create_domain():
db.session.add(domain)
db.session.commit()
- # Auto-create nginx config for Docker apps
- nginx_result = None
- if app.app_type == 'docker' and app.port:
- # Get all domains for this app to include in nginx config
- all_domains = [d.name for d in Domain.query_active().filter_by(application_id=application_id).all()]
-
- # Create nginx site config
- nginx_result = NginxService.create_site(
- name=app.name,
- app_type='docker',
- domains=all_domains,
- root_path=app.root_path or '',
- port=app.port
- )
-
- # Enable the site if creation was successful
- if nginx_result.get('success'):
- enable_result = NginxService.enable_site(app.name)
- if not enable_result.get('success'):
- nginx_result['warning'] = f"Site created but not enabled: {enable_result.get('error')}"
+ # Publish through SiteDomainService rather than a bare create_site.
+ #
+ # create_site takes ssl_cert/ssl_key/micro_cache as arguments and this call
+ # passed none of them, so the regenerated vhost came out HTTP-only and
+ # cache-less: adding a domain to a site covered by a base wildcard cert
+ # silently knocked the WHOLE site back to plain HTTP, and dropped its
+ # micro-cache directives. app_vhost_kwargs re-resolves both, picks the right
+ # template for the app type (php/static/flask/django too, not just docker),
+ # and enables the site.
+ nginx_result = _publish_app_vhost(app)
response = {
'message': 'Domain created successfully',
@@ -332,27 +339,19 @@ def delete_domain(domain_id):
domain.soft_delete(user_id=current_user_id)
db.session.commit()
- # Update nginx config for Docker apps
+ # Re-publish without the removed domain. Same seam as create_domain, for the
+ # same reason: the old bare create_site here dropped the wildcard cert and
+ # the micro-cache from the vhost, so removing ONE domain quietly took the
+ # site's other domains off HTTPS. It also only ran for docker apps, leaving
+ # php/static/flask vhosts still advertising the deleted name.
nginx_result = None
- if app.app_type == 'docker' and app.port:
- remaining_domains = [d.name for d in
- Domain.query_active().filter_by(application_id=application_id).all()]
-
- if remaining_domains:
- # Update nginx config with remaining domains
- nginx_result = NginxService.create_site(
- name=app.name,
- app_type='docker',
- domains=remaining_domains,
- root_path=app.root_path or '',
- port=app.port
- )
- if nginx_result.get('success'):
- NginxService.reload()
- else:
- # No domains left, disable and delete the site
- NginxService.disable_site(app.name)
- nginx_result = NginxService.delete_site(app.name)
+ remaining = Domain.query_active().filter_by(application_id=application_id).count()
+ if remaining:
+ nginx_result = _publish_app_vhost(app)
+ elif app.app_type == 'docker' and app.port:
+ # Nothing left to serve: take the site down entirely.
+ NginxService.disable_site(app.name)
+ nginx_result = NginxService.delete_site(app.name)
return jsonify({
'message': 'Domain deleted successfully',
diff --git a/backend/app/services/site_domain_service.py b/backend/app/services/site_domain_service.py
index 8bb8f65c..2bf57289 100644
--- a/backend/app/services/site_domain_service.py
+++ b/backend/app/services/site_domain_service.py
@@ -527,7 +527,12 @@ class SiteDomainService:
"""
from app.models.domain import Domain
- domains = [d.name for d in Domain.query.filter_by(application_id=app.id).all()]
+ # query_active, not query: Domain is soft-deleted now, so a plain query
+ # returns tombstones and this renderer would write a deleted domain
+ # straight back into server_name — the vhost would keep serving a domain
+ # the user removed, and drift detection (which renders through this same
+ # function) would report the correct config as drifted.
+ domains = [d.name for d in Domain.query_active().filter_by(application_id=app.id).all()]
if not domains:
return None, None
diff --git a/backend/tests/test_domain_vhost_ssl.py b/backend/tests/test_domain_vhost_ssl.py
new file mode 100644
index 00000000..ae98515e
--- /dev/null
+++ b/backend/tests/test_domain_vhost_ssl.py
@@ -0,0 +1,84 @@
+"""Adding or removing ONE domain must not take the site's others off HTTPS.
+
+Both routes used to call NginxService.create_site directly with no
+ssl_cert/ssl_key/micro_cache, so the regenerated vhost came out HTTP-only and
+cache-less. On a site covered by a base wildcard cert that meant touching any
+domain silently dropped the WHOLE site to plain HTTP — invisible until someone
+loaded it. Both now go through SiteDomainService, which re-resolves the cert,
+the cache flag and the app-type template.
+"""
+import pytest
+
+from app import db
+from app.models import Application, Domain
+from app.services.site_domain_service import SiteDomainService
+
+
+def wildcard_site(app, monkeypatch):
+ """An app on two subdomains of a base whose wildcard HTTPS is enabled."""
+ monkeypatch.setattr(SiteDomainService, 'covering_base',
+ classmethod(lambda cls, host: 'acme.dev' if host.endswith('.acme.dev') else None))
+ monkeypatch.setattr(SiteDomainService, 'https_enabled', classmethod(lambda cls, base: True))
+ monkeypatch.setattr(SiteDomainService, 'wildcard_cert_paths',
+ classmethod(lambda cls, base: ('/etc/le/live/acme.dev/fullchain.pem',
+ '/etc/le/live/acme.dev/privkey.pem')))
+ with app.app_context():
+ application = Application(name='shop', app_type='docker', port=8001,
+ user_id=1, micro_cache_enabled=True)
+ db.session.add(application)
+ db.session.flush()
+ a = Domain(name='a.acme.dev', application_id=application.id, is_primary=True)
+ b = Domain(name='b.acme.dev', application_id=application.id)
+ db.session.add_all([a, b])
+ db.session.commit()
+ yield {'app_id': application.id, 'a': a.id, 'b': b.id}
+
+
+def test_vhost_kwargs_carry_the_wildcard_cert_and_cache(app, wildcard_site):
+ with app.app_context():
+ application = Application.query.get(wildcard_site['app_id'])
+ kwargs, reason = SiteDomainService.app_vhost_kwargs(application)
+
+ assert reason is None
+ assert kwargs['ssl_cert'].endswith('fullchain.pem'), 'wildcard cert dropped -> site falls back to HTTP'
+ assert kwargs['ssl_key'].endswith('privkey.pem')
+ assert kwargs['micro_cache'] is True
+ assert sorted(kwargs['domains']) == ['a.acme.dev', 'b.acme.dev']
+
+
+def test_a_soft_deleted_domain_is_not_written_back_into_the_vhost(app, wildcard_site):
+ """The renderer used Domain.query, which now returns tombstones — it would
+ have put a deleted domain straight back into server_name."""
+ with app.app_context():
+ Domain.query.get(wildcard_site['b']).soft_delete()
+ db.session.commit()
+
+ application = Application.query.get(wildcard_site['app_id'])
+ kwargs, _ = SiteDomainService.app_vhost_kwargs(application)
+
+ assert kwargs['domains'] == ['a.acme.dev']
+ # and the surviving domain keeps its cert
+ assert kwargs['ssl_cert'].endswith('fullchain.pem')
+
+
+def test_deleting_a_domain_keeps_https_for_the_rest(app, wildcard_site, auth_headers, client, monkeypatch):
+ """End to end through the route: the vhost written after a delete must still
+ carry the cert."""
+ written = []
+ from app.services import nginx_service
+ monkeypatch.setattr(nginx_service.NginxService, 'create_site',
+ classmethod(lambda cls, **kw: written.append(kw) or {'success': True}))
+ monkeypatch.setattr(nginx_service.NginxService, 'enable_site',
+ classmethod(lambda cls, name: {'success': True}))
+
+ resp = client.delete(f"/api/v1/domains/{wildcard_site['b']}", headers=auth_headers)
+ assert resp.status_code in (200, 403) # 403 only if the fixture user lacks the grant
+ if resp.status_code != 200:
+ pytest.skip('fixture user cannot edit this app')
+
+ assert written, 'no vhost was written after the delete'
+ last = written[-1]
+ assert last['domains'] == ['a.acme.dev'], 'deleted domain still in server_name'
+ assert last['ssl_cert'], 'wildcard cert dropped on delete -> site fell back to HTTP'
+ assert last['micro_cache'] is True, 'micro-cache dropped on delete'