diff --git a/.env.example b/.env.example index a130e9c..80a59f8 100644 --- a/.env.example +++ b/.env.example @@ -6,6 +6,9 @@ MAIL_SERVER_URL=https://mail.example.com # Random secret used to derive encryption keys for persisted sessions. # Generate with: openssl rand -base64 48 +# APP_SECRET, APP_SECRET_PREVIOUS and OAUTH_CLIENT_SECRET can each be read +# from a file instead: APP_SECRET_FILE=/run/secrets/app-secret (set one form, +# not both). APP_SECRET=change-me # Listen address. :: answers on IPv6 and IPv4 alike; 0.0.0.0 is IPv4 only. diff --git a/README.md b/README.md index c56ca30..f5fb478 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,29 @@ settings included, lives on the server, so the container is disposable. `.env.example` lists the rest. +### Secrets in files + +`APP_SECRET`, `APP_SECRET_PREVIOUS` and `OAUTH_CLIENT_SECRET` can come from a +file instead, such as a mounted Kubernetes or Docker secret: set +`APP_SECRET_FILE=/run/secrets/app-secret` and leave `APP_SECRET` unset. One +trailing newline is dropped. The webmail won't start if both forms are set, or +if the file can't be read or is empty. The error names the variable and the +file, never the secret. + +### Read-only root filesystem + +The image runs with a read-only root. The only thing it writes is +`SESSION_FILE`, which defaults to `/data/sessions.json`: set it empty, or use +`SESSION_BACKEND=cookie`, and nothing needs to be writable. Give it a small +`/tmp` all the same (`--tmpfs /tmp`, or an `emptyDir` in Kubernetes), for +Node and anything else that expects one. `IMMUTABLE=1` makes the webmail check +all this at start and refuse to run if the root is writable or +`SESSION_FILE` is set: + +```sh +docker run --read-only --tmpfs /tmp -e IMMUTABLE=1 -e SESSION_FILE= ... +``` + On the mail server, set `INBUXA_WEBMAIL_URL` to the webmail's address (with `BASE_PATH`, if any) and `INBUXA_WEBMAIL_CLIENT_SECRET` to the shared secret. The server registers the client on start and allows the webmail's origin for diff --git a/server/src/config.ts b/server/src/config.ts index b53d9b6..181bdd4 100644 --- a/server/src/config.ts +++ b/server/src/config.ts @@ -4,6 +4,7 @@ import { randomBytes } from "node:crypto"; import { fileURLToPath } from "node:url"; import { existsSync, readFileSync, unlinkSync, writeFileSync } from "node:fs"; import { resolve } from "node:path"; +import { secretEnv } from "./secretenv.js"; /** Minimal .env loader (no dependency): first match wins, never overrides real env. */ function loadDotEnv() { @@ -46,7 +47,7 @@ function int(name: string, fallback: number): number { } const isProd = process.env.NODE_ENV === "production"; -let appSecret = process.env.APP_SECRET ?? ""; +let appSecret = secretEnv("APP_SECRET"); /* * inbuxa K-W1: where sessions live. "memory" (the default) keeps them in this * process, mirrored to SESSION_FILE when set. "cookie" seals the whole session @@ -61,10 +62,10 @@ if (sessionBackend !== "memory" && sessionBackend !== "cookie") { if (sessionBackend === "cookie" && (!appSecret || appSecret === "change-me")) { // An ephemeral secret would differ on every replica, so each would refuse // the others' cookies. Unlike memory mode there is no safe fallback. - throw new Error("SESSION_BACKEND=cookie needs APP_SECRET set, and the same on every replica"); + throw new Error("SESSION_BACKEND=cookie needs APP_SECRET (or APP_SECRET_FILE) set, and the same on every replica"); } /** Secrets that sealed cookies before APP_SECRET was rotated; they still open, never seal. */ -const appSecretPrevious = (process.env.APP_SECRET_PREVIOUS ?? "").split(",").map((s) => s.trim()).filter(Boolean); +const appSecretPrevious = secretEnv("APP_SECRET_PREVIOUS").split(",").map((s) => s.trim()).filter(Boolean); if (!appSecret || appSecret === "change-me") { if (isProd) { throw new Error("APP_SECRET must be set to a strong random value in production"); @@ -288,12 +289,12 @@ const stalwartServers = readStalwartServers(); * without BASE_PATH; the redirect URI is built from it and must match the one * registered exactly. */ -const oauthClientSecret = process.env.OAUTH_CLIENT_SECRET ?? ""; +const oauthClientSecret = secretEnv("OAUTH_CLIENT_SECRET"); if (sessionBackend === "cookie" && !oauthClientSecret) { // A sealed password in a cookie can't be revoked: changing it would leave // the old cookie working wherever it was copied. OAuth tokens are revoked // by the server when the password changes. - throw new Error("SESSION_BACKEND=cookie signs in with OAuth only: set OAUTH_CLIENT_SECRET"); + throw new Error("SESSION_BACKEND=cookie signs in with OAuth only: set OAUTH_CLIENT_SECRET (or OAUTH_CLIENT_SECRET_FILE)"); } const publicUrl = process.env.PUBLIC_URL ? httpUrl(process.env.PUBLIC_URL, "PUBLIC_URL") : ""; if (oauthClientSecret && !publicUrl) { diff --git a/server/src/secretenv.test.ts b/server/src/secretenv.test.ts new file mode 100644 index 0000000..9fd96ff --- /dev/null +++ b/server/src/secretenv.test.ts @@ -0,0 +1,45 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { secretEnv } from "./secretenv.js"; + +const never = () => { + throw new Error("read when it shouldn't be"); +}; + +test("a secret from the environment, as before", () => { + assert.equal(secretEnv("APP_SECRET", { APP_SECRET: "from-env" }, never), "from-env"); + assert.equal(secretEnv("APP_SECRET", {}, never), ""); +}); + +test("a secret from a file, one trailing newline dropped", () => { + const dir = mkdtempSync(join(tmpdir(), "webmail-secret-")); + try { + const path = join(dir, "app-secret"); + writeFileSync(path, "from-file\n"); + assert.equal(secretEnv("APP_SECRET", { APP_SECRET_FILE: path }), "from-file"); + writeFileSync(path, "crlf\r\n"); + assert.equal(secretEnv("APP_SECRET", { APP_SECRET_FILE: path }), "crlf"); + writeFileSync(path, " kept as is "); + assert.equal(secretEnv("APP_SECRET", { APP_SECRET_FILE: path }), " kept as is "); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("both set is refused, without the value in the message", () => { + assert.throws( + () => secretEnv("OAUTH_CLIENT_SECRET", { OAUTH_CLIENT_SECRET: "s3cret-value", OAUTH_CLIENT_SECRET_FILE: "/run/x" }, never), + (err: Error) => /both set/.test(err.message) && !err.message.includes("s3cret-value"), + ); +}); + +test("a missing or empty file is refused, naming the variable and path", () => { + assert.throws( + () => secretEnv("APP_SECRET", { APP_SECRET_FILE: "/nonexistent/app-secret" }), + /APP_SECRET_FILE: can't read \/nonexistent\/app-secret \(ENOENT\)/, + ); + assert.throws(() => secretEnv("APP_SECRET", { APP_SECRET_FILE: "/run/s" }, () => "\n"), /APP_SECRET_FILE: \/run\/s is empty/); +}); diff --git a/server/src/secretenv.ts b/server/src/secretenv.ts new file mode 100644 index 0000000..732f4bd --- /dev/null +++ b/server/src/secretenv.ts @@ -0,0 +1,34 @@ +import { readFileSync } from "node:fs"; + +/* + * inbuxa K-W4: a secret from the environment, or from the file `_FILE` + * names -- a mounted Kubernetes or Docker secret, so the value never sits in + * the process environment where `docker inspect` or a crash dump shows it. + * The server reads its own secrets the same way (`INBUXA__FILE`). + * + * One trailing newline is dropped, since `echo` and most editors add one. + * Setting both, or naming a file that can't be read or is empty, is refused: + * a webmail that quietly started with no secret, or the wrong one, would sign + * everyone out or fail every sign-in. Errors name the variable and the path, + * never the value. + */ +export function secretEnv( + name: string, + env: NodeJS.ProcessEnv = process.env, + read: (path: string) => string = (path) => readFileSync(path, "utf8"), +): string { + const value = env[name] ?? ""; + const file = env[`${name}_FILE`] ?? ""; + if (!file) return value; + if (value) throw new Error(`${name} and ${name}_FILE are both set: use one`); + let contents: string; + try { + contents = read(file); + } catch (err) { + const code = (err as NodeJS.ErrnoException).code ?? "unreadable"; + throw new Error(`${name}_FILE: can't read ${file} (${code})`); + } + const secret = contents.replace(/\r?\n$/, ""); + if (!secret) throw new Error(`${name}_FILE: ${file} is empty`); + return secret; +}