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(mail): pin Stalwart engine against live 0.16.11 (WSL+Docker)

Juan Denis427492cb4b14
diff --git a/backend/tests/test_serverkit_mail_extension.py b/backend/tests/test_serverkit_mail_extension.py
index 6399f25b..e668fd9b 100644
--- a/backend/tests/test_serverkit_mail_extension.py
+++ b/backend/tests/test_serverkit_mail_extension.py
@@ -293,8 +293,8 @@ def test_install_builds_correct_docker_run(monkeypatch, linux):
result = StalwartService.install('Mail.Example.COM.')
assert result['success'] is True, result
- # Data dir created, container started.
- assert ['mkdir', '-p', svc_mod.DATA_DIR] in calls
+ # Config + data dirs created, container started.
+ assert ['mkdir', '-p', svc_mod.HOST_CONFIG_DIR, svc_mod.HOST_DATA_DIR] in calls
run_cmd = next(c for c in calls if c[:2] == ['docker', 'run'])
# Mail ports published on the host.
@@ -306,18 +306,25 @@ def test_install_builds_correct_docker_run(monkeypatch, linux):
assert '127.0.0.1:8080:8080' in run_cmd
assert not any(a == '8080:8080' for a in run_cmd)
- # Official image, restart policy, data volume.
+ # Live-verified image (stalwartlabs/stalwart, NOT the defunct mail-server),
+ # restart policy, and the split config/data bind mounts.
assert svc_mod.IMAGE in run_cmd
+ assert svc_mod.IMAGE.startswith('stalwartlabs/stalwart')
assert '--restart' in run_cmd
- assert f'{svc_mod.DATA_DIR}:{svc_mod.CONTAINER_DATA_DIR}' in run_cmd
-
- # A generated admin password was seeded into the container AND persisted.
- secret_args = [a for a in run_cmd if a.startswith('FALLBACK_ADMIN_SECRET=')]
- assert len(secret_args) == 1
- generated = secret_args[0].split('=', 1)[1]
+ assert f'{svc_mod.HOST_CONFIG_DIR}:{svc_mod.CONTAINER_CONFIG_DIR}' in run_cmd
+ assert f'{svc_mod.HOST_DATA_DIR}:{svc_mod.CONTAINER_DATA_DIR}' in run_cmd
+
+ # A generated admin password was pinned via the single recovery-admin env
+ # var (user:secret) AND persisted to the config store.
+ recovery_args = [a for a in run_cmd if a.startswith('STALWART_RECOVERY_ADMIN=')]
+ assert len(recovery_args) == 1
+ user, _, generated = recovery_args[0].split('=', 1)[1].partition(':')
+ assert user == svc_mod.ADMIN_USER
assert generated # non-empty generated secret
assert saved['admin_password'] == generated
assert saved['hostname'] == 'mail.example.com' # normalized (lowercased, no dot)
+ # install() tells the caller setup is still required.
+ assert result['needs_setup'] is True and result['setup_url']
def test_install_requires_hostname(monkeypatch, linux):
@@ -388,11 +395,45 @@ def test_status_running_reads_version(monkeypatch, linux):
status = StalwartService.get_status()
assert status['installed'] is True
assert status['running'] is True
+ # A 200 from the session probe means setup is complete (ready).
+ assert status['needs_setup'] is False
assert status['version'] == '0.11.1'
assert status['engine'] == 'stalwart'
assert status['admin_api'] == f'{svc_mod.API_HOST}:{svc_mod.API_PORT}'
+def test_status_bootstrap_reports_needs_setup(monkeypatch, linux):
+ """A fresh Stalwart container is running but in bootstrap mode: every /api/*
+ is a 404 (RFC-7807 problem+json) until the one-time setup completes. This is
+ the exact contract verified against live Stalwart 0.16.11 — the panel must
+ report needs_setup + a setup_url instead of a false 'ready' state."""
+ monkeypatch.setattr(
+ svc_mod, 'run_privileged',
+ lambda cmd, timeout=None, **kw: _proc(returncode=0, stdout='true\n'))
+ monkeypatch.setattr(
+ svc_mod.requests, 'request',
+ lambda method, url, **kw: FakeResponse(
+ 404, {'type': 'about:blank', 'status': 404, 'title': 'Not Found',
+ 'detail': 'The requested resource does not exist on this server.'}))
+ status = StalwartService.get_status()
+ assert status['installed'] is True
+ assert status['running'] is True
+ assert status['needs_setup'] is True
+ assert status['setup_url'] and svc_mod.ADMIN_UI in status['setup_url']
+
+
+def test_api_parses_problem_json_detail(monkeypatch, linux):
+ """_api extracts the RFC-7807 `detail` (then `title`) from Stalwart errors."""
+ monkeypatch.setattr(
+ svc_mod.requests, 'request',
+ lambda method, url, **kw: FakeResponse(
+ 404, {'status': 404, 'title': 'Not Found', 'detail': 'nope'}))
+ res = StalwartService._api('GET', '/principal')
+ assert res['success'] is False
+ assert res['status_code'] == 404
+ assert 'nope' in res['error']
+
+
def test_status_not_installed(monkeypatch, linux):
monkeypatch.setattr(
svc_mod, 'run_privileged',
diff --git a/builtin-extensions/serverkit-mail/backend/stalwart_service.py b/builtin-extensions/serverkit-mail/backend/stalwart_service.py
index b16b0e3c..fcdfa873 100644
--- a/builtin-extensions/serverkit-mail/backend/stalwart_service.py
+++ b/builtin-extensions/serverkit-mail/backend/stalwart_service.py
@@ -39,12 +39,19 @@ logger = logging.getLogger(__name__)
SLUG = 'serverkit-mail'
-# Official Stalwart all-in-one mail server image.
-IMAGE = 'stalwartlabs/mail-server:latest'
+# Official Stalwart all-in-one mail server image. NOTE: the image is
+# ``stalwartlabs/stalwart`` — the older ``stalwartlabs/mail-server`` name no
+# longer resolves on Docker Hub (verified against a live pull, v0.16.11).
+IMAGE = 'stalwartlabs/stalwart:latest'
CONTAINER_NAME = 'serverkit-mail'
DATA_DIR = '/var/serverkit/mail'
-# Bind-mount target inside the container (Stalwart's data/config root).
-CONTAINER_DATA_DIR = '/opt/stalwart-mail'
+# Stalwart splits config from data inside the container (its CMD is
+# ``--config /etc/stalwart/config.json``). We bind two host sub-dirs so both
+# survive a container recreate: the local bootstrap config and the data store.
+CONTAINER_CONFIG_DIR = '/etc/stalwart' # holds config.json (written at setup)
+CONTAINER_DATA_DIR = '/opt/stalwart' # holds the data/blob/fts store
+HOST_CONFIG_DIR = f'{DATA_DIR}/etc'
+HOST_DATA_DIR = f'{DATA_DIR}/data'
# Admin HTTP API — published on 127.0.0.1 only, never reachable off-host.
API_HOST = '127.0.0.1'
@@ -53,9 +60,17 @@ API_BASE = f'http://{API_HOST}:{API_PORT}/api'
API_TIMEOUT = 10
DOCKER_TIMEOUT = 180
-# Default admin account Stalwart provisions on first start.
+# Default admin account Stalwart provisions on first start. The recovery/admin
+# credential is pinned via a single ``STALWART_RECOVERY_ADMIN=user:secret`` env
+# var (verified from the container's first-boot log, v0.16.11).
ADMIN_USER = 'admin'
+# The web setup + admin SPA the recovery listener serves on the API port. On a
+# fresh container Stalwart boots into *bootstrap mode*: only this UI + a recovery
+# listener are up, and the whole ``/api/*`` management surface 404s until the
+# one-time initial setup is completed here.
+ADMIN_UI = '/account'
+
# Mail ports published on the host (SMTP / submission / IMAP / Sieve).
MAIL_PORTS = ('25', '465', '587', '993', '143', '4190')
@@ -63,11 +78,13 @@ DOCS_URL = 'https://stalw.art/docs/'
# ── Admin-API endpoint paths (version-sensitive; centralized on purpose) ──
# Each reconcile method wraps these so a 404 / shape change degrades gracefully.
+# These management paths only exist once initial setup is complete (see
+# ``get_status`` bootstrap detection); before that every ``/api/*`` is a 404.
EP_PRINCIPAL = '/principal' # accounts / mailboxes / domains (CRUD)
EP_DKIM = '/dkim' # DKIM signature management
EP_QUEUE = '/queue/messages' # outbound queue introspection
EP_RECONFIG = '/reload' # ask Stalwart to reload config
-EP_STATUS = '/status' # health / version probe (read-only)
+EP_SESSION = '/session' # logged-in principal probe (readiness/bootstrap)
class StalwartService:
@@ -158,9 +175,11 @@ class StalwartService:
return {'success': False,
'error': f'Stalwart admin API is unreachable: {e}'}
if resp.status_code >= 400:
+ # Stalwart returns RFC-7807 problem+json: {type,status,title,detail}.
try:
body = resp.json()
- detail = body.get('error') or body.get('details') or resp.text
+ detail = (body.get('detail') or body.get('title')
+ or body.get('error') or resp.text)
except ValueError:
detail = resp.text
return {'success': False, 'status_code': resp.status_code,
@@ -189,6 +208,8 @@ class StalwartService:
status = {
'installed': False,
'running': False,
+ 'needs_setup': None, # True until Stalwart's one-time setup is done
+ 'setup_url': None,
'version': None,
'engine': 'stalwart',
'image': IMAGE,
@@ -207,11 +228,21 @@ class StalwartService:
status['installed'] = True
status['running'] = res.get('stdout', '').strip() == 'true'
if status['running']:
- info = cls._api('GET', EP_STATUS)
- # Version is best-effort; a shape/endpoint change must not break
- # status (never GET the reload endpoint just to read a version).
- if info.get('success') and isinstance(info.get('data'), dict):
- status['version'] = info['data'].get('version')
+ # A fresh container boots into bootstrap mode: only the recovery
+ # setup UI is up and every /api/* is a 404 until initial setup is
+ # completed. Detect that so the panel can guide the operator instead
+ # of firing management calls that will all fail.
+ probe = cls._api('GET', EP_SESSION)
+ if probe.get('status_code') == 404:
+ status['needs_setup'] = True
+ status['setup_url'] = f'http://{API_HOST}:{API_PORT}{ADMIN_UI}'
+ elif probe.get('success'):
+ status['needs_setup'] = False
+ data = probe.get('data')
+ if isinstance(data, dict):
+ status['version'] = data.get('version') or status['version']
+ # Any other error (unreachable, still starting): leave needs_setup
+ # None so the UI shows "checking…" rather than a false ready state.
return status
@classmethod
@@ -234,7 +265,7 @@ class StalwartService:
return {'success': False,
'error': 'The mail server container already exists. Uninstall it first.'}
- dir_res = run_privileged(['mkdir', '-p', DATA_DIR])
+ dir_res = run_privileged(['mkdir', '-p', HOST_CONFIG_DIR, HOST_DATA_DIR])
if getattr(dir_res, 'returncode', 1) != 0:
return {'success': False,
'error': f'Could not create data directory {DATA_DIR}: '
@@ -251,11 +282,16 @@ class StalwartService:
run_args += ['-p', f'{port}:{port}']
# Admin API bound to loopback on the host — never reachable off-box.
run_args += ['-p', f'{API_HOST}:{API_PORT}:{API_PORT}']
- run_args += ['-v', f'{DATA_DIR}:{CONTAINER_DATA_DIR}']
- # Seed the fallback admin credentials Stalwart reads on first boot.
+ # Config and data on separate host dirs (see the module constants).
+ run_args += [
+ '-v', f'{HOST_CONFIG_DIR}:{CONTAINER_CONFIG_DIR}',
+ '-v', f'{HOST_DATA_DIR}:{CONTAINER_DATA_DIR}',
+ ]
+ # Pin the recovery/admin credential Stalwart reads on first boot — a
+ # single ``user:secret`` env var. Without this Stalwart prints a random
+ # one-time password to the container log that we could never recover.
run_args += [
- '-e', f'FALLBACK_ADMIN_USER={ADMIN_USER}',
- '-e', f'FALLBACK_ADMIN_SECRET={admin_password}',
+ '-e', f'STALWART_RECOVERY_ADMIN={ADMIN_USER}:{admin_password}',
IMAGE,
]
res = cls._docker(run_args)
@@ -268,9 +304,12 @@ class StalwartService:
'hostname': hostname,
})
result = {'success': True,
- 'message': 'Stalwart mail server installed',
+ 'message': 'Stalwart mail server installed — complete the one-time '
+ 'setup to activate the admin API',
'container': CONTAINER_NAME,
- 'hostname': hostname}
+ 'hostname': hostname,
+ 'needs_setup': True,
+ 'setup_url': f'http://{API_HOST}:{API_PORT}{ADMIN_UI}'}
if not persisted:
result['warning'] = ('Container started but the admin password could not '
'be persisted to the plugin config store.')
diff --git a/builtin-extensions/serverkit-mail/frontend/components/MailPage.jsx b/builtin-extensions/serverkit-mail/frontend/components/MailPage.jsx
index 2c18f373..490fdf4b 100644
--- a/builtin-extensions/serverkit-mail/frontend/components/MailPage.jsx
+++ b/builtin-extensions/serverkit-mail/frontend/components/MailPage.jsx
@@ -711,6 +711,27 @@ const MailPage = () => {
return (
<>
{renderPreflightBanner()}
+ {status?.needs_setup === true && (
+ <div className="card mail-preflight mail-preflight--warn">
+ <div className="mail-preflight__head">
+ <span className="mail-preflight__title">
+ <ShieldAlert size={16} /> Finish the one-time Stalwart setup
+ </span>
+ </div>
+ <p className="text-muted">
+ The container is running in bootstrap mode — its admin API stays
+ offline until you complete the initial setup wizard, which creates
+ the permanent administrator. For safety the setup UI is bound to the
+ server&apos;s loopback only ({status.setup_url || 'http://127.0.0.1:8080/account'});
+ reach it over an SSH tunnel, then re-check.
+ </p>
+ <div className="mail-install-actions">
+ <Button variant="outline" size="sm" onClick={loadStatus}>
+ <RefreshCw size={14} /> Re-check
+ </Button>
+ </div>
+ </div>
+ )}
<div className="card">
<div className="card-header">
<h3>Server Status</h3>
diff --git a/frontend/src/plugins/serverkit-mail/components/MailPage.jsx b/frontend/src/plugins/serverkit-mail/components/MailPage.jsx
index 2c18f373..490fdf4b 100644
--- a/frontend/src/plugins/serverkit-mail/components/MailPage.jsx
+++ b/frontend/src/plugins/serverkit-mail/components/MailPage.jsx
@@ -711,6 +711,27 @@ const MailPage = () => {
return (
<>
{renderPreflightBanner()}
+ {status?.needs_setup === true && (
+ <div className="card mail-preflight mail-preflight--warn">
+ <div className="mail-preflight__head">
+ <span className="mail-preflight__title">
+ <ShieldAlert size={16} /> Finish the one-time Stalwart setup
+ </span>
+ </div>
+ <p className="text-muted">
+ The container is running in bootstrap mode — its admin API stays
+ offline until you complete the initial setup wizard, which creates
+ the permanent administrator. For safety the setup UI is bound to the
+ server&apos;s loopback only ({status.setup_url || 'http://127.0.0.1:8080/account'});
+ reach it over an SSH tunnel, then re-check.
+ </p>
+ <div className="mail-install-actions">
+ <Button variant="outline" size="sm" onClick={loadStatus}>
+ <RefreshCw size={14} /> Re-check
+ </Button>
+ </div>
+ </div>
+ )}
<div className="card">
<div className="card-header">
<h3>Server Status</h3>