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: '

Docker Support
Kontakt

', }, ], }) const config = await api('/queues/support/mail') await api('/queues/support/mail', 'PUT', { ...config, 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' }) 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(restored.messages.some((m) => m.html?.includes('Docker Support'))) 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(!(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') 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) }