diff --git a/src/QueueMailSettings.tsx b/src/QueueMailSettings.tsx
index 7f65dd2..3750929 100644
--- a/src/QueueMailSettings.tsx
+++ b/src/QueueMailSettings.tsx
@@ -172,7 +172,7 @@ export function QueueMailSettings({ q }: D) {
onChange={(e) => updateSmtp('host', e.target.value)}
/>
-
+
-
+
+
+
+
diff --git a/tests/docker-smoke.mjs b/tests/docker-smoke.mjs
index 6b4885b..21234c0 100644
--- a/tests/docker-smoke.mjs
+++ b/tests/docker-smoke.mjs
@@ -90,7 +90,12 @@ try {
],
})
const config = await api('/queues/support/mail')
- await api('/queues/support/mail', 'PUT', { ...config, password: 'test-fixture-secret' })
+ await api('/queues/support/mail', 'PUT', {
+ ...config,
+ smtp: { ...config.smtp, security: 'none', port: 25, validateCertificate: false },
+ imap: { ...config.imap, security: 'tls', port: 25, validateCertificate: false },
+ password: 'test-fixture-secret',
+ })
await api(`/tickets/${ticket.id}/messages`, 'POST', {
kind: 'outgoing',
from: 'support@syncova.local',
@@ -141,6 +146,12 @@ try {
assert.equal(await bytes.text(), 'PERSISTENT-BYTES')
const restoredConfig = await api('/queues/support/mail')
assert.equal(restoredConfig.passwordSet, true)
+ assert.equal(restoredConfig.smtp.security, 'none')
+ assert.equal(restoredConfig.smtp.port, 25)
+ assert.equal(restoredConfig.smtp.validateCertificate, false)
+ assert.equal(restoredConfig.imap.security, 'tls')
+ assert.equal(restoredConfig.imap.port, 25)
+ assert.equal(restoredConfig.imap.validateCertificate, false)
assert(!(await api('/bootstrap')).queues.some((q) => q.id === 'service'))
assert((await api('/logs')).some((a) => a.action === 'Queue gelöscht'))
compose([
diff --git a/tests/fixtures/mail-test-cert.pem b/tests/fixtures/mail-test-cert.pem
new file mode 100644
index 0000000..6377da7
--- /dev/null
+++ b/tests/fixtures/mail-test-cert.pem
@@ -0,0 +1,19 @@
+-----BEGIN CERTIFICATE-----
+MIIDJTCCAg2gAwIBAgIUHhrw55gNyw3jjUDn2alyGBELSaAwDQYJKoZIhvcNAQEL
+B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/tests/fixtures/mail-test-key.pem
new file mode 100644
index 0000000..2251d1a
--- /dev/null
+++ b/tests/fixtures/mail-test-key.pem
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCyNh4DvyxpazNZ
+9lHnrwJVYuGhB5lGGzHJAexJFItQkFghsv0qb6w/suj0cVD4nKggO52p1Z4q3kFB
+3tNRzZkHmnrJRupo5OqTUYMq+jJmFJq7AqV24S4FFgVh1tw3i6lRfNyc44ir7PwX
+k8ZshFQC4ipRC3Sv728s/WlhxOJ5VE2E+dBgwQX/2vlaZuF8DKPZ50yBzfa8J++s
+y9D4SyHbcLswprNgmdtB91q0SCCtFsVOu79Aqr1VbZDoUuKqhA7DmBFau76ydtdX
+kSiU9A/Gu6EEcUE5XfnNO1Vkjr3MZprle3UqKKUPDBStOR+eq4FE+3Kw+QM1nMET
++xK3n+szAgMBAAECggEACLNCqN0q7mSY57HyUrTFEOUYbdOgpH8MYatR3Ul++apq
+Ww7RdEJqbtutqs1jbhe7z4MJkfKHW8Fo/y3BNFOsvmXIy83GAOP4HcQTesQnNLuZ
+yDp7WH/qzr3B+oJSUvXjCMLnRFOJZxdVQVNqEv8s2M0w0q8T/cjbLR+cBvVlNxYU
+8rGF4ugAY4uOGa4wbsgMhdUMLp4AQojEpNQHHbr4iJ5lGUUBIC/HVtZq5ZU/hLzJ
+E0xYnTyTovFPnCtwn4EJ9AkfLEKF0fi25vmu74x9bDTiivGdJ5b848iFZoEix2DV
+B1tBY4LMfyCmnJFQkqqJXJhU7Qmp85RKq+PSGs1OgQKBgQD30PJCT9ujCSJvlNBA
+IR3xyTeGsKxFruAgd6+sEtSifNFIpobTsAOOaYS3/ao8uQ3sM9DpzPH4xe7iXvyx
+t7XdlXVrT6rB0D7T0Pd0Qk4g3erjxiU4m8ArqSqOfzRUvEObtBTydTuuD+O3jn1e
+8awLuE576LJBTvFDSomvjsMNgQKBgQC4GLpBqOOFzjLyFtuhzDEKpgY5nzBsenSP
+6OyfA8fZYGOKaP23ghuE2E6mtsPjZPKo2dVbgaDvKmc74U5yUro7fvEk6ZsAw8Vy
+KvqvyJexe+8LROzuULaH3kMClUw5vAjhVU2lpqDfUaOGG+YbpsnEwFkmMz71AnRs
+NakTk856swKBgHSuG7KfORG9dkpFLfxT226BSDSRsLsqiHqg/8SsJRPQYxWq2qaH
+JFWEVynuNJ5cnzKMfxvmFDQGteA9ywq+LdID0gJRw1t3+mzu4eQKaBDPjA3suI+7
+vbKQ9uma+P/AmLCSDJ7QFeZxss01ONBgR5pJECMFQBDB45TEXqmbNTmBAoGBAIPz
+DUTUhUc5dOB5q7A7R4dHWjzgsXd/CZ7AJyEON6bBZHcnK3rlIU5FL5JkeuC4UQjf
+IQJ2VeA2N0n/AhgE3YCZSsPXQAb7SsC6t3VYxAktODeOjnd9mGan0sW+NqVG9eJ0
+HrQ1SyblP9x2kKaPFB0WdI9huaUovkN07puenCbrAoGBAM19Nart8imoJXiEKMwQ
+SU3F+e0qre7iFtyy1I/VwFLtrOSPvS84rRDL1zRaW04xn57aYqYIYnvhj0fW+YIs
+eN0UJcQu7QnTolY6IDO6CM1S0xF1xjUuELD0roD1/lOuDRz6XldHZmTuAGPTYVhj
+SMki+Ddzu6VVkTLS+8vQovMt
+-----END PRIVATE KEY-----
diff --git a/tests/mail-connections.test.js b/tests/mail-connections.test.js
new file mode 100644
index 0000000..73c9f35
--- /dev/null
+++ b/tests/mail-connections.test.js
@@ -0,0 +1,186 @@
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import net from 'node:net'
+import tls from 'node:tls'
+import { ImapFlow } from 'imapflow'
+import { openDb, seed } from '../server/db.js'
+import { Service } from '../server/service.js'
+import { readMailSettings, saveMailSettings, smtpTransport } from '../server/mail-config.js'
+import { imapOptions } from '../server/inbound.js'
+
+process.env.SMTP_ENCRYPTION_KEY = 'a9'.repeat(32)
+// Public test-only key/certificate; never used by the application or runtime image.
+const certificate = {
+ key: readFileSync(new URL('./fixtures/mail-test-key.pem', import.meta.url)),
+ cert: readFileSync(new URL('./fixtures/mail-test-cert.pem', import.meta.url)),
+}
+
+async function mailServer(protocol, security, advertiseStarttls = true) {
+ const sockets = new Set(),
+ commands = [],
+ authentications = []
+ function track(socket) {
+ sockets.add(socket)
+ socket.on('error', () => {})
+ socket.on('close', () => sockets.delete(socket))
+ }
+ function session(socket, greeting = true) {
+ track(socket)
+ if (greeting)
+ socket.write(protocol === 'smtp' ? '220 localhost test\r\n' : '* OK IMAP test\r\n')
+ let buffer = ''
+ function onData(chunk) {
+ buffer += chunk.toString()
+ while (buffer.includes('\r\n')) {
+ const index = buffer.indexOf('\r\n'),
+ line = buffer.slice(0, index)
+ buffer = buffer.slice(index + 2)
+ const parts = line.split(' '),
+ tag = protocol === 'imap' ? parts.shift() : ''
+ const command = parts[0].toUpperCase()
+ commands.push(command)
+ const reply = (value) => socket.write(value + '\r\n')
+ if (command === 'STARTTLS') {
+ if (!advertiseStarttls) {
+ reply(protocol === 'smtp' ? '454 TLS unavailable' : `${tag} BAD STARTTLS unavailable`)
+ continue
+ }
+ socket.removeListener('data', onData)
+ reply(protocol === 'smtp' ? '220 Ready for TLS' : `${tag} OK Ready for TLS`)
+ const encrypted = new tls.TLSSocket(socket, {
+ isServer: true,
+ secureContext: tls.createSecureContext(certificate),
+ })
+ session(encrypted, false)
+ return
+ }
+ if (protocol === 'smtp') {
+ if (command === 'EHLO' || command === 'HELO') {
+ reply('250-localhost')
+ if (advertiseStarttls && !socket.encrypted) reply('250-STARTTLS')
+ reply('250 AUTH PLAIN')
+ } else if (command === 'AUTH') {
+ authentications.push(!!socket.encrypted)
+ reply('235 Authentication successful')
+ } else if (command === 'QUIT') {
+ socket.end('221 Bye\r\n')
+ } else reply('500 Unexpected command')
+ } else {
+ if (command === 'CAPABILITY') {
+ reply(
+ `* CAPABILITY IMAP4rev1 NAMESPACE${advertiseStarttls && !socket.encrypted ? ' STARTTLS' : ''}`,
+ )
+ reply(`${tag} OK Capabilities`)
+ } else if (command === 'LOGIN') {
+ authentications.push(!!socket.encrypted)
+ reply(`${tag} OK Authenticated`)
+ } else if (command === 'NAMESPACE') {
+ reply('* NAMESPACE (("" "/")) NIL NIL')
+ reply(`${tag} OK Namespace`)
+ } else if (command === 'LOGOUT') {
+ socket.end(`* BYE\r\n${tag} OK Logged out\r\n`)
+ } else reply(`${tag} BAD Unexpected command`)
+ }
+ }
+ }
+ socket.on('data', onData)
+ }
+ const server =
+ security === 'tls' ? tls.createServer(certificate, session) : net.createServer(session)
+ // Also track sockets whose TLS handshake fails before the secureConnection event.
+ server.on('connection', track)
+ server.on('tlsClientError', () => {})
+ await new Promise((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(0, '127.0.0.1', resolve)
+ })
+ return {
+ port: server.address().port,
+ commands,
+ authentications,
+ async close() {
+ for (const socket of sockets) socket.destroy()
+ await new Promise((resolve) => server.close(resolve))
+ },
+ }
+}
+
+async function checkConnection(protocol, security, validateCertificate, advertiseStarttls = true) {
+ const server = await mailServer(protocol, security, advertiseStarttls),
+ db = openDb(':memory:')
+ let client
+ try {
+ seed(db)
+ const s = new Service(db),
+ admin = s.user('admin'),
+ settings = readMailSettings(s, admin, 'support')
+ saveMailSettings(s, admin, 'support', {
+ ...settings,
+ [protocol]: {
+ ...settings[protocol],
+ mode: 'smtp',
+ enabled: true,
+ host: '127.0.0.1',
+ port: server.port,
+ security,
+ validateCertificate,
+ username: 'test-user',
+ },
+ [protocol === 'smtp' ? 'password' : 'imapPassword']: 'test-password',
+ })
+ if (protocol === 'smtp') {
+ client = smtpTransport(s, 'support')
+ await client.verify()
+ } else {
+ client = new ImapFlow({ ...imapOptions(s, 'support'), verifyOnly: true })
+ client.on('error', () => {})
+ await client.connect()
+ }
+ assert.deepEqual(server.authentications, [security !== 'none'])
+ assert.equal(server.commands.includes('STARTTLS'), security === 'starttls')
+ } catch (error) {
+ assert.equal(
+ server.authentications.length,
+ 0,
+ 'Do not authenticate after failed TLS negotiation',
+ )
+ throw error
+ } finally {
+ client?.close()
+ await server.close()
+ db.close()
+ }
+}
+
+for (const protocol of ['smtp', 'imap']) {
+ for (const security of ['tls', 'starttls', 'none']) {
+ test(
+ `${protocol}: ${security} connects with the selected encryption (self-signed certificates allowed)`,
+ { timeout: 15000 },
+ async () => {
+ await checkConnection(protocol, security, false)
+ },
+ )
+ if (security !== 'none') {
+ test(
+ `${protocol}: ${security} rejects a self-signed certificate when validation is enabled`,
+ { timeout: 15000 },
+ async () => {
+ await assert.rejects(checkConnection(protocol, security, true), (error) =>
+ /self.signed|certificate/i.test(error.message),
+ )
+ },
+ )
+ }
+ }
+ test(
+ `${protocol}: required STARTTLS refuses a server without STARTTLS before authentication`,
+ { timeout: 15000 },
+ async () => {
+ await assert.rejects(checkConnection(protocol, 'starttls', false, false), (error) =>
+ /STARTTLS|TLS/i.test(error.message),
+ )
+ },
+ )
+}
diff --git a/tests/service.test.js b/tests/service.test.js
index 08b4afd..96bade7 100644
--- a/tests/service.test.js
+++ b/tests/service.test.js
@@ -959,6 +959,102 @@ test('Manual tickets enforce queue permissions, are idempotent, audited and do n
db.close()
}
})
+test('Mail encryption and certificate validation persist per queue, preserve old settings and reject invalid updates atomically', () => {
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'syncova-mail-security-'))
+ const file = path.join(dir, 'test.db')
+ let db
+ try {
+ const initial = setup(file)
+ db = initial.db
+ const { s, admin } = initial
+ let c = configureImap(s, admin, 'support')
+ // Existing installations stored the implicit TLS mode as "tls" without this new field.
+ delete c.imap.validateCertificate
+ s.run('UPDATE queue_inbound SET config=? WHERE queue_id=?', JSON.stringify(c.imap), 'support')
+ const oldSmtp = {
+ mode: 'smtp',
+ host: 'exchange.example.invalid',
+ port: 465,
+ security: 'tls',
+ username: 'support',
+ }
+ c = saveMailSettings(s, admin, 'support', { ...c, smtp: oldSmtp, password: 'test-secret' })
+ s.run('UPDATE queue_mail SET smtp=? WHERE queue_id=?', JSON.stringify(oldSmtp), 'support')
+ c = readMailSettings(s, admin, 'support')
+ assert.equal(c.smtp.validateCertificate, true)
+ assert.equal(c.imap.validateCertificate, true)
+ assert.equal(smtpTransport(s, 'support', (o) => o).tls.rejectUnauthorized, true)
+ assert.equal(imapOptions(s, 'support').tls.rejectUnauthorized, true)
+ c = saveMailSettings(s, admin, 'support', {
+ ...c,
+ smtp: { ...c.smtp, security: 'none', port: 25, validateCertificate: false },
+ imap: { ...c.imap, security: 'tls', port: 25, validateCertificate: false },
+ })
+ const smtpPassword = s.get(
+ 'SELECT password FROM queue_mail WHERE queue_id=?',
+ 'support',
+ ).password
+ const imapPassword = s.get(
+ 'SELECT password FROM queue_inbound WHERE queue_id=?',
+ 'support',
+ ).password
+ // Older API clients omitting the field must preserve an explicit "Nein".
+ delete c.smtp.validateCertificate
+ delete c.imap.validateCertificate
+ c = saveMailSettings(s, admin, 'support', c)
+ assert.equal(c.smtp.validateCertificate, false)
+ assert.equal(c.imap.validateCertificate, false)
+ const smtp = smtpTransport(s, 'support', (o) => o)
+ assert.equal(smtp.port, 25)
+ assert.equal(smtp.secure, false)
+ assert.equal(smtp.requireTLS, false)
+ assert.equal(smtp.ignoreTLS, true)
+ assert.equal(imapOptions(s, 'support').port, 25)
+ assert.equal(imapOptions(s, 'support').secure, true)
+ assert.equal(imapOptions(s, 'support').tls.rejectUnauthorized, false)
+ assert.equal(readMailSettings(s, admin, 'vertrieb').smtp.validateCertificate, true)
+ assert.equal(readMailSettings(s, admin, 'vertrieb').imap.validateCertificate, true)
+ for (const protocol of ['smtp', 'imap']) {
+ for (const invalid of ['false', 0, null]) {
+ assert.throws(
+ () =>
+ saveMailSettings(s, admin, 'support', {
+ ...c,
+ [protocol]: { ...c[protocol], validateCertificate: invalid },
+ }),
+ { status: 400 },
+ )
+ assert.deepEqual(readMailSettings(s, admin, 'support'), c)
+ }
+ assert.throws(
+ () =>
+ saveMailSettings(s, admin, 'support', {
+ ...c,
+ [protocol]: { ...c[protocol], security: 'invalid' },
+ }),
+ { status: 400 },
+ )
+ }
+ assert.equal(
+ s.get('SELECT password FROM queue_mail WHERE queue_id=?', 'support').password,
+ smtpPassword,
+ )
+ assert.equal(
+ s.get('SELECT password FROM queue_inbound WHERE queue_id=?', 'support').password,
+ imapPassword,
+ )
+ db.close()
+ db = openDb(file)
+ const reopened = new Service(db)
+ assert.deepEqual(readMailSettings(reopened, reopened.user('admin'), 'support'), c)
+ assert.equal(smtpTransport(reopened, 'support', (o) => o).ignoreTLS, true)
+ assert.equal(imapOptions(reopened, 'support').tls.rejectUnauthorized, false)
+ } finally {
+ db?.close()
+ rmSync(dir, { recursive: true, force: true })
+ }
+})
+
test('IMAP secrets, TLS, configuration validation and atomic mail settings', () => {
const { db, s, admin, reader } = setup()
try {