diff --git a/CHANGELOG.md b/CHANGELOG.md index bf45a3c..eff9115 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Aktueller Stand +- SMTP und IMAP pro Queue: SSL, verpflichtendes TLS (+STARTTLS) oder keine Verschlüsselung sowie getrennte Zertifikatsprüfung (Ja/Nein). Individuelle Ports bleiben bei Änderungen erhalten; vorhandene Konten bleiben kompatibel. - Antwortvorlagen pro Queue mit Platzhaltern und Einfügen an der Cursorposition. - Automatische HTML-Darstellung neuer eingehender Mails, sichere CID-Bilder und Originalansicht mit `.eml`-Download. - HTML-Nachrichten und Signaturvorschauen folgen dem Hell-/Dunkelmodus; externe Bilder bleiben standardmäßig blockiert. diff --git a/README.md b/README.md index aa7cb22..242ced5 100644 --- a/README.md +++ b/README.md @@ -31,18 +31,18 @@ Syncova Ticket ist ein deutschsprachiges, selbst gehostetes Ticketsystem für Te ## Funktionen -| Bereich | Möglichkeiten | -| ------------------- | -------------------------------------------------------------------------------------------------------------- | -| Ticketbearbeitung | Suche, Filter, Sortierung, Zuständigkeiten, manuelle Tickets, Queue-Wechsel und interne Notizen | -| Queues | Eigene Adressen, freigegebene Absender, Signaturen, Status, SMTP- und IMAP-Konten | -| E-Mail | TLS/STARTTLS, Referenz-basierte Threadzuordnung, Duplikaterkennung, persistente Versandwarteschlange | -| Empfang | IMAP-Postfach und Ordner je Queue, Intervall oder Cron-Ausdruck mit IANA-Zeitzone, manueller Abruf | -| Anhänge | Eingehende und ausgehende Dateien, geschützter Download, dauerhafte Speicherung in SQLite | -| Automatisierung | Warten auf Kunde, Termin oder Ware; optionale einmalige Eingangsbestätigung pro Queue | -| Signaturen | Klartext oder bereinigtes HTML, dynamische Benutzer-/Ticketdaten, geschützte Vorschau | -| Team | Benutzer, Gruppen, kombinierte Queue-Rechte, konfigurierbare Glocken- und Mailbenachrichtigungen | -| Nachvollziehbarkeit | Ticketaktivitäten, Vorher-/Nachher-Werte, Versandstatus und Systemprotokoll | -| Betrieb | Registry-Image, persistentes Volume, nicht privilegierter App-Benutzer, Healthcheck, Ressourcen- und Loglimits | +| Bereich | Möglichkeiten | +| ------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| Ticketbearbeitung | Suche, Filter, Sortierung, Zuständigkeiten, manuelle Tickets, Queue-Wechsel und interne Notizen | +| Queues | Eigene Adressen, freigegebene Absender, Signaturen, Status, SMTP- und IMAP-Konten | +| E-Mail | SSL/TLS, STARTTLS oder ohne Verschlüsselung; Zertifikatsprüfung pro Queue, Threadzuordnung und persistente Versandwarteschlange | +| Empfang | IMAP-Postfach und Ordner je Queue, Intervall oder Cron-Ausdruck mit IANA-Zeitzone, manueller Abruf | +| Anhänge | Eingehende und ausgehende Dateien, geschützter Download, dauerhafte Speicherung in SQLite | +| Automatisierung | Warten auf Kunde, Termin oder Ware; optionale einmalige Eingangsbestätigung pro Queue | +| Signaturen | Klartext oder bereinigtes HTML, dynamische Benutzer-/Ticketdaten, geschützte Vorschau | +| Team | Benutzer, Gruppen, kombinierte Queue-Rechte, konfigurierbare Glocken- und Mailbenachrichtigungen | +| Nachvollziehbarkeit | Ticketaktivitäten, Vorher-/Nachher-Werte, Versandstatus und Systemprotokoll | +| Betrieb | Registry-Image, persistentes Volume, nicht privilegierter App-Benutzer, Healthcheck, Ressourcen- und Loglimits | ## Bilder und Arbeitsabläufe @@ -214,7 +214,7 @@ Alles liegt unter **Einstellungen → Queue → Mail-Einstellungen**. Dafür ist | Einstellung | Beschreibung | | ------------------- | ------------------------------------------------------------------------------------------------------------- | -| SMTP | Queue-eigener Server, Port, Benutzername und Passwort; TLS ab Verbindungsaufbau oder verpflichtendes STARTTLS | +| SMTP | Queue-eigener Server, Port, Benutzername und Passwort; Verschlüsselung und Zertifikatsprüfung separat wählbar | | IMAP | Queue-eigenes Konto, Ordner, ungelesene Nachrichten und Markierung nach erfolgreicher Verarbeitung | | Intervall | Regelmäßiger Abruf in Sekunden | | Cron | Fünf Felder: Minute, Stunde, Tag, Monat, Wochentag; Auswertung in der gewählten IANA-Zeitzone | @@ -231,6 +231,27 @@ Beispiele: `*/5 * * * *` alle fünf Minuten; `0 8-18 * * 1-5` werktags stündlic SMTP- und IMAP-Passwörter werden serverseitig mit AES-256-GCM verschlüsselt. Im Normalbetrieb wird der zufällige Schlüssel als `/app/data/smtp.key` im persistenten Volume verwahrt. Leere Passwortfelder bei einer Bearbeitung behalten das gespeicherte Geheimnis; beim Wechsel von Server oder Benutzer muss das Passwort erneut eingegeben werden. +Für **SMTP und IMAP getrennt** stehen folgende Verbindungseinstellungen zur Verfügung: + +| Verschlüsselung | Verhalten | +| --------------- | -------------------------------------------------------------------------------------------------------------------- | +| SSL | Direkt verschlüsselter Verbindungsaufbau mit modernem TLS (üblicherweise SMTP 465 / IMAP 993; kein SSLv3) | +| TLS (+STARTTLS) | Zunächst Protokollverbindung, dann verpflichtendes TLS-Upgrade vor der Anmeldung (üblicherweise SMTP 587 / IMAP 143) | +| Keine | Unverschlüsselte Verbindung; auch ein vom Server angebotenes STARTTLS wird nicht verwendet | + +**Zertifikat validieren: Ja / Nein** bestimmt für das jeweilige Konto, ob die Vertrauenskette und der Servername geprüft werden. Mit „Nein“ sind beispielsweise selbst signierte Exchange-Zertifikate möglich. Bei „Keine“ findet keine TLS-Zertifikatsprüfung statt. Bestehende Konten behalten ihre Verschlüsselung und erhalten standardmäßig „Ja“; gespeicherte Passwörter und Abrufzeitpläne bleiben erhalten. + +Der Port ist frei konfigurierbar und wird beim Ändern der Verschlüsselung beibehalten. Beispiel für eine entsprechende Exchange-Konfiguration: SMTP **Keine**, Port **25**; IMAP **SSL**, Zertifikat validieren **Nein**, mit dem tatsächlich für IMAP eingerichteten Port. Auch Port 25 ist eintragbar, sofern dort wirklich der IMAP-Dienst lauscht; normalerweise wird dieser Port für SMTP verwendet. Zum Prüfen **Speichern & SMTP prüfen** bzw. bei aktiviertem Empfang **Speichern & IMAP prüfen** verwenden. + +
+Neue Verbindungseinstellungen mit fiktiver Exchange-Konfiguration + +![SMTP ohne Verschlüsselung mit frei wählbarem Port und eigener Zertifikatsoption](docs/images/mail-security-smtp.jpg) + +![IMAP mit direktem SSL/TLS und deaktivierter Zertifikatsprüfung in der isolierten Demo](docs/images/mail-security-imap.jpg) + +
+ Eingangsbestätigungen unterstützen `{ticketnummer}`, `{betreff}`, `{kundenname}` und `{queue}`. Sie sind bei manuellen Tickets und weiteren Kundenantworten nicht erneut aktiv. Automatisch erzeugte Mails und übliche Bulk-/Loop-Nachrichten werden zum Schutz vor Antwortschleifen ignoriert. Threads werden aus Message-ID, References/In-Reply-To, derselben Kundenadresse und der aktuellen Queue gebildet. Eine Betreffänderung allein erzeugt kein neues Ticket. Nachrichten an mehrere Queues oder ohne eindeutige To/Cc-Zuordnung werden zur Prüfung zurückgehalten. Empfang löscht keine Nachrichten vom Postfachserver. diff --git a/docs/images/mail-security-imap.jpg b/docs/images/mail-security-imap.jpg new file mode 100644 index 0000000..09eff47 Binary files /dev/null and b/docs/images/mail-security-imap.jpg differ diff --git a/docs/images/mail-security-smtp.jpg b/docs/images/mail-security-smtp.jpg new file mode 100644 index 0000000..0177b04 Binary files /dev/null and b/docs/images/mail-security-smtp.jpg differ diff --git a/package.json b/package.json index d333b8d..ac3103f 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "dev": "concurrently -k \"node --watch server/index.js\" \"vite --host 127.0.0.1\"", "start": "node server/index.js", "build": "panda codegen && tsc --noEmit && vite build", - "test": "node --test tests/service.test.js", + "test": "node --test tests/service.test.js tests/mail-connections.test.js", "prepare": "panda codegen", "test:docker": "node tests/docker-smoke.mjs", "test:image": "node tests/image-smoke.mjs", diff --git a/server/inbound.js b/server/inbound.js index 0e215af..0f287b0 100644 --- a/server/inbound.js +++ b/server/inbound.js @@ -25,6 +25,7 @@ function ensure(s, id) { host: process.env.IMAP_HOST || '', port: Number(process.env.IMAP_PORT || 993), security: 'tls', + validateCertificate: true, username: process.env.IMAP_USER || '', folder: 'INBOX', onlyUnread: true, @@ -45,6 +46,7 @@ function ensure(s, id) { export function inboundSettings(s, id) { const r = ensure(s, id) return { + validateCertificate: true, ...JSON.parse(r.config), passwordSet: !!r.password, runtime: { @@ -62,7 +64,8 @@ export function saveInbound(s, user, id, data, password) { if ( !data || typeof data.enabled !== 'boolean' || - !['tls', 'starttls'].includes(data.security) || + !['tls', 'starttls', 'none'].includes(data.security) || + (data.validateCertificate !== undefined && typeof data.validateCertificate !== 'boolean') || typeof data.host !== 'string' || typeof data.username !== 'string' || !Number.isInteger(Number(data.port)) || @@ -122,6 +125,7 @@ export function saveInbound(s, user, id, data, password) { host: data.host.trim(), port: Number(data.port), security: data.security, + validateCertificate: data.validateCertificate ?? before.validateCertificate, username: data.username.trim(), folder: data.folder.trim(), onlyUnread: data.onlyUnread, @@ -161,6 +165,7 @@ export function imapOptions(s, id) { port: c.port, secure: c.security === 'tls', doSTARTTLS: c.security === 'starttls', + tls: { rejectUnauthorized: c.validateCertificate !== false }, auth: { user: c.username, pass: decryptSecret(r.password) }, connectionTimeout: 10000, greetingTimeout: 10000, diff --git a/server/mail-config.js b/server/mail-config.js index ec2ad42..fafb90d 100644 --- a/server/mail-config.js +++ b/server/mail-config.js @@ -27,6 +27,7 @@ export function mailSettings(s, id) { security: 'tls', username: '', } + smtp.validateCertificate ??= true if (process.env.NODE_ENV === 'production' && smtp.mode === 'development') smtp.mode = 'disabled' return { allowDevelopment: process.env.NODE_ENV !== 'production', @@ -51,12 +52,16 @@ export function saveMailSettings(s, user, id, data) { if ( !smtp || !['smtp', 'development', 'legacy', 'disabled'].includes(smtp.mode) || - !['tls', 'starttls'].includes(smtp.security) || + !['tls', 'starttls', 'none'].includes(smtp.security) || + (smtp.validateCertificate !== undefined && typeof smtp.validateCertificate !== 'boolean') || !Number.isInteger(Number(smtp.port)) || Number(smtp.port) < 1 || Number(smtp.port) > 65535 ) - throw new HttpError(400, 'Gültigen Versandmodus, Port und TLS-Modus auswählen.') + throw new HttpError( + 400, + 'Gültigen Versandmodus, Port, Verschlüsselung und Zertifikatsprüfung auswählen.', + ) if (process.env.NODE_ENV === 'production' && smtp.mode === 'development') throw new HttpError(400, 'Der Entwicklungsadapter ist in Produktion deaktiviert.') if (smtp.mode === 'legacy' && before.smtp.mode !== 'legacy') @@ -109,6 +114,7 @@ export function saveMailSettings(s, user, id, data) { host: String(smtp.host || '').trim(), port: Number(smtp.port), security: smtp.security, + validateCertificate: smtp.validateCertificate ?? before.smtp.validateCertificate, username: String(smtp.username || '').trim(), } const cleanAck = { @@ -179,6 +185,8 @@ export function smtpTransport(s, id, factory = nodemailer.createTransport) { port: smtp.port, secure: smtp.security === 'tls', requireTLS: smtp.security === 'starttls', + ignoreTLS: smtp.security === 'none', + tls: { rejectUnauthorized: smtp.validateCertificate !== false }, auth: { user: smtp.username, pass: decryptSecret(row.password) }, connectionTimeout: 10000, greetingTimeout: 10000, diff --git a/src/InboundSettings.tsx b/src/InboundSettings.tsx index 71f3fee..4ca4c5e 100644 --- a/src/InboundSettings.tsx +++ b/src/InboundSettings.tsx @@ -52,18 +52,20 @@ export function InboundSettings({ config: c, update, password, setPassword, busy /> - + + + +
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 +BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MTEwNDA4MzI1NloXDTQ2MTAz +MDA4MzI1NlowFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF +AAOCAQ8AMIIBCgKCAQEAsjYeA78saWszWfZR568CVWLhoQeZRhsxyQHsSRSLUJBY +IbL9Km+sP7Lo9HFQ+JyoIDudqdWeKt5BQd7TUc2ZB5p6yUbqaOTqk1GDKvoyZhSa +uwKlduEuBRYFYdbcN4upUXzcnOOIq+z8F5PGbIRUAuIqUQt0r+9vLP1pYcTieVRN +hPnQYMEF/9r5WmbhfAyj2edMgc32vCfvrMvQ+Esh23C7MKazYJnbQfdatEggrRbF +Tru/QKq9VW2Q6FLiqoQOw5gRWru+snbXV5EolPQPxruhBHFBOV35zTtVZI69zGaa +5Xt1KiilDwwUrTkfnquBRPtysPkDNZzBE/sSt5/rMwIDAQABo28wbTAdBgNVHQ4E +FgQUIIOI+svdLE3NtAte5RYvxx52amQwHwYDVR0jBBgwFoAUIIOI+svdLE3NtAte +5RYvxx52amQwDwYDVR0TAQH/BAUwAwEB/zAaBgNVHREEEzARgglsb2NhbGhvc3SH +BH8AAAEwDQYJKoZIhvcNAQELBQADggEBAH1veA1XKHstvcxq5Mf/tcJ0O7XurPaU +54o4xG2bmd8rrP2TJCwJNoutcRPbXmuASFPI6J47FArsYIAJCnro0yS9wNp68BQ5 +uqJZciuJUeSRuqGjfIkCdWDUPhBju8fcpgopIpAWPJI9GVufb6oNWJn0yonLfFLF +/gATaGxFWavX9hNHe1y0d270dnKS88wLIk3QbE8vPYZzoRGNzavqBVLObUHkZ01L +gFfsssRmYUZVFJzxzqGMOSnkQv0grZGTrIZrrzIghCzrN2lSskkFF0ZtQX9Qp0u0 +uyQRXpftBwXLG0/rt+pPg4VUCasA/Yhk6V+n33DqmfF8aa8XRhgT5+s= +-----END CERTIFICATE----- diff --git a/tests/fixtures/mail-test-key.pem b/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 {