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), ) }, ) }