Add configurable mail encryption and certificate validation per queue
This commit is contained in:
parent
4dec9ac483
commit
24043b96cc
@ -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.
|
||||
|
||||
47
README.md
47
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.
|
||||
|
||||
<details>
|
||||
<summary>Neue Verbindungseinstellungen mit fiktiver Exchange-Konfiguration</summary>
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
</details>
|
||||
|
||||
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.
|
||||
|
||||
BIN
docs/images/mail-security-imap.jpg
Normal file
BIN
docs/images/mail-security-imap.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 53 KiB |
BIN
docs/images/mail-security-smtp.jpg
Normal file
BIN
docs/images/mail-security-smtp.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 53 KiB |
@ -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",
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -52,18 +52,20 @@ export function InboundSettings({ config: c, update, password, setPassword, busy
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
<Field label="IMAP-Verbindungssicherheit">
|
||||
<Field label="IMAP-Verschlüsselung">
|
||||
<Select value={c.security} onChange={(v: string) => update('security', v)}>
|
||||
<option value="tls">SSL · direkt verschlüsselt</option>
|
||||
<option value="starttls">TLS (+STARTTLS) · Upgrade erforderlich</option>
|
||||
<option value="none">Keine</option>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field label="IMAP-Zertifikat validieren">
|
||||
<Select
|
||||
value={c.security}
|
||||
onChange={(v: string) => {
|
||||
update('security', v)
|
||||
update('port', v === 'tls' ? 993 : 143)
|
||||
}}
|
||||
value={String(c.validateCertificate)}
|
||||
onChange={(v: string) => update('validateCertificate', v === 'true')}
|
||||
>
|
||||
<option value="tls">TLS · verschlüsselt ab Verbindungsaufbau (Port 993)</option>
|
||||
<option value="starttls">
|
||||
STARTTLS · Verschlüsselung zwingend erforderlich (Port 143)
|
||||
</option>
|
||||
<option value="true">Ja</option>
|
||||
<option value="false">Nein</option>
|
||||
</Select>
|
||||
</Field>
|
||||
<div className="form-columns">
|
||||
|
||||
@ -172,7 +172,7 @@ export function QueueMailSettings({ q }: D) {
|
||||
onChange={(e) => updateSmtp('host', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Port">
|
||||
<Field label="SMTP-Port">
|
||||
<Input
|
||||
type="number"
|
||||
required
|
||||
@ -183,22 +183,20 @@ export function QueueMailSettings({ q }: D) {
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
<Field label="Verbindungssicherheit">
|
||||
<Field label="SMTP-Verschlüsselung">
|
||||
<Select value={smtp.security} onChange={(v: string) => updateSmtp('security', v)}>
|
||||
<option value="tls">SSL · direkt verschlüsselt</option>
|
||||
<option value="starttls">TLS (+STARTTLS) · Upgrade erforderlich</option>
|
||||
<option value="none">Keine</option>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field label="SMTP-Zertifikat validieren">
|
||||
<Select
|
||||
value={smtp.security}
|
||||
onChange={(v: string) =>
|
||||
setConfig({
|
||||
...config,
|
||||
smtp: { ...smtp, security: v, port: v === 'tls' ? 465 : 587 },
|
||||
})
|
||||
}
|
||||
value={String(smtp.validateCertificate)}
|
||||
onChange={(v: string) => updateSmtp('validateCertificate', v === 'true')}
|
||||
>
|
||||
<option value="tls">
|
||||
TLS · verschlüsselt ab Verbindungsaufbau (üblicherweise Port 465)
|
||||
</option>
|
||||
<option value="starttls">
|
||||
STARTTLS · Verschlüsselung zwingend erforderlich (üblicherweise Port 587)
|
||||
</option>
|
||||
<option value="true">Ja</option>
|
||||
<option value="false">Nein</option>
|
||||
</Select>
|
||||
</Field>
|
||||
<div className="form-columns">
|
||||
|
||||
@ -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([
|
||||
|
||||
19
tests/fixtures/mail-test-cert.pem
vendored
Normal file
19
tests/fixtures/mail-test-cert.pem
vendored
Normal file
@ -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-----
|
||||
28
tests/fixtures/mail-test-key.pem
vendored
Normal file
28
tests/fixtures/mail-test-key.pem
vendored
Normal file
@ -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-----
|
||||
186
tests/mail-connections.test.js
Normal file
186
tests/mail-connections.test.js
Normal file
@ -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),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
@ -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 {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user