/** * The SMTP sender behind the image's `EMAIL` binding, end to end (#291). CI only: * .github/workflows/docker.yml runs it on the candidate image, and it refuses to start outside * GitHub Actions. * * 1. Mailpit with a certificate made here, requiring STARTTLS and SMTP AUTH, so a message that * arrives went encrypted and authenticated. SeaweedFS and one instance, which trusts the * certificate through CLOUDHAL_SMTP_CA_FILE. * 2. Studio reports email delivery. The first owner invites someone with `delivery: "email"`, and * the invite arrives with its link. A password reset asked for by email arrives too. * 3. The instance's log names each send, but neither the SMTP password nor any link's token. * * node scripts/mail-smoke.ts --image [--port ] */ import { execFile } from "node:child_process"; import { randomBytes } from "node:crypto"; import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; if (process.env.GITHUB_ACTIONS !== "true") { console.error("mail-smoke runs in CI only (.github/workflows/docker.yml), never locally"); process.exit(2); } const arg = (name: string): string | undefined => { const i = process.argv.indexOf(`--${name}`); return i === -1 ? undefined : process.argv[i + 1]; }; const image = arg("image") ?? "cloudhal:ci"; const port = Number(arg("port") ?? 38787); const id = `cloudhal-mail-${process.pid}`; const names = { store: `${id}-store`, mailpit: `${id}-mailpit`, cloudhal: `${id}-cloudhal` }; // 127.0.0.1, never localhost (#306) const studio = `http://127.0.0.1:${port}`; const mailpitApi = `http://127.0.0.1:${port + 2}`; const compose = readFileSync( path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../deploy/docker/compose.yml"), "utf8", ); const pinned = (repo: string) => { const at = compose.indexOf(`image: ${repo}:`); if (at === -1) throw new Error(`compose.yml names no ${repo} image`); return compose.slice(at + 7, compose.indexOf("\n", at)).trim(); }; const STORE_IMAGE = pinned("chrislusf/seaweedfs"); const MAILPIT_IMAGE = pinned("axllent/mailpit"); const run = promisify(execFile); async function docker(args: string[], timeout = 120_000): Promise { const { stdout } = await run("docker", args, { encoding: "utf8", timeout, maxBuffer: 64 << 20 }); return stdout.trim(); } async function dockerLogs(name: string): Promise { const { stdout, stderr } = await run("docker", ["logs", "--timestamps", name], { encoding: "utf8", timeout: 30_000, maxBuffer: 64 << 20, }); return `${stdout}${stderr}`; } const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); const step = (text: string) => console.log(`āœ“ ${text}`); function expect(ok: boolean, what: string, detail?: unknown): void { if (!ok) throw new Error(`${what}${detail === undefined ? "" : `: ${JSON.stringify(detail)}`}`); } const work = mkdtempSync(path.join(os.tmpdir(), "cloudhal-mail-")); const tls = path.join(work, "tls"); function envFile(name: string, env: Record): string { const file = path.join(work, `${name}.env`); writeFileSync( file, Object.entries(env) .map(([k, v]) => `${k}=${v}\n`) .join(""), { mode: 0o600 }, ); return file; } interface Res { status: number; text: string; body: unknown; headers: Headers; } async function req(url: string, init: RequestInit = {}): Promise { try { const res = await fetch(url, { ...init, signal: AbortSignal.timeout(30_000) }); const text = await res.text(); let body: unknown = text; try { body = JSON.parse(text); } catch { // not JSON } return { status: res.status, text, body, headers: res.headers }; } catch (e) { const err = e as { name?: string; cause?: { code?: string } }; const text = err.cause?.code ?? err.name ?? String(e); return { status: 0, text, body: text, headers: new Headers() }; } } async function until(what: string, seconds: number, check: () => Promise) { const deadline = Date.now() + seconds * 1000; while (Date.now() < deadline) { const v = await check().catch(() => undefined); if (v !== undefined) return v; await sleep(1000); } throw new Error(`${what} within ${seconds} s`); } /** A self-signed certificate for `mailpit`, readable by Mailpit's and Cloudhal's users. */ async function certificate(): Promise { await run("mkdir", ["-p", tls]); await run( "openssl", [ ...["req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes"], ...["-days", "2", "-subj", "/CN=mailpit", "-addext", "subjectAltName=DNS:mailpit"], ...["-keyout", path.join(tls, "key.pem"), "-out", path.join(tls, "cert.pem")], ], { timeout: 30_000 }, ); chmodSync(tls, 0o755); for (const f of ["key.pem", "cert.pem"]) chmodSync(path.join(tls, f), 0o644); } const smtpPassword = randomBytes(18).toString("hex"); async function start(env: Record): Promise { await docker(["network", "create", id]); const s3 = JSON.stringify({ identities: [ { name: "cloudhal", credentials: [{ accessKey: env.AWS_ACCESS_KEY_ID, secretKey: env.AWS_SECRET_ACCESS_KEY }], actions: ["Admin", "Read", "Write", "List", "Tagging"], }, ], }); await docker([ ...["run", "-d", "--name", names.store, "--network", id, "--network-alias", "seaweedfs"], ...["--env-file", envFile("store", { S3_CONFIG: s3 }), "--entrypoint", "/bin/sh"], STORE_IMAGE, "-c", 'printf "%s" "$S3_CONFIG" > /tmp/s3.json && exec weed server -dir=/data -s3 -s3.config=/tmp/s3.json -master.volumeSizeLimitMB=256', ]); const mailpit = envFile("mailpit", { MP_SMTP_TLS_CERT: "/tls/cert.pem", MP_SMTP_TLS_KEY: "/tls/key.pem", MP_SMTP_REQUIRE_STARTTLS: "true", MP_SMTP_AUTH: `cloudhal:${smtpPassword}`, }); await docker([ ...["run", "-d", "--name", names.mailpit, "--network", id, "--network-alias", "mailpit"], ...["--env-file", mailpit, "-v", `${tls}:/tls:ro`, "-p", `127.0.0.1:${port + 2}:8025`], MAILPIT_IMAGE, ]); const cloudhal = envFile("cloudhal", { ...env, CLOUDHAL_S3_ENDPOINT: "http://seaweedfs:8333", CLOUDHAL_S3_BUCKET: "cloudhal", CLOUDHAL_CLUSTER_ADVERTISE: `${names.cloudhal}:7000`, CLOUDHAL_SITE_NAME: "Mail Site", CLOUDHAL_BASE_URL: studio, CLOUDHAL_SMTP_URL: `smtp://cloudhal:${smtpPassword}@mailpit:1025`, CLOUDHAL_SMTP_CA_FILE: "/run/cloudhal-mail/cert.pem", CLOUDHAL_MAIL_FROM: "cloudhal@example.com", CLOUDHAL_MAIL_FROM_NAME: "Cloudhal Smoke", }); await docker([ ...["run", "-d", "--name", names.cloudhal, "--network", id, "--read-only", "--tmpfs", "/tmp"], ...["--cap-drop", "ALL", "--security-opt", "no-new-privileges:true"], ...["-v", `${tls}:/run/cloudhal-mail:ro`, "--env-file", cloudhal], ...["-p", `127.0.0.1:${port}:8787`, "-p", `127.0.0.1:${port + 1}:8788`], image, ]); } interface MailpitMessage { ID: string; To: { Address: string }[]; Subject: string; } /** The message Mailpit holds for `to`, with its plain text. */ function arrives(to: string): Promise<{ subject: string; text: string }> { return until(`no message to ${to} arrived`, 60, async () => { const list = await req(`${mailpitApi}/api/v1/messages`); const found = ((list.body as { messages?: MailpitMessage[] }).messages ?? []).find((m) => m.To.some((t) => t.Address === to), ); if (!found) return undefined; const full = await req(`${mailpitApi}/api/v1/message/${found.ID}`); return { subject: found.Subject, text: String((full.body as { Text?: string }).Text ?? "") }; }); } async function main(env: Record): Promise { await certificate(); await start(env); const admin = { authorization: `Bearer ${env.CLOUDHAL_DEPLOY_TOKEN}` }; await until("the instance did not create its site", 180, async () => { const r = await req(`${studio}/api/admin/sites`, { headers: admin }); const sites = (r.body as { sites?: { id: string }[] }).sites ?? []; return sites.some((s) => s.id === env.CLOUDHAL_SITE_ID) ? true : undefined; }); step("Mailpit (STARTTLS and AUTH required) and an instance with CLOUDHAL_SMTP_URL are up"); const json = { origin: studio, "content-type": "application/json" }; const signUp = await req(`${studio}/api/auth/sign-up/email`, { method: "POST", headers: { ...json, "x-cloudhal-setup-token": env.CLOUDHAL_SETUP_TOKEN as string }, body: JSON.stringify({ name: "Mail Owner", email: "owner@example.com", password: "mail-smoke-password", }), }); expect(signUp.status === 200, "sign-up of the first owner", signUp.body); const cookie = signUp.headers .getSetCookie() .map((c) => c.split(";")[0] as string) .find((c) => c.includes("better-auth.session_token=")) ?? ""; const instance = await req(`${studio}/api/instance`, { headers: { cookie } }); const delivery = (instance.body as { invites?: { delivery?: string[] } }).invites?.delivery; expect(delivery?.includes("email") === true, "Studio reports email delivery", instance.body); step("Studio reports invites by email"); const invite = await req(`${studio}/api/invites`, { method: "POST", headers: { ...json, cookie }, body: JSON.stringify({ email: "invitee@example.org", role: "editor", delivery: "email" }), }); expect(invite.status === 201, "the invite by email", invite.body); const invited = await arrives("invitee@example.org"); expect(invited.text.includes("/invite#chinv_"), "the invite carries its link", invited.subject); step(`the invite arrived through STARTTLS and AUTH ("${invited.subject}")`); const reset = await req(`${studio}/api/password-reset/request`, { method: "POST", headers: json, body: JSON.stringify({ email: "owner@example.com" }), }); expect(reset.status === 202, "the password reset request", reset.body); const resetMail = await arrives("owner@example.com"); expect(resetMail.text.length > 0, "the reset mail has a text"); step(`a password reset asked for by email arrived ("${resetMail.subject}")`); const logs = await dockerLogs(names.cloudhal); const sent = logs.split("\n").filter((l) => l.includes("smtp: sent to")); expect(sent.length >= 2, "the log names each send", sent); expect(!logs.includes(smtpPassword), "the log holds no SMTP password"); expect(!logs.includes("chinv_"), "the log holds no invite token"); step("the log names both sends and holds neither the password nor a token"); console.log("\nMail smoke test passed."); } const env = Object.fromEntries( (await docker(["run", "--rm", image, "secrets"])) .split("\n") .filter((l) => l.includes("=") && !l.startsWith("#")) .map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]), ) as Record; try { await main(env); } catch (e) { console.error(`\nāœ— ${e instanceof Error ? e.message : String(e)}`); for (const name of Object.values(names)) { const text = await dockerLogs(name).catch((d: Error) => `error: ${d.message}`); // the SMTP password is this run's own, but never print it anyway console.error( `--- ${name} logs\n${text.split(smtpPassword).join("").slice(-12_000)}`, ); } process.exitCode = 1; } finally { for (const name of Object.values(names)) await docker(["rm", "-f", "-v", name], 60_000).catch(() => undefined); await docker(["network", "rm", id], 30_000).catch(() => undefined); rmSync(work, { recursive: true, force: true }); }