syncova-ticket/tests/docker-smoke.mjs
Weapie 24043b96cc
All checks were successful
Tests und Docker-Image / Tests und Frontend-Build (push) Successful in 1m5s
Tests und Docker-Image / Leeres Produktionsimage bauen und veröffentlichen (push) Successful in 1m47s
Add configurable mail encryption and certificate validation per queue
2026-11-04 09:40:58 +01:00

224 lines
8.9 KiB
JavaScript

import { spawnSync } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { createServer } from 'node:net'
import assert from 'node:assert/strict'
import { mkdirSync, mkdtempSync, existsSync, rmSync, realpathSync, writeFileSync } from 'node:fs'
import path from 'node:path'
const listener = createServer()
await new Promise((resolve) => listener.listen(0, '127.0.0.1', resolve))
const port = listener.address().port
await new Promise((resolve) => listener.close(resolve))
const project = `syncova-smoke-${Date.now()}`,
password = `Test-${randomUUID()}!`
mkdirSync('data', { recursive: true })
const secretPath = path.resolve('data', project + '-password')
writeFileSync(secretPath, password, { mode: 0o644, flag: 'wx' })
Object.assign(process.env, {
SYNCOVA_IMAGE: process.env.SYNCOVA_IMAGE || 'syncova-ticket:local',
SYNCOVA_PULL_POLICY: 'never',
ADMIN_PASSWORD: password,
ADMIN_PASSWORD_FILE: secretPath,
ADMIN_EMAIL: 'docker-test@example.invalid',
SYNCOVA_PORT: String(port),
SYNCOVA_BIND: '127.0.0.1',
APP_ORIGIN: 'https://smoke.example.invalid',
})
const args = ['compose', '--env-file', '.env.docker.example', '-p', project]
function compose(extra, selectedProject = project) {
const selectedArgs = [...args]
selectedArgs[selectedArgs.length - 1] = selectedProject
const result = spawnSync('docker', [...selectedArgs, ...extra], {
encoding: 'utf8',
timeout: 120000,
})
if (result.status !== 0)
throw new Error(
(result.stderr || result.error?.message || 'Docker fehlgeschlagen').replaceAll(
password,
'[redacted]',
),
)
return result.stdout
}
const base = `http://127.0.0.1:${port}`
let cookie = ''
const importProject = project + '-import'
let importSource
async function api(url, method = 'GET', data) {
const options = {
method,
headers: {
'Content-Type': 'application/json',
Connection: 'close',
...(cookie ? { cookie } : {}),
},
body: data === undefined ? undefined : JSON.stringify(data),
}
let response
try {
response = await fetch(base + '/api' + url, options)
} catch (error) {
if (method !== 'GET') throw error
await new Promise((resolve) => setTimeout(resolve, 500))
response = await fetch(base + '/api' + url, options)
}
assert.equal(response.status, 200, `HTTP ${response.status} ${url}`)
if (url === '/login') cookie = response.headers.get('set-cookie').split(';')[0]
return response.json()
}
try {
compose(['up', '-d', '--no-build', '--wait', '--wait-timeout', '60'])
console.log('Docker-Container ist gesund.')
await api('/login', 'POST', { email: process.env.ADMIN_EMAIL, password })
const ticket = await api('/tickets', 'POST', {
queue_id: 'support',
customer: 'customer@example.invalid',
customer_name: 'Persistenztest',
subject: 'Docker-Persistenz',
body: 'Container-Neustart prüfen',
key: randomUUID(),
})
await api('/queues/support/signatures', 'PUT', {
signatures: [
{
id: 'docker-signature',
name: 'HTML',
default: true,
format: 'html',
body: '<p><strong>Docker Support</strong><br><a href="https://example.org">Kontakt</a></p>',
},
],
})
const config = await api('/queues/support/mail')
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',
body: 'Anbei die Datei.',
signature_id: 'docker-signature',
key: randomUUID(),
attachments: [
{
name: 'persistenz.txt',
mime: 'text/plain',
content: Buffer.from('PERSISTENT-BYTES').toString('base64'),
},
],
})
await api('/queues/service', 'DELETE', { confirm: 'Service' })
await api('/queues/support/templates', 'PUT', {
templates: [{ name: 'Docker-Vorlage', body: 'Hallo {kunde.name}, dauerhaft gespeichert.' }],
})
const originalId = compose([
'exec',
'-T',
'syncova',
'node',
'--input-type=module',
'-e',
`
import {openDb} from './server/db.js';import {Service} from './server/service.js';
const db=openDb(),s=new Service(db);
s.ingest({messageId:'<docker-html-original@example.invalid>',references:[s.get('SELECT message_id FROM messages WHERE ticket_id=? ORDER BY created_at LIMIT 1',${ticket.id}).message_id],from:'customer@example.invalid',to:['support@syncova.local'],body:'HTML-Original mit Bild',html:'<p>Docker-Original<img src="cid:pixel"></p>',source:Buffer.from('From: customer@example.invalid\\r\\nContent-Type: text/html\\r\\n\\r\\n<p>Docker-Original</p>'),attachments:[{name:'pixel.png',mime:'image/png',content:'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a3ioAAAAASUVORK5CYII=',contentId:'pixel'}]});
console.log(s.get('SELECT id FROM messages WHERE message_id=?','<docker-html-original@example.invalid>').id);db.close();
`,
]).trim()
const first = await api(`/tickets/${ticket.id}`)
const attachment = first.messages.flatMap((m) => m.attachments)[0]
compose(['up', '-d', '--force-recreate', '--no-build', '--wait', '--wait-timeout', '60'])
console.log('Container wurde vollständig neu erstellt; dasselbe Volume wird verwendet.')
const restored = await api(`/tickets/${ticket.id}`)
assert((await api(`/messages/${originalId}/view`)).html.includes('data:image/png;base64,'))
assert(
(await api('/bootstrap')).queues
.find((q) => q.id === 'support')
.templates.some((t) => t.name === 'Docker-Vorlage'),
)
assert(restored.messages.some((m) => m.html?.includes('<strong>Docker Support</strong>')))
assert.equal(restored.messages.flatMap((m) => m.attachments)[0].id, attachment.id)
const bytes = await fetch(base + '/api/attachments/' + attachment.id, { headers: { cookie } })
assert.equal(bytes.status, 200)
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([
'exec',
'-T',
'syncova',
'node',
'--input-type=module',
'-e',
"import {openDb} from './server/db.js'; import {decryptSecret} from './server/secrets.js'; const db=openDb();if(!decryptSecret(db.prepare('SELECT password FROM queue_mail WHERE queue_id=?').get('support').password))throw Error('Missing key');db.close();",
])
console.log(
'Persistenz erfolgreich geprüft: Tickets, Nachrichten, Anhänge, HTML-Signaturen, Mailkonfiguration, Schlüssel, Sitzungen und Audit-Historie.',
)
compose(['stop'])
mkdirSync('data', { recursive: true })
importSource = mkdtempSync(path.join(path.resolve('data'), 'docker-import-test-'))
compose(['cp', 'syncova:/app/data/.', importSource])
assert(existsSync(path.join(importSource, 'syncova.db')))
compose(
[
'run',
'--rm',
'--no-deps',
'--user',
'0',
'--cap-add',
'CHOWN',
'--cap-add',
'DAC_OVERRIDE',
'--entrypoint',
'sh',
'--volume',
`${importSource}:/import:ro`,
'syncova',
'-c',
'node server/import-data.js && chown -R 1000:1000 /app/data',
],
importProject,
)
compose(['up', '-d', '--no-build', '--wait', '--wait-timeout', '60'], importProject)
assert.equal(
(await api(`/tickets/${ticket.id}`)).messages.flatMap((m) => m.attachments)[0].id,
attachment.id,
)
const importedFile = await fetch(base + '/api/attachments/' + attachment.id, {
headers: { cookie },
})
assert.equal(await importedFile.text(), 'PERSISTENT-BYTES')
const original = await fetch(base + `/api/messages/${originalId}/original`, {
headers: { cookie },
})
assert.equal(original.status, 200)
assert((await original.text()).includes('<p>Docker-Original</p>'))
console.log(
'Datenübernahme in ein neues Docker-Volume einschließlich Mail-Schlüssel erfolgreich geprüft.',
)
} finally {
compose(['down', '--volumes', '--remove-orphans'], importProject)
compose(['down', '--volumes', '--remove-orphans'])
if (importSource) {
const actual = realpathSync(importSource),
root = realpathSync('data') + path.sep
if (!actual.toLowerCase().startsWith(root.toLowerCase())) throw Error('Unerwarteter Testpfad')
rmSync(actual, { recursive: true, force: true })
}
console.log('Isolierte Docker-Testumgebung entfernt.')
rmSync(secretPath)
}