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(ssl): remember one Let's Encrypt contact instead of asking every time

Juan Denisfc000a3b972e
diff --git a/backend/app/api/domains.py b/backend/app/api/domains.py
index 18318b61..a7d8fd2c 100644
--- a/backend/app/api/domains.py
+++ b/backend/app/api/domains.py
@@ -8,7 +8,7 @@ from app import db
from app.middleware.rbac import admin_required
from app.models import Domain, Application, User
from app.services.nginx_service import NginxService
-from app.services.ssl_service import SSLService
+from app.services.ssl_service import SSLService, get_acme_contact, remember_acme_contact
from app.services.resource_grant_service import ResourceGrantService
domains_bp = Blueprint('domains', __name__)
@@ -386,10 +386,14 @@ def enable_ssl(domain_id):
return jsonify({'error': 'Access denied'}), 403
data = request.get_json() or {}
- email = data.get('email')
+ # An address on the request wins; otherwise the panel-wide ACME contact,
+ # so the modal stops asking for the same address on every certificate.
+ email = get_acme_contact(data.get('email'))
if not email:
- return jsonify({'error': 'Email is required for SSL certificate'}), 400
+ return jsonify({'error': 'Email is required for SSL certificate. Set a '
+ 'default contact in Settings to stop being '
+ 'asked for it per certificate.'}), 400
# Request Let's Encrypt certificate
result = SSLService.obtain_certificate(
@@ -416,6 +420,10 @@ def enable_ssl(domain_id):
domain.ssl_private_key_path = result['private_key_path']
db.session.commit()
+ # Only after issuance actually worked — remembering an address that
+ # Let's Encrypt rejected would be worse than not remembering one.
+ remember_acme_contact(data.get('email'), user_id=current_user_id)
+
return jsonify({
'message': 'SSL enabled for domain',
'domain': domain.to_dict(),
diff --git a/backend/app/api/ssl.py b/backend/app/api/ssl.py
index af2e0cff..d196c6a2 100644
--- a/backend/app/api/ssl.py
+++ b/backend/app/api/ssl.py
@@ -1,11 +1,24 @@
from flask import Blueprint, request, jsonify
-from flask_jwt_extended import jwt_required
+from flask_jwt_extended import jwt_required, get_jwt_identity
from app.middleware.rbac import admin_required
-from app.services.ssl_service import SSLService
+from app.services.ssl_service import SSLService, get_acme_contact, remember_acme_contact
ssl_bp = Blueprint('ssl', __name__)
+@ssl_bp.route('/acme-contact', methods=['GET'])
+@jwt_required()
+def acme_contact():
+ """The panel-wide ACME contact, for prefilling certificate forms.
+
+ Deliberately not admin-gated: issuing a certificate for an app you can
+ edit is not an admin action, so the surfaces that need this prefill are
+ reachable by non-admins too. The value is the address the operator chose
+ to receive expiry notices at, not a credential.
+ """
+ return jsonify({'email': get_acme_contact() or ''}), 200
+
+
@ssl_bp.route('/certificates', methods=['GET'])
@jwt_required()
@admin_required
@@ -37,7 +50,9 @@ def obtain_certificate():
return jsonify({'error': 'No data provided'}), 400
domains = data.get('domains')
- email = data.get('email')
+ # Falls back to the stored panel-wide contact, so a caller that has one
+ # configured no longer has to repeat it on every request.
+ email = get_acme_contact(data.get('email'))
if not domains or not email:
return jsonify({'error': 'domains and email are required'}), 400
@@ -49,6 +64,9 @@ def obtain_certificate():
use_nginx=data.get('use_nginx', True)
)
+ if result.get('success'):
+ remember_acme_contact(data.get('email'), user_id=get_jwt_identity())
+
return jsonify(result), 201 if result['success'] else 400
diff --git a/backend/app/services/domain_attach_service.py b/backend/app/services/domain_attach_service.py
index c9cc6f47..2616612e 100644
--- a/backend/app/services/domain_attach_service.py
+++ b/backend/app/services/domain_attach_service.py
@@ -124,9 +124,13 @@ class DomainAttachService:
want_ssl = ssl in ('auto', 'on', True)
if want_ssl:
try:
- from app.services.ssl_service import SSLService
+ from app.services.ssl_service import SSLService, get_acme_contact
from app.services.nginx_service import NginxService
- cert = SSLService.obtain_certificate([host], email or f'admin@{host}')
+ # The stored panel contact before the admin@<host> guess —
+ # that guess is where Let's Encrypt expiry notices went to
+ # die, since the address usually does not exist.
+ cert = SSLService.obtain_certificate(
+ [host], get_acme_contact(email) or f'admin@{host}')
if cert and cert.get('success'):
domain.ssl_enabled = True
domain.ssl_certificate_path = cert.get('certificate_path')
diff --git a/backend/app/services/settings_service.py b/backend/app/services/settings_service.py
index 8422f396..aa7377a8 100644
--- a/backend/app/services/settings_service.py
+++ b/backend/app/services/settings_service.py
@@ -87,6 +87,16 @@ class SettingsService:
'type': 'boolean',
'description': 'Whether the wildcard certificate for the sites base domain is set up; managed subdomains serve HTTPS when true.'
},
+ # Panel-wide ACME contact. Every certificate ServerKit requests
+ # registers this address with Let's Encrypt, which is where expiry and
+ # revocation notices go — so it is worth storing once rather than
+ # retyping per certificate (or guessing admin@<domain>, which usually
+ # does not exist).
+ 'ssl.acme_email': {
+ 'value': '',
+ 'type': 'string',
+ 'description': "Contact email registered with Let's Encrypt for certificate expiry notices. Used when a certificate request does not carry its own address."
+ },
# Canonical panel domain. When set, the panel uses this domain for
# agent install commands, CORS origins, and optional IP redirects.
'canonical_domain': {
diff --git a/backend/app/services/ssl_service.py b/backend/app/services/ssl_service.py
index 18d216d0..30ce4a76 100644
--- a/backend/app/services/ssl_service.py
+++ b/backend/app/services/ssl_service.py
@@ -57,6 +57,50 @@ def resolve_certbot_bin() -> Optional[str]:
return found
+# Panel-wide ACME contact, stored in system settings.
+ACME_EMAIL_SETTING = 'ssl.acme_email'
+
+
+def get_acme_contact(provided: Optional[str] = None) -> Optional[str]:
+ """The contact address to register with Let's Encrypt.
+
+ An address supplied with the request wins; otherwise the panel-wide
+ contact stored in settings. Returns ``None`` when neither exists, leaving
+ it to the caller to decide whether that is fatal — the domain SSL modal
+ treats it as a hard requirement, while the automatic issuance paths would
+ rather fall back than refuse.
+ """
+ provided = (provided or '').strip()
+ if provided:
+ return provided
+ try:
+ from app.services.settings_service import SettingsService
+ stored = (SettingsService.get(ACME_EMAIL_SETTING) or '').strip()
+ except Exception: # noqa: BLE001 — never let settings break issuance
+ return None
+ return stored or None
+
+
+def remember_acme_contact(email: Optional[str], user_id=None) -> None:
+ """Store *email* as the panel-wide ACME contact.
+
+ Called whenever a certificate request carries an explicit address, so the
+ next request anywhere in the panel can prefill instead of asking again.
+ Best-effort by design: failing to remember an address must never turn a
+ successful certificate issuance into an error.
+ """
+ email = (email or '').strip()
+ if not email:
+ return
+ try:
+ from app.services.settings_service import SettingsService
+ if (SettingsService.get(ACME_EMAIL_SETTING) or '').strip() == email:
+ return
+ SettingsService.set(ACME_EMAIL_SETTING, email, user_id=user_id)
+ except Exception: # noqa: BLE001
+ pass
+
+
class SSLService:
"""Service for SSL certificate management with Let's Encrypt."""
diff --git a/backend/tests/test_ssl_acme_contact.py b/backend/tests/test_ssl_acme_contact.py
new file mode 100644
index 00000000..964a1b0f
--- /dev/null
+++ b/backend/tests/test_ssl_acme_contact.py
@@ -0,0 +1,197 @@
+"""Plan 73 item 5 — the SSL modal re-asked for the same email every time.
+
+The app-detail Settings tab remembered the address in localStorage; the
+Domains modal did not, and the backend hard-required one per call. So the
+address was retyped per certificate, per browser — and the automatic issuance
+paths, which have no form to type into, guessed ``admin@<host>``, an address
+that usually does not exist and therefore silently discarded every Let's
+Encrypt expiry notice.
+
+There is now one panel-wide ACME contact in settings that every issuance path
+falls back to, and that an explicit address updates.
+"""
+from unittest.mock import patch
+
+import pytest
+
+from app.services.ssl_service import (
+ ACME_EMAIL_SETTING,
+ get_acme_contact,
+ remember_acme_contact,
+)
+from app.services.settings_service import SettingsService
+
+
+STORED = '[email protected]'
+EXPLICIT = '[email protected]'
+
+
+def stored_contact(app):
+ SettingsService.set(ACME_EMAIL_SETTING, STORED)
+ return STORED
+
+
+# --------------------------------------------------------------------------- #
+# Resolution
+# --------------------------------------------------------------------------- #
+class TestGetAcmeContact:
+
+ def test_explicit_address_wins(self, app, stored_contact):
+ assert get_acme_contact(EXPLICIT) == EXPLICIT
+
+ def test_falls_back_to_the_stored_contact(self, app, stored_contact):
+ assert get_acme_contact(None) == STORED
+ assert get_acme_contact('') == STORED
+ assert get_acme_contact(' ') == STORED
+
+ def test_none_when_nothing_is_stored(self, app):
+ assert get_acme_contact(None) is None
+
+ def test_whitespace_is_trimmed(self, app):
+ assert get_acme_contact(' [email protected] ') == '[email protected]'
+
+ def test_settings_failure_does_not_break_issuance(self, app):
+ """A settings lookup blowing up must not take certificate issuance
+ down with it."""
+ with patch.object(SettingsService, 'get', side_effect=Exception('db gone')):
+ assert get_acme_contact(None) is None
+ assert get_acme_contact(EXPLICIT) == EXPLICIT
+
+
+class TestRememberAcmeContact:
+
+ def test_stores_the_address(self, app):
+ remember_acme_contact(EXPLICIT)
+ assert SettingsService.get(ACME_EMAIL_SETTING) == EXPLICIT
+
+ def test_later_address_replaces_the_earlier_one(self, app, stored_contact):
+ remember_acme_contact(EXPLICIT)
+ assert SettingsService.get(ACME_EMAIL_SETTING) == EXPLICIT
+
+ def test_empty_input_never_clears_a_stored_contact(self, app, stored_contact):
+ """The automatic paths pass whatever they were given, often nothing —
+ that must not wipe a contact the operator configured."""
+ remember_acme_contact(None)
+ remember_acme_contact('')
+ remember_acme_contact(' ')
+ assert SettingsService.get(ACME_EMAIL_SETTING) == STORED
+
+ def test_unchanged_address_is_not_rewritten(self, app, stored_contact):
+ with patch.object(SettingsService, 'set') as setter:
+ remember_acme_contact(STORED)
+ setter.assert_not_called()
+
+ def test_storage_failure_is_swallowed(self, app):
+ """Failing to remember an address must never turn a successful
+ certificate issuance into an error."""
+ with patch.object(SettingsService, 'set', side_effect=Exception('nope')):
+ remember_acme_contact(EXPLICIT) # must not raise
+
+
+# --------------------------------------------------------------------------- #
+# API surfaces
+# --------------------------------------------------------------------------- #
+def admin_headers(app):
+ from flask_jwt_extended import create_access_token
+ from werkzeug.security import generate_password_hash
+ from app import db
+ from app.models import User
+
+ user = User(email='[email protected]', username='acmeadmin',
+ password_hash=generate_password_hash('x'),
+ role=User.ROLE_ADMIN, is_active=True)
+ db.session.add(user)
+ db.session.commit()
+ return {'Authorization': f'Bearer {create_access_token(identity=user.id)}'}, user
+
+
+def ssl_domain(app, admin_headers):
+ from app import db
+ from app.models.application import Application
+ from app.models.domain import Domain
+
+ _, user = admin_headers
+ site = Application(name='acmesite', app_type='static', user_id=user.id)
+ db.session.add(site)
+ db.session.flush()
+ row = Domain(name='acme.example.com', application_id=site.id)
+ db.session.add(row)
+ db.session.commit()
+ return row
+
+
+class TestAcmeContactEndpoint:
+
+ def test_returns_the_stored_contact(self, client, admin_headers, stored_contact):
+ headers, _ = admin_headers
+ resp = client.get('/api/v1/ssl/acme-contact', headers=headers)
+
+ assert resp.status_code == 200
+ assert resp.get_json() == {'email': STORED}
+
+ def test_returns_empty_string_when_unset(self, client, admin_headers):
+ headers, _ = admin_headers
+ resp = client.get('/api/v1/ssl/acme-contact', headers=headers)
+
+ assert resp.status_code == 200
+ assert resp.get_json() == {'email': ''}
+
+ def test_requires_authentication(self, client):
+ assert client.get('/api/v1/ssl/acme-contact').status_code == 401
+
+
+class TestEnableSslUsesTheStoredContact:
+
+ def _enable(self, client, headers, domain, body):
+ cert = {'success': True, 'certificate_path': '/c.pem',
+ 'private_key_path': '/k.pem'}
+ with patch('app.api.domains.SSLService.obtain_certificate',
+ return_value=cert) as obtain, \
+ patch('app.api.domains.NginxService.add_ssl_to_site',
+ return_value={'success': True}):
+ resp = client.post(f'/api/v1/domains/{domain.id}/ssl/enable',
+ json=body, headers=headers)
+ return resp, obtain
+
+ def test_request_without_an_email_uses_the_stored_contact(
+ self, client, admin_headers, ssl_domain, stored_contact):
+ """The whole point of the item: the modal stops asking."""
+ headers, _ = admin_headers
+ resp, obtain = self._enable(client, headers, ssl_domain, {})
+
+ assert resp.status_code == 200
+ assert obtain.call_args.kwargs['email'] == STORED
+
+ def test_explicit_email_wins_and_is_remembered(
+ self, client, admin_headers, ssl_domain, stored_contact):
+ headers, _ = admin_headers
+ resp, obtain = self._enable(client, headers, ssl_domain,
+ {'email': EXPLICIT})
+
+ assert resp.status_code == 200
+ assert obtain.call_args.kwargs['email'] == EXPLICIT
+ assert SettingsService.get(ACME_EMAIL_SETTING) == EXPLICIT
+
+ def test_no_email_anywhere_still_refuses(self, client, admin_headers, ssl_domain):
+ headers, _ = admin_headers
+ resp, obtain = self._enable(client, headers, ssl_domain, {})
+
+ assert resp.status_code == 400
+ assert 'Email is required' in resp.get_json()['error']
+ obtain.assert_not_called()
+
+ def test_a_failed_issuance_does_not_remember_the_address(
+ self, client, admin_headers, ssl_domain):
+ """Remembering an address Let's Encrypt rejected would be worse than
+ remembering none."""
+ headers, _ = admin_headers
+ with patch('app.api.domains.SSLService.obtain_certificate',
+ return_value={'success': False, 'error': 'rejected'}):
+ resp = client.post(f'/api/v1/domains/{ssl_domain.id}/ssl/enable',
+ json={'email': EXPLICIT}, headers=headers)
+
+ assert resp.status_code == 400
+ assert not (SettingsService.get(ACME_EMAIL_SETTING) or '')
diff --git a/frontend/src/components/service-detail/SettingsTab.jsx b/frontend/src/components/service-detail/SettingsTab.jsx
index 3b3e4ede..0e158fac 100644
--- a/frontend/src/components/service-detail/SettingsTab.jsx
+++ b/frontend/src/components/service-detail/SettingsTab.jsx
@@ -452,8 +452,22 @@ const DomainSslPanel = ({ app, domains, primaryDomain, onUpdate }) => {
const [attaching, setAttaching] = useState(false);
const [serverkitDomains, setServerkitDomains] = useState([]);
const [contextLoading, setContextLoading] = useState(true);
+ // localStorage seeds the field instantly (no flash on a page the user has
+ // used before); the panel-wide contact fills it in when this browser has
+ // no copy — which is the case the Domains modal shares.
const [email, setEmail] = useState(() => localStorage.getItem('serverkit_ssl_email') || '');
+ useEffect(() => {
+ if (email) return undefined;
+ let cancelled = false;
+ api.getAcmeContact()
+ .then(({ email: stored }) => { if (!cancelled && stored) setEmail(stored); })
+ .catch(() => {});
+ return () => { cancelled = true; };
+ // Runs once: this only ever seeds an empty field, never overwrites typing.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
// "Give it a subdomain" — publish the app at a managed <label>.<base> host.
const [subdomainModal, setSubdomainModal] = useState(null); // { base_domain, dns_mode }
const [subdomainLabel, setSubdomainLabel] = useState('');
diff --git a/frontend/src/pages/Domains.jsx b/frontend/src/pages/Domains.jsx
index 67f1450d..cc3b4873 100644
--- a/frontend/src/pages/Domains.jsx
+++ b/frontend/src/pages/Domains.jsx
@@ -149,10 +149,22 @@ const Domains = () => {
const [selectedAppId, setSelectedAppId] = useState('');
const [isPrimary, setIsPrimary] = useState(false);
const [sslEmail, setSslEmail] = useState('');
+ const [acmeContact, setAcmeContact] = useState('');
const [actionLoading, setActionLoading] = useState(false);
useEffect(() => { loadData(); }, []);
+ // The panel remembers one Let's Encrypt contact; this modal used to ask
+ // for it on every single certificate. Best-effort — an unreachable
+ // setting just leaves the field empty, as before.
+ useEffect(() => {
+ let cancelled = false;
+ api.getAcmeContact()
+ .then(({ email }) => { if (!cancelled && email) setAcmeContact(email); })
+ .catch(() => {});
+ return () => { cancelled = true; };
+ }, []);
+
// Lazily resolve registration (expiry/registrar) for the open provider domain:
// use the provider value if present, else fall back to a one-off RDAP lookup.
useEffect(() => {
@@ -237,10 +249,13 @@ const Domains = () => {
async function handleEnableSsl(e) {
e.preventDefault();
- if (!selectedDomain || !sslEmail) return;
+ // Mirrors the input's display fallback: an untouched field submits the
+ // stored contact rather than nothing.
+ const email = sslEmail || acmeContact;
+ if (!selectedDomain || !email) return;
try {
setActionLoading(true);
- await api.enableSsl(selectedDomain.id, sslEmail);
+ await api.enableSsl(selectedDomain.id, email);
setShowSslModal(false);
setSslEmail('');
setSelectedDomain(null);
@@ -883,8 +898,18 @@ const Domains = () => {
</div>
<div className="form-group">
<Label>Email Address</Label>
- <Input type="email" placeholder="[email protected]" value={sslEmail} onChange={e => setSslEmail(e.target.value)} required />
- <p className="hint">Required for certificate expiration notifications</p>
+ <Input
+ type="email"
+ placeholder={acmeContact || '[email protected]'}
+ value={sslEmail || acmeContact}
+ onChange={e => setSslEmail(e.target.value)}
+ required
+ />
+ <p className="hint">
+ {acmeContact
+ ? "Certificate expiry notices go here. Saved from the last certificate you issued — change it to use a different address."
+ : 'Required for certificate expiration notifications. It will be remembered for the next certificate.'}
+ </p>
</div>
<div className="modal-actions">
<Button type="button" variant="outline" onClick={() => setShowSslModal(false)}>Cancel</Button>
diff --git a/frontend/src/services/api/security.js b/frontend/src/services/api/security.js
index 287c8116..e0d8f0b0 100644
--- a/frontend/src/services/api/security.js
+++ b/frontend/src/services/api/security.js
@@ -105,6 +105,12 @@ export async function obtainCertificate(data) {
});
}
+// Panel-wide Let's Encrypt contact, used to prefill certificate forms so the
+// same address isn't retyped per certificate.
+export async function getAcmeContact() {
+ return this.request('/ssl/acme-contact');
+}
+
export async function renewCertificate(domain) {
return this.request(`/ssl/certificates/${domain}/renew`, { method: 'POST' });
}