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.

feat(dns): give-this-a-subdomain + all-managed-records view (Phase 4 backend)

Juan Denis4fba9c1f1336
diff --git a/backend/app/api/dns_zones.py b/backend/app/api/dns_zones.py
index 305d7146..5475ebb4 100644
--- a/backend/app/api/dns_zones.py
+++ b/backend/app/api/dns_zones.py
@@ -157,6 +157,23 @@ def list_dns_changes():
return jsonify({'changes': [c.to_dict() for c in changes]})
+@dns_zones_bp.route('/managed', methods=['GET'])
+@jwt_required()
+def list_managed_records():
+ """Every DNS record ServerKit owns across all provider zones, in one place —
+ enriched with the app that triggered each (when applicable)."""
+ from app.services.dns_ownership_service import DnsOwnershipService
+ from app.models.application import Application
+ rows = DnsOwnershipService.list_all()
+ app_names = {a.id: a.name for a in Application.query.all()} if rows else {}
+ out = []
+ for r in rows:
+ d = r.to_dict()
+ d['app_name'] = app_names.get(r.app_id)
+ out.append(d)
+ return jsonify({'records': out, 'count': len(out)})
+
+
@dns_zones_bp.route('/<int:zone_id>/export', methods=['GET'])
@jwt_required()
def export_zone(zone_id):
diff --git a/backend/app/api/domains.py b/backend/app/api/domains.py
index 9bee3646..2f476aaa 100644
--- a/backend/app/api/domains.py
+++ b/backend/app/api/domains.py
@@ -216,6 +216,42 @@ def create_domain():
return jsonify(response), 201
+@domains_bp.route('/suggest-subdomain', methods=['GET'])
+@jwt_required()
+def suggest_subdomain():
+ """Suggest a managed-sites subdomain (<slug>.<base>) for an app, so the UI can
+ prefill the 'give this a subdomain' action."""
+ from app.services.site_domain_service import SiteDomainService
+ app_id = request.args.get('application_id', type=int)
+ app = Application.query.get(app_id) if app_id else None
+ base = SiteDomainService.base_domain()
+ if not base:
+ return jsonify({'base_domain': None, 'suggestion': None,
+ 'dns_mode': SiteDomainService.dns_mode()}), 200
+ slug = SiteDomainService.slugify(app.name) if app else 'site'
+ return jsonify({'base_domain': base, 'suggestion': f'{slug}.{base}',
+ 'dns_mode': SiteDomainService.dns_mode()}), 200
+
+
+@domains_bp.route('/give-subdomain', methods=['POST'])
+@jwt_required()
+def give_subdomain():
+ """Publish an app at <label>.<base_domain> in one click — Domain row + nginx
+ vhost + (per-site mode) an auto-created A record."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ data = request.get_json() or {}
+ app = Application.query.get(data.get('application_id')) if data.get('application_id') else None
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+ if not ResourceGrantService.can_edit_app(user, app):
+ return jsonify({'error': 'Access denied'}), 403
+
+ from app.services.site_domain_service import SiteDomainService
+ result = SiteDomainService.give_subdomain(app, label=data.get('label'))
+ return jsonify(result), 200 if result.get('success') else 400
+
+
@domains_bp.route('/<int:domain_id>', methods=['PUT'])
@jwt_required()
def update_domain(domain_id):
diff --git a/backend/app/services/site_domain_service.py b/backend/app/services/site_domain_service.py
index c5759543..2bf5a9e7 100644
--- a/backend/app/services/site_domain_service.py
+++ b/backend/app/services/site_domain_service.py
@@ -138,3 +138,63 @@ class SiteDomainService:
return DNSProviderService.ensure_a_record(host, ip)
except Exception as e:
return {'created': False, 'reason': 'error', 'error': str(e)}
+
+ @classmethod
+ def give_subdomain(cls, app, label=None):
+ """One-click 'give this app a subdomain': publish ``app`` at
+ ``<label>.<base_domain>`` (label defaults to the app-name slug). Creates the
+ primary Domain row, (re)writes its nginx vhost, and — in per-site DNS mode —
+ auto-creates the A record (wildcard mode relies on ``*.<base>``).
+
+ Returns ``{success, host, url, dns, nginx, warning}`` or
+ ``{success: False, error}``.
+ """
+ from app import db
+ from app.models.domain import Domain
+ from app.services.nginx_service import NginxService
+
+ base = cls.base_domain()
+ if not base:
+ 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()
+ 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(
+ 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})
+ db.session.add(Domain(name=host, is_primary=make_primary, application_id=app.id))
+ db.session.commit()
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': f'Could not record domain: {e}'}
+
+ warning = None
+ nginx = None
+ if app.app_type == 'docker' and app.port:
+ all_domains = [d.name for d in Domain.query.filter_by(application_id=app.id).all()]
+ ssl_cert, ssl_key = (None, None)
+ if cls.https_enabled() and all(cls.covers(d) for d in all_domains):
+ ssl_cert, ssl_key = cls.wildcard_cert_paths()
+ nginx = NginxService.create_site(
+ name=app.name, app_type='docker', domains=all_domains,
+ root_path=app.root_path or '', port=app.port,
+ ssl_cert=ssl_cert, ssl_key=ssl_key)
+ if nginx.get('success'):
+ NginxService.enable_site(app.name)
+ else:
+ warning = nginx.get('error')
+
+ dns = cls.ensure_site_dns(host)
+ if dns and not dns.get('skipped') and not dns.get('created') and dns.get('message'):
+ warning = (warning + '; ' + dns['message']) if warning else dns['message']
+
+ return {'success': True, 'host': host,
+ 'url': cls.site_url(host, ssl=cls.https_enabled() and cls.covers(host)),
+ 'dns': dns, 'nginx': nginx, 'warning': warning}
diff --git a/backend/tests/test_dns_give_subdomain.py b/backend/tests/test_dns_give_subdomain.py
new file mode 100644
index 00000000..6f89de8b
--- /dev/null
+++ b/backend/tests/test_dns_give_subdomain.py
@@ -0,0 +1,120 @@
+"""Proving tests for Phase 4 ergonomics: give-this-a-subdomain + all-managed view.
+
+A first-class "publish this app at <slug>.<base>" action (Domain row + nginx vhost +
+per-site DNS record when in per-site mode), plus one endpoint that lists every record
+ServerKit owns across all zones.
+"""
+
+
+def _set(key, value):
+ from app import db
+ from app.services.settings_service import SettingsService
+ SettingsService.set(key, value)
+ db.session.commit()
+
+
+def _mk_app(name='Acme Blog', port=8500):
+ from app import db
+ from app.models import User, Application
+ from werkzeug.security import generate_password_hash
+ u = User(email=f'{name}@p4.local', username=f'p4-{name}'.replace(' ', '-').lower(),
+ password_hash=generate_password_hash('x'), role=User.ROLE_ADMIN, is_active=True)
+ db.session.add(u)
+ db.session.commit()
+ a = Application(name=name, app_type='docker', user_id=u.id,
+ root_path=f'/srv/{name}', port=port)
+ db.session.add(a)
+ db.session.commit()
+ return a
+
+
+# ── give_subdomain (service) ─────────────────────────────────────────────────
+
+def test_give_subdomain_requires_base_domain(app, monkeypatch):
+ from app.services.site_domain_service import SiteDomainService
+ # TestingConfig pins SITES_BASE_DOMAIN=lvh.me; clear it to exercise the unset path.
+ monkeypatch.setitem(app.config, 'SITES_BASE_DOMAIN', '')
+ a = _mk_app()
+ res = SiteDomainService.give_subdomain(a)
+ assert res['success'] is False and 'base domain' in res['error'].lower()
+
+
+def test_give_subdomain_creates_domain_and_per_site_dns(app, monkeypatch):
+ from app.models.domain import Domain
+ from app.services.site_domain_service import SiteDomainService
+ from app.services.nginx_service import NginxService
+ from app.services.dns_provider_service import DNSProviderService
+
+ _set('sites_base_domain', 'apps.example.com')
+ _set('sites_dns_mode', 'per-site')
+ _set('server_public_ip', '203.0.113.9')
+ a = _mk_app(name='Acme Blog', port=8500)
+
+ monkeypatch.setattr(NginxService, 'create_site', staticmethod(lambda **k: {'success': True}))
+ monkeypatch.setattr(NginxService, 'enable_site', staticmethod(lambda name: {'success': True}))
+ seen = {}
+ monkeypatch.setattr(DNSProviderService, 'ensure_a_record', classmethod(
+ lambda cls, host, ip: (seen.update(host=host, ip=ip) or {'created': True, 'record': {}})))
+
+ res = SiteDomainService.give_subdomain(a)
+ assert res['success'] and res['host'] == 'acme-blog.apps.example.com'
+ dom = Domain.query.filter_by(name='acme-blog.apps.example.com').first()
+ assert dom and dom.is_primary and dom.application_id == a.id
+ assert seen == {'host': 'acme-blog.apps.example.com', 'ip': '203.0.113.9'}
+
+
+def test_give_subdomain_wildcard_mode_skips_per_site_record(app, monkeypatch):
+ from app.models.domain import Domain
+ from app.services.site_domain_service import SiteDomainService
+ from app.services.nginx_service import NginxService
+ from app.services.dns_provider_service import DNSProviderService
+
+ _set('sites_base_domain', 'apps.example.com') # default mode = wildcard
+ a = _mk_app(name='Wild One', port=8600)
+
+ monkeypatch.setattr(NginxService, 'create_site', staticmethod(lambda **k: {'success': True}))
+ monkeypatch.setattr(NginxService, 'enable_site', staticmethod(lambda name: {'success': True}))
+ called = {'n': 0}
+ monkeypatch.setattr(DNSProviderService, 'ensure_a_record',
+ classmethod(lambda cls, h, ip: called.update(n=called['n'] + 1)))
+
+ res = SiteDomainService.give_subdomain(a)
+ assert res['success'] and res['dns'].get('skipped')
+ assert called['n'] == 0
+ assert Domain.query.filter_by(name='wild-one.apps.example.com').first() is not None
+
+
+def test_give_subdomain_rejects_label_taken_by_other_app(app, monkeypatch):
+ from app import db
+ from app.models.domain import Domain
+ from app.services.site_domain_service import SiteDomainService
+
+ _set('sites_base_domain', 'apps.example.com')
+ other = _mk_app(name='Other', port=8700)
+ db.session.add(Domain(name='shared.apps.example.com', application_id=other.id))
+ db.session.commit()
+
+ a = _mk_app(name='Mine', port=8800)
+ res = SiteDomainService.give_subdomain(a, label='shared')
+ assert res['success'] is False and 'another app' in res['error']
+
+
+# ── endpoints ────────────────────────────────────────────────────────────────
+
+def test_suggest_subdomain_endpoint(app, client, auth_headers):
+ _set('sites_base_domain', 'apps.example.com')
+ a = _mk_app(name='My Service', port=8900)
+ resp = client.get(f'/api/v1/domains/suggest-subdomain?application_id={a.id}', headers=auth_headers)
+ assert resp.status_code == 200
+ assert resp.get_json()['suggestion'] == 'my-service.apps.example.com'
+
+
+def test_managed_records_endpoint(app, client, auth_headers):
+ from app.services.dns_ownership_service import DnsOwnershipService
+ DnsOwnershipService.record_write('cloudflare', 'Z1', 'A', 'www.example.com',
+ provider_record_id='R1', source='zone')
+ resp = client.get('/api/v1/dns/managed', headers=auth_headers)
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data['count'] >= 1
+ assert any(r['name'] == 'www.example.com' for r in data['records'])