syncova-ticket/tests/inbound-resilience.test.js
Weapie 02a28f4ee9
All checks were successful
Tests und Docker-Image / Tests und Frontend-Build (push) Successful in 50s
Tests und Docker-Image / Leeres Produktionsimage bauen und veröffentlichen (push) Successful in 1m51s
Raise incoming mail and attachment limits to 50 MiB
2026-11-05 17:02:48 +01:00

384 lines
14 KiB
JavaScript

import { test } from 'node:test'
import assert from 'node:assert/strict'
import { mkdtempSync, rmSync } from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { openDb, seed } from '../server/db.js'
import { Service } from '../server/service.js'
import { readMailSettings, saveMailSettings } from '../server/mail-config.js'
import { InboundWorker } from '../server/inbound.js'
import { retryAt } from '../server/inbound-errors.js'
import { INCOMING_MAIL_BYTES } from '../server/mail-limits.js'
import { normaliseAttachments } from '../server/content.js'
import nodemailer from 'nodemailer'
process.env.SMTP_ENCRYPTION_KEY = 'a9'.repeat(32)
function setup(file = ':memory:') {
const db = openDb(file)
seed(db)
const s = new Service(db),
admin = s.user('admin')
const c = readMailSettings(s, admin, 'support')
saveMailSettings(s, admin, 'support', {
...c,
imap: { ...c.imap, enabled: true, host: 'imap.example.invalid', username: 'support' },
imapPassword: 'imap-secret-for-test',
})
return { db, s, admin }
}
const mime = (uid, valid = true) =>
Buffer.from(
`From: Anna Beispiel <anna@example.org>\r\nTo: support@syncova.local\r\n${valid ? `Message-ID: <resilience-${uid}@example.org>\r\n` : ''}Date: Thu, 05 Nov 2026 14:13:00 +0100\r\nSubject: Importprobe ${uid}\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nBitte helfen.\r\n`,
)
function fake(messages, state = {}) {
state.requests ||= []
return () => ({
mailbox: { uidValidity: state.validity || 1n },
async connect() {},
async getMailboxLock() {
return { release() {} }
},
async search() {
return [...messages.keys()]
},
async fetchOne(uid, query) {
state.requests.push({ uid, type: query.size ? 'metadata' : 'source' })
if (query.size)
return {
size: state.sizes?.[uid] || messages.get(uid).length,
envelope: {
subject: `Kopf ${uid}`,
from: [{ name: 'Anna', address: 'anna@example.org' }],
to: [{ address: 'support@syncova.local' }],
date: new Date('2026-11-05T13:13:00Z'),
messageId: `<head-${uid}@example.org>`,
},
}
if (state.sourceErrors?.[uid]) throw state.sourceErrors[uid]
return { source: messages.get(uid) }
},
async messageFlagsAdd(uids) {
if (state.flagsError) throw state.flagsError
;(state.seen ||= []).push(uids)
},
async logout() {},
close() {},
})
}
const errors = (s) =>
s
.all("SELECT * FROM audits WHERE action='Nachricht konnte nicht importiert werden' ORDER BY id")
.map((a) => JSON.parse(a.after_value))
test('IMAP imports a complete MIME mail above 20 MiB with an attachment above the old 10 MiB limit', async () => {
const { db, s } = setup()
try {
const sent = await nodemailer
.createTransport({ streamTransport: true, buffer: true, newline: 'windows' })
.sendMail({
from: 'customer@example.org',
to: 'support@syncova.local',
messageId: '<large-mime@example.org>',
subject: 'Große Originalmail',
text: 'Bitte die Datei bearbeiten.',
attachments: [
{
filename: 'gross.bin',
content: Buffer.alloc(19 * 1024 * 1024, 97),
contentType: 'application/octet-stream',
},
],
})
const source = sent.message
assert(source.length > 20 * 1024 * 1024 && source.length < INCOMING_MAIL_BYTES)
const state = {}
const result = await new InboundWorker(s, {
clientFactory: fake(new Map([[1, source]]), state),
}).run('support')
assert.equal(result.imported, 1)
assert.equal(result.failed, 0)
assert.deepEqual(state.seen, [1])
const message = s.get("SELECT id FROM messages WHERE message_id='<large-mime@example.org>'")
assert.equal(
s.get('SELECT length(source) n FROM message_originals WHERE message_id=?', message.id).n,
source.length,
)
assert.equal(
s.get('SELECT length(content) n FROM attachments WHERE message_id=?', message.id).n,
19 * 1024 * 1024,
)
} finally {
db.close()
}
})
test('The 50 MiB metadata boundary is inclusive and oversized downloads are rejected even if metadata underreports size', async () => {
const { db, s } = setup()
try {
const messages = new Map([
[1, mime(1)],
[2, Buffer.alloc(INCOMING_MAIL_BYTES + 1)],
[3, mime(3)],
])
const state = { sizes: { 1: INCOMING_MAIL_BYTES, 2: 100 } }
const result = await new InboundWorker(s, { clientFactory: fake(messages, state) }).run(
'support',
)
assert.equal(result.imported, 2)
assert.equal(result.failed, 1)
assert.deepEqual(state.seen, [1, 3])
const [failure] = errors(s)
assert.equal(failure.code, 'MessageTooLarge')
assert.equal(failure.stage, 'download')
assert.match(failure.reason, /50 MiB/)
assert.equal(failure.size, INCOMING_MAIL_BYTES + 1)
} finally {
db.close()
}
})
test('Original storage accepts exactly 50 MiB and HTML above 20 MiB while refusing larger originals and HTML', () => {
const { db, s } = setup()
try {
const source = Buffer.alloc(INCOMING_MAIL_BYTES),
html = 'x'.repeat(21 * 1024 * 1024)
const incoming = {
messageId: '<large-storage@example.org>',
from: 'customer@example.org',
to: ['support@syncova.local'],
subject: 'Speicherlimit',
body: 'Beschreibung',
source,
html,
}
const id = s.ingest(incoming).ticket_id
const stored = s.get(
'SELECT length(o.source) source_size,length(o.html) html_size FROM message_originals o JOIN messages m ON m.id=o.message_id WHERE m.ticket_id=?',
id,
)
assert.equal(stored.source_size, INCOMING_MAIL_BYTES)
assert.equal(stored.html_size, html.length)
assert.throws(
() =>
s.ingest({
...incoming,
messageId: '<too-large-source@example.org>',
source: Buffer.alloc(INCOMING_MAIL_BYTES + 1),
html: null,
}),
/50 MiB/,
)
assert.throws(
() =>
s.ingest({
...incoming,
messageId: '<too-large-html@example.org>',
source: null,
html: 'x'.repeat(INCOMING_MAIL_BYTES + 1),
}),
/50 MiB/,
)
} finally {
db.close()
}
})
test('Outbound attachments retain their existing per-file and total limits', () => {
const large = { name: 'gross.bin', content: Buffer.alloc(11 * 1024 * 1024).toString('base64') }
assert.throws(() => normaliseAttachments([large]), /10 MiB/)
const small = { name: 'klein.bin', content: Buffer.alloc(8 * 1024 * 1024).toString('base64') }
assert.throws(() => normaliseAttachments([small, small, small]), /20 MiB/)
})
test('A failed message does not stop later imports and logs usable identity, cause and retry time', async () => {
const { db, s, admin } = setup()
try {
const state = {},
messages = new Map([
[1, mime(1, false)],
[2, mime(2)],
[3, mime(3)],
])
const worker = new InboundWorker(s, {
clientFactory: fake(messages, state),
clock: () => new Date('2030-01-01T00:00:00Z'),
})
const result = await worker.run('support')
assert.equal(result.imported, 2)
assert.equal(result.failed, 1)
assert.equal(result.pending, 1)
assert.deepEqual(state.seen, [2, 3])
assert.equal(s.get('SELECT count(*) n FROM inbound_receipts WHERE uid=1').n, 0)
const [error] = errors(s)
assert.equal(error.subject, 'Importprobe 1')
assert.equal(error.from, 'Anna Beispiel <anna@example.org>')
assert.equal(error.to, 'support@syncova.local')
assert.equal(error.date, '2026-11-05T13:13:00.000Z')
assert.match(error.reason, /Message-ID fehlt/)
assert.equal(error.stage, 'import')
assert.equal(error.uid, 1)
assert.equal(error.uidValidity, '1')
assert.equal(error.folder, 'INBOX')
assert.equal(error.nextRetry, '2030-01-01T00:01:00.000Z')
assert.match(error.continuation, /weiter/)
assert(!JSON.stringify(s.logs(admin)).includes('imap-secret-for-test'))
assert.equal(s.logs(s.user('mira')).length, 0)
} finally {
db.close()
}
})
test('More than 100 bad messages cannot starve new mail, including after a database restart', async () => {
const folder = mkdtempSync(path.join(os.tmpdir(), 'syncova-inbound-resilience-'))
let db
try {
const initial = setup(path.join(folder, 'test.db'))
db = initial.db
const messages = new Map()
for (let uid = 1; uid <= 105; uid++) messages.set(uid, mime(uid, false))
messages.set(106, mime(106))
const clock = () => new Date('2030-01-01T00:00:00Z')
assert.equal(
(await new InboundWorker(initial.s, { clientFactory: fake(messages), clock }).run('support'))
.failed,
100,
)
db.close()
db = openDb(path.join(folder, 'test.db'))
const s = new Service(db),
state = {}
const worker = new InboundWorker(s, { clientFactory: fake(messages, state), clock })
const second = await worker.run('support')
assert.equal(second.imported, 1)
assert.equal(second.failed, 5)
assert.equal(second.pending, 105)
assert.equal(second.retried, 0)
assert.equal(state.requests.filter((r) => r.type === 'source').length, 6)
const manual = await worker.run('support', { retryFailed: true })
assert.equal(manual.retried, 10)
assert.equal(manual.failed, 10)
assert.equal(manual.pending, 105)
messages.set(107, mime(107))
assert.equal((await worker.run('support')).imported, 1)
} finally {
db?.close()
assert.equal(path.dirname(path.resolve(folder)), path.resolve(os.tmpdir()))
assert(path.basename(folder).startsWith('syncova-inbound-resilience-'))
rmSync(folder, { recursive: true, force: true })
}
})
test('Retry cooldown is persistent, grows, and recovery removes failure state without duplicate tickets', async () => {
const { db, s } = setup()
try {
let at = new Date('2030-01-01T00:00:00Z')
const messages = new Map([[1, mime(1, false)]]),
factory = fake(messages)
let worker = new InboundWorker(s, { clientFactory: factory, clock: () => at })
await worker.run('support')
worker = new InboundWorker(s, { clientFactory: factory, clock: () => at })
assert.equal((await worker.run('support')).failed, 0)
assert.equal(errors(s).length, 1)
at = new Date('2030-01-01T00:01:01Z')
assert.equal((await worker.run('support')).retried, 1)
assert.equal(errors(s)[1].attempts, 2)
assert.equal(errors(s)[1].nextRetry, '2030-01-01T00:06:01.000Z')
messages.set(1, mime(1))
const recovered = await worker.run('support', { retryFailed: true })
assert.equal(recovered.imported, 1)
assert.equal(recovered.pending, 0)
assert.equal(recovered.ok, true)
assert.equal(s.get('SELECT count(*) n FROM inbound_failures').n, 0)
assert.equal((await worker.run('support')).imported, 0)
assert.equal(
s.get("SELECT count(*) n FROM messages WHERE message_id='<resilience-1@example.org>'").n,
1,
)
assert.equal(s.get("SELECT error FROM queue_inbound WHERE queue_id='support'").error, null)
assert.equal(retryAt(99, at), '2030-01-02T00:01:01.000Z')
} finally {
db.close()
}
})
test('Oversize and failed downloads retain envelope identity without logging raw server errors or credentials', async () => {
const { db, s } = setup()
try {
const messages = new Map([
[1, mime(1)],
[2, mime(2)],
[3, mime(3)],
])
const state = {
sizes: { 1: 51 * 1024 * 1024 },
sourceErrors: {
2: Object.assign(new Error('raw-server-password=do-not-log'), { code: 'ECONNRESET' }),
},
}
const result = await new InboundWorker(s, { clientFactory: fake(messages, state) }).run(
'support',
)
assert.equal(result.imported, 1)
assert.equal(result.failed, 2)
const [large, download] = errors(s)
assert.equal(large.subject, 'Kopf 1')
assert.equal(large.code, 'MessageTooLarge')
assert.equal(large.size, 51 * 1024 * 1024)
assert.match(large.reason, /50 MiB/)
assert(!state.requests.some((r) => r.uid === 1 && r.type === 'source'))
assert.equal(download.subject, 'Kopf 2')
assert.equal(download.stage, 'download')
assert.equal(download.code, 'ECONNRESET')
assert(!JSON.stringify(s.all('SELECT * FROM audits')).includes('do-not-log'))
} finally {
db.close()
}
})
test('Read flag errors are separate from import failures and never block new mail or cause duplicate imports', async () => {
const { db, s } = setup()
try {
const messages = new Map([
[1, mime(1)],
[2, mime(2)],
]),
state = { flagsError: Object.assign(new Error('server refused'), { code: 'NO' }) }
const worker = new InboundWorker(s, { clientFactory: fake(messages, state) })
const first = await worker.run('support')
assert.equal(first.imported, 2)
assert.equal(first.failed, 0)
assert.equal(first.pending, 0)
assert.equal(first.flagFailed, 2)
assert.equal(errors(s).length, 0)
messages.set(3, mime(3))
assert.equal((await worker.run('support')).imported, 1)
state.flagsError = null
assert.equal((await worker.run('support')).imported, 0)
assert.equal(s.get('SELECT count(*) n FROM inbound_receipts').n, 3)
assert.equal(s.get('SELECT count(*) n FROM inbound_failures').n, 0)
assert.equal(s.get("SELECT error FROM queue_inbound WHERE queue_id='support'").error, null)
} finally {
db.close()
}
})
test('Failure cooldown does not cross a changed UIDVALIDITY', async () => {
const { db, s } = setup()
try {
const messages = new Map([[1, mime(1, false)]]),
state = { validity: 1n }
const clock = () => new Date('2030-01-01T00:00:00Z')
await new InboundWorker(s, { clientFactory: fake(messages, state), clock }).run('support')
messages.set(1, mime(1))
state.validity = 2n
const result = await new InboundWorker(s, { clientFactory: fake(messages, state), clock }).run(
'support',
)
assert.equal(result.imported, 1)
assert.equal(result.retried, 0)
assert.equal(result.pending, 0)
} finally {
db.close()
}
})