Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

feat(docker): support file-backed secrets for container deployments (#1853)

tuttucodesb80818fe2e93
diff --git a/.env.sample b/.env.sample
index e8adc145b..593b379bb 100644
--- a/.env.sample
+++ b/.env.sample
@@ -9,6 +9,7 @@ KANEO_CLIENT_URL=http://localhost:5173
POSTGRES_DB=kaneo
POSTGRES_USER=kaneo
POSTGRES_PASSWORD=
+# Alternatively, mount a secret file and set POSTGRES_PASSWORD_FILE=/run/secrets/postgres_password
# POSTGRES_HOST=postgres # Compose container default; use localhost for host-native API startup
# POSTGRES_PORT=5432
# Note: POSTGRES_DB and POSTGRES_USER alone do not enable derived connection mode.
@@ -37,6 +38,7 @@ POSTGRES_PASSWORD=
# Required for host-native startup. Bundled image generates a temporary one if unset.
# Keep it stable: it protects authentication sessions.
AUTH_SECRET=
+# Alternatively, mount a secret file and set AUTH_SECRET_FILE=/run/secrets/auth_secret
# GitHub SSO (Sign in with GitHub, OAuth App)
GITHUB_OAUTH_CLIENT_ID=
diff --git a/.trufflehog-exclude b/.trufflehog-exclude
index 70368d240..6b1e4fa85 100644
--- a/.trufflehog-exclude
+++ b/.trufflehog-exclude
@@ -12,3 +12,4 @@
^apps/docs/
^\.cursor/rules/deployment-devops\.mdc$
^CONTRIBUTORS\.svg$
+^scripts/security/file-secrets\.test\.mjs$
diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts
index 2a69e66b4..6671be3cc 100644
--- a/apps/api/src/auth.ts
+++ b/apps/api/src/auth.ts
@@ -56,6 +56,7 @@ import {
} from "./utils/check-registration-allowed";
import { checkWorkspaceName } from "./utils/check-workspace-name";
import { mapCustomOAuthProfileToUser } from "./utils/custom-oauth-profile";
+import { resolveFileSecret } from "./utils/file-secret";
import { generateDemoName } from "./utils/generate-demo-name";
import { getDefaultCookieAttributes } from "./utils/get-default-cookie-attributes";
import { getInvitationEmailSubject } from "./utils/get-invitation-email-subject";
@@ -589,7 +590,7 @@ export const auth = betterAuth({
{
providerId: "custom",
clientId: process.env.CUSTOM_OAUTH_CLIENT_ID || "",
- clientSecret: process.env.CUSTOM_OAUTH_CLIENT_SECRET,
+ clientSecret: resolveFileSecret("CUSTOM_OAUTH_CLIENT_SECRET"),
authorizationUrl: process.env.CUSTOM_OAUTH_AUTHORIZATION_URL || "",
tokenUrl: process.env.CUSTOM_OAUTH_TOKEN_URL || "",
userInfoUrl: process.env.CUSTOM_OAUTH_USER_INFO_URL || "",
diff --git a/apps/api/src/database/resolve-database-url.ts b/apps/api/src/database/resolve-database-url.ts
index bd1ab718e..315439964 100644
--- a/apps/api/src/database/resolve-database-url.ts
+++ b/apps/api/src/database/resolve-database-url.ts
@@ -1,3 +1,5 @@
+import { resolveFileSecret } from "../utils/file-secret";
+
const LOCAL_FALLBACK_CONNECTION_STRING = "postgresql://localhost:5432/kaneo";
type DatabaseConfigSource = "DATABASE_URL" | "POSTGRES_ENV" | "LOCAL_FALLBACK";
@@ -21,6 +23,7 @@ export type ResolvedDatabaseConfig = {
function getDerivationSignal(): boolean {
return Boolean(
process.env.POSTGRES_PASSWORD ||
+ process.env.POSTGRES_PASSWORD_FILE ||
process.env.POSTGRES_HOST ||
process.env.POSTGRES_PORT,
);
@@ -53,14 +56,15 @@ export function resolveDatabaseConfig(): ResolvedDatabaseConfig {
}
if (getDerivationSignal()) {
- if (!process.env.POSTGRES_PASSWORD) {
+ const rawPassword = resolveFileSecret("POSTGRES_PASSWORD");
+ if (!rawPassword) {
throw new Error(
"POSTGRES_PASSWORD must be set when deriving DATABASE_URL from POSTGRES_* variables",
);
}
const username = process.env.POSTGRES_USER || "kaneo";
- const password = encodeURIComponent(process.env.POSTGRES_PASSWORD);
+ const password = encodeURIComponent(rawPassword);
const host = process.env.POSTGRES_HOST || "postgres";
const port = process.env.POSTGRES_PORT || "5432";
const database = process.env.POSTGRES_DB || "kaneo";
diff --git a/apps/api/src/utils/auth-secret.ts b/apps/api/src/utils/auth-secret.ts
index 71d41eba7..87b28e57b 100644
--- a/apps/api/src/utils/auth-secret.ts
+++ b/apps/api/src/utils/auth-secret.ts
@@ -1,6 +1,10 @@
+import { resolveFileSecret } from "./file-secret";
+
export const MIN_AUTH_SECRET_LENGTH = 32;
-export function resolveAuthSecret(raw = process.env.AUTH_SECRET): string {
+export function resolveAuthSecret(
+ raw = resolveFileSecret("AUTH_SECRET"),
+): string {
const secret = raw ?? "";
if (!secret) {
throw new Error(
diff --git a/apps/api/src/utils/file-secret.ts b/apps/api/src/utils/file-secret.ts
new file mode 100644
index 000000000..7fcc81c87
--- /dev/null
+++ b/apps/api/src/utils/file-secret.ts
@@ -0,0 +1,34 @@
+import { readFileSync } from "node:fs";
+
+const cachedFileSecrets = new Map<string, string>();
+
+export function resolveFileSecret(name: string): string | undefined {
+ const directValue = process.env[name];
+ if (directValue) return directValue;
+
+ const fileVariable = `${name}_FILE`;
+ const filePath = process.env[fileVariable];
+ if (!filePath) return undefined;
+
+ const cached = cachedFileSecrets.get(filePath);
+ if (cached !== undefined) return cached;
+
+ let value: string;
+ try {
+ value = readFileSync(filePath, "utf8").replace(/(?:\r?\n)+$/, "");
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code ?? "unknown";
+ throw new Error(
+ `${fileVariable} could not be read (${code}): ${filePath}`,
+ {
+ cause: error,
+ },
+ );
+ }
+
+ if (!value) {
+ throw new Error(`${fileVariable} points to an empty file: ${filePath}`);
+ }
+ cachedFileSecrets.set(filePath, value);
+ return value;
+}
diff --git a/apps/api/src/utils/get-settings.ts b/apps/api/src/utils/get-settings.ts
index 0646ca9fa..38f20b105 100644
--- a/apps/api/src/utils/get-settings.ts
+++ b/apps/api/src/utils/get-settings.ts
@@ -1,6 +1,7 @@
import { isSmtpConfigured } from "@kaneo/email";
import { config } from "dotenv-mono";
import { isBillingEnabled } from "../billing/config";
+import { resolveFileSecret } from "./file-secret";
import { isGithubSsoConfigured } from "./github-sso-env";
import { isCloud } from "./is-cloud";
@@ -25,7 +26,7 @@ function getSettings() {
Boolean(process.env.DISCORD_CLIENT_SECRET),
hasCustomOAuth:
Boolean(process.env.CUSTOM_OAUTH_CLIENT_ID) &&
- Boolean(process.env.CUSTOM_OAUTH_CLIENT_SECRET),
+ Boolean(resolveFileSecret("CUSTOM_OAUTH_CLIENT_SECRET")),
hasGuestAccess: [
"DISABLE_GUEST_ACCESS",
"DISABLE_REGISTRATION",
diff --git a/apps/docs/core/installation/docker-compose.mdx b/apps/docs/core/installation/docker-compose.mdx
index e45c03f52..3e19aea4b 100644
--- a/apps/docs/core/installation/docker-compose.mdx
+++ b/apps/docs/core/installation/docker-compose.mdx
@@ -109,6 +109,53 @@ docker compose up -d --force-recreate kaneo
A plain restart keeps the old environment. If you use a proxy in another container, connect it to Kaneo's Docker network and proxy to `kaneo:5173` instead of the host's loopback address.
+## Keep secrets in files
+
+Instead of putting `POSTGRES_PASSWORD` and `AUTH_SECRET` in `.env`, you can mount them as Docker secret files. This requires a Kaneo release that includes `_FILE` support, so raise `KANEO_IMAGE_TAG` past `2.28.3` first.
+
+Move the values you already use from `.env` into their own files:
+
+```bash
+mkdir -p secrets
+sed -n 's/^POSTGRES_PASSWORD=//p' .env > secrets/postgres_password
+sed -n 's/^AUTH_SECRET=//p' .env > secrets/auth_secret
+chmod 700 secrets
+chmod 644 secrets/*
+```
+
+Keep the current values. PostgreSQL sets its password only when it first initializes the `postgres_data` volume, so a new value in the file would no longer match the database. A new `AUTH_SECRET` would also sign everyone out. Generate fresh values with `openssl rand -hex 32` only for a new installation that has not started yet.
+
+Compose mounts these files with their host ownership, and the containers read them as non-root users (UID 1001 for Kaneo, `postgres` for PostgreSQL). The files therefore need to be readable by other users, while the `700` directory keeps other accounts on the host from reaching them.
+
+Remove `POSTGRES_PASSWORD` and `AUTH_SECRET` from `.env`. In `compose.yml`, replace the `POSTGRES_PASSWORD` line of the `postgres` service and add the secrets to both services:
+
+```yaml
+services:
+ postgres:
+ environment:
+ POSTGRES_USER: ${POSTGRES_USER:-kaneo}
+ POSTGRES_DB: ${POSTGRES_DB:-kaneo}
+ POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
+ secrets:
+ - postgres_password
+
+ kaneo:
+ environment:
+ POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
+ AUTH_SECRET_FILE: /run/secrets/auth_secret
+ secrets:
+ - postgres_password
+ - auth_secret
+
+secrets:
+ postgres_password:
+ file: ./secrets/postgres_password
+ auth_secret:
+ file: ./secrets/auth_secret
+```
+
+Keep the other keys of each service as they are. For [custom OAuth](/core/social-providers/custom-oauth), mount the client secret the same way and set `CUSTOM_OAUTH_CLIENT_SECRET_FILE`. A direct value in `.env` takes precedence over its `_FILE` variable, so leave the direct variable unset. See the [environment variable reference](/core/installation/environment-variables#authentication) for how files are read and what happens when one is missing.
+
## Optional features
- [Silo](/core/installation/silo) stores images and attachments.
diff --git a/apps/docs/core/installation/environment-variables.mdx b/apps/docs/core/installation/environment-variables.mdx
index f00ef989f..8c8a4ce66 100644
--- a/apps/docs/core/installation/environment-variables.mdx
+++ b/apps/docs/core/installation/environment-variables.mdx
@@ -40,6 +40,7 @@ Name | Description |
| `POSTGRES_PASSWORD` | The password for the PostgreSQL database. Use a strong value in production.
| `POSTGRES_HOST` | Database hostname for derived configuration. Default: `postgres`; use `localhost` for a host-native API connected to local PostgreSQL. |
| `POSTGRES_PORT` | Database port for derived configuration. Default: `5432`. |
+| `POSTGRES_PASSWORD_FILE` | Path to a UTF-8 file containing the database password. Used when `POSTGRES_PASSWORD` is unset and Kaneo derives `DATABASE_URL` from `POSTGRES_*`. Set the same file variable on the PostgreSQL container when using the bundled Compose setup; see [Keep secrets in files](/core/installation/docker-compose#keep-secrets-in-files). |
### Authentication
@@ -49,8 +50,14 @@ Name | Description |
--- | --- |
| `AUTH_SECRET` | The secret used by the authentication service. **Must be at least 32 characters long**, use a long, random value in production. Example: use `openssl rand -base64 32` to generate a secure key in Linux/macOS.
| `COOKIE_DOMAIN` | Optional cookie domain override. Leave unset for host-only cookies. Set a parent domain only when your deployment needs cookies shared across its trusted subdomains. |
+| `AUTH_SECRET_FILE` | Path to a UTF-8 file containing the authentication secret. Used when `AUTH_SECRET` is unset; the same 32-character minimum applies. |
| `DEVICE_AUTH_CLIENT_IDS` | **Optional.** Comma-separated list of allowed device authorization client IDs. When unset, Kaneo implicitly allows `kaneo-cli` and `kaneo-mcp` by default, so no extra configuration is required for the CLI or MCP. Override only when you need additional trusted clients, for example `kaneo-cli,kaneo-mcp,my-desktop-app`. |
+The Docker Compose quick-start pins image `2.28.3`, which predates `_FILE`
+support. Raise `KANEO_IMAGE_TAG` to a release containing this feature before
+following [Keep secrets in files](/core/installation/docker-compose#keep-secrets-in-files).
+
+For the supported `_FILE` variables, a non-empty direct value takes precedence. Kaneo removes trailing line endings from secret files but keeps other whitespace. Missing, unreadable, or empty files fail startup instead of silently using a fallback. Secrets are read at startup; restart Kaneo after rotating a file. `DATABASE_URL` takes precedence over both PostgreSQL password variables.
## Optional variables
@@ -162,6 +169,7 @@ Name | Description |
--- | --- |
| `CUSTOM_OAUTH_CLIENT_ID` | OAuth client ID from your provider.
| `CUSTOM_OAUTH_CLIENT_SECRET` | OAuth client secret from your provider.
+| `CUSTOM_OAUTH_CLIENT_SECRET_FILE` | Path to a UTF-8 file containing the custom OAuth client secret. Used when `CUSTOM_OAUTH_CLIENT_SECRET` is unset.
| `CUSTOM_OAUTH_AUTHORIZATION_URL` | Authorization endpoint URL.
| `CUSTOM_OAUTH_TOKEN_URL` | Token exchange endpoint URL.
| `CUSTOM_OAUTH_USER_INFO_URL` | User info endpoint URL.
diff --git a/apps/web/src/components/kanban-board/task-labels.test.tsx b/apps/web/src/components/kanban-board/task-labels.test.tsx
index e4392c7ba..37b59c774 100644
--- a/apps/web/src/components/kanban-board/task-labels.test.tsx
+++ b/apps/web/src/components/kanban-board/task-labels.test.tsx
@@ -1,7 +1,15 @@
import { cleanup, render, screen } from "@testing-library/react";
-import { afterEach, describe, expect, it } from "vite-plus/test";
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { TaskLabels } from "./task-labels";
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ i18n: { language: "en-US", resolvedLanguage: "en-US" },
+ }),
+ initReactI18next: { type: "3rdParty", init: vi.fn() },
+}));
+
afterEach(() => {
cleanup();
});
diff --git a/deploy/kaneo-entrypoint.sh b/deploy/kaneo-entrypoint.sh
index 7f60d131f..2c9c90932 100644
--- a/deploy/kaneo-entrypoint.sh
+++ b/deploy/kaneo-entrypoint.sh
@@ -5,6 +5,24 @@ urlencode() {
node -e 'const input = process.argv[1]; process.stdout.write(encodeURIComponent(input).replace(/[!\x27()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`));' -- "$1"
}
+check_file_secret() {
+ node -e '
+ const fs = require("node:fs");
+ const [name, file] = process.argv.slice(1);
+ let value;
+ try {
+ value = fs.readFileSync(file, "utf8").replace(/(?:\r?\n)+$/, "");
+ } catch (error) {
+ process.stderr.write(`ERROR: ${name} could not be read (${error.code ?? "unknown"}): ${file}\n`);
+ process.exit(1);
+ }
+ if (!value) {
+ process.stderr.write(`ERROR: ${name} points to an empty file: ${file}\n`);
+ process.exit(1);
+ }
+ ' -- "$1" "$2"
+}
+
api_pid=""
nginx_pid=""
@@ -39,6 +57,9 @@ if [ -z "${DATABASE_URL:-}" ]; then
encoded_password="$(urlencode "$POSTGRES_PASSWORD")"
export DATABASE_URL="postgresql://${encoded_user}:${encoded_password}@${POSTGRES_HOST:-postgres}:${POSTGRES_PORT:-5432}/${POSTGRES_DB}"
echo "DATABASE_URL not set — derived from POSTGRES_* vars"
+ elif [ -n "${POSTGRES_PASSWORD_FILE:-}" ]; then
+ check_file_secret POSTGRES_PASSWORD_FILE "$POSTGRES_PASSWORD_FILE"
+ echo "DATABASE_URL not set — the API derives it from POSTGRES_* vars and POSTGRES_PASSWORD_FILE"
else
echo "ERROR: DATABASE_URL is not set and POSTGRES_PASSWORD is not set for bundled-image startup" >&2
exit 1
@@ -46,7 +67,9 @@ if [ -z "${DATABASE_URL:-}" ]; then
fi
# Auto-generate AUTH_SECRET if not set
-if [ -z "${AUTH_SECRET:-}" ]; then
+if [ -z "${AUTH_SECRET:-}" ] && [ -n "${AUTH_SECRET_FILE:-}" ]; then
+ check_file_secret AUTH_SECRET_FILE "$AUTH_SECRET_FILE"
+elif [ -z "${AUTH_SECRET:-}" ]; then
export AUTH_SECRET="$(node -e 'process.stdout.write(require("node:crypto").randomBytes(32).toString("hex"))')"
echo "WARNING: AUTH_SECRET not set — generated a random secret for this session."
echo "WARNING: Set AUTH_SECRET in your .env to persist sessions across restarts."
diff --git a/scripts/security/file-secrets.test.mjs b/scripts/security/file-secrets.test.mjs
new file mode 100644
index 000000000..9a24e7a49
--- /dev/null
+++ b/scripts/security/file-secrets.test.mjs
@@ -0,0 +1,122 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { test } from "node:test";
+
+const root = path.resolve(import.meta.dirname, "../..");
+const entrypoint = readFileSync(
+ path.join(root, "deploy/kaneo-entrypoint.sh"),
+ "utf8",
+);
+const startup = entrypoint.slice(
+ 0,
+ entrypoint.indexOf("/docker-entrypoint.d/env.sh"),
+);
+
+function runStartup(env) {
+ return spawnSync(
+ "sh",
+ ["-c", `${startup}\nprintf '%s\\n' "$DATABASE_URL" "$AUTH_SECRET"`],
+ {
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ DATABASE_URL: "",
+ POSTGRES_PASSWORD: "",
+ POSTGRES_PASSWORD_FILE: "",
+ AUTH_SECRET: "",
+ AUTH_SECRET_FILE: "",
+ ...env,
+ },
+ },
+ );
+}
+
+test("bundled startup checks secret files without exporting their contents", () => {
+ const directory = mkdtempSync(
+ path.join(tmpdir(), "kaneo-entrypoint-secret-"),
+ );
+ try {
+ const passwordFile = path.join(directory, "postgres-password");
+ const authFile = path.join(directory, "auth-secret");
+ writeFileSync(passwordFile, "space &/#%\n");
+ writeFileSync(authFile, `${"a".repeat(32)}\n`);
+
+ const result = runStartup({
+ POSTGRES_PASSWORD_FILE: passwordFile,
+ AUTH_SECRET_FILE: authFile,
+ });
+
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(result.stdout.split("\n").slice(-3, -1), ["", ""]);
+ assert.doesNotMatch(result.stdout, /space|a{32}/);
+ assert.doesNotMatch(result.stdout, /generated a random secret/);
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+test("direct values override unreadable secret-file paths", () => {
+ const result = runStartup({
+ POSTGRES_PASSWORD: "direct-password",
+ POSTGRES_PASSWORD_FILE: "/missing/postgres-password",
+ AUTH_SECRET: "a".repeat(32),
+ AUTH_SECRET_FILE: "/missing/auth-secret",
+ });
+
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(result.stdout.trimEnd().split("\n").slice(-2), [
+ "postgresql://kaneo:direct-password@postgres:5432/kaneo",
+ "a".repeat(32),
+ ]);
+});
+
+test("unreadable AUTH_SECRET_FILE fails instead of generating a session secret", () => {
+ const result = runStartup({
+ POSTGRES_PASSWORD: "direct-password",
+ AUTH_SECRET_FILE: "/missing/auth-secret",
+ });
+
+ assert.notEqual(result.status, 0);
+ assert.match(
+ result.stderr,
+ /AUTH_SECRET_FILE could not be read \(ENOENT\): \/missing\/auth-secret/,
+ );
+ assert.doesNotMatch(result.stdout, /generated a random secret/);
+});
+
+test("unreadable POSTGRES_PASSWORD_FILE fails before database startup", () => {
+ const result = runStartup({
+ POSTGRES_PASSWORD_FILE: "/missing/postgres-password",
+ AUTH_SECRET: "a".repeat(32),
+ });
+
+ assert.notEqual(result.status, 0);
+ assert.match(
+ result.stderr,
+ /POSTGRES_PASSWORD_FILE could not be read \(ENOENT\): \/missing\/postgres-password/,
+ );
+});
+
+test("an empty auth secret file fails instead of generating a random value", () => {
+ const directory = mkdtempSync(
+ path.join(tmpdir(), "kaneo-entrypoint-secret-"),
+ );
+ try {
+ const authFile = path.join(directory, "auth-secret");
+ writeFileSync(authFile, "\n");
+
+ const result = runStartup({
+ POSTGRES_PASSWORD: "direct-password",
+ AUTH_SECRET_FILE: authFile,
+ });
+
+ assert.notEqual(result.status, 0);
+ assert.match(result.stderr, /AUTH_SECRET_FILE points to an empty file/);
+ assert.doesNotMatch(result.stdout, /generated a random secret/);
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
diff --git a/tests/api-integration/file-backed-secrets.test.ts b/tests/api-integration/file-backed-secrets.test.ts
new file mode 100644
index 000000000..0532e3ace
--- /dev/null
+++ b/tests/api-integration/file-backed-secrets.test.ts
@@ -0,0 +1,100 @@
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { Pool } from "pg";
+import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
+import { resolveDatabaseConfig } from "../../apps/api/src/database/resolve-database-url";
+import { createApp } from "../../apps/api/src/index";
+import { resolveAuthSecret } from "../../apps/api/src/utils/auth-secret";
+
+const SECRET_ENV_KEYS = [
+ "DATABASE_URL",
+ "POSTGRES_HOST",
+ "POSTGRES_PORT",
+ "POSTGRES_USER",
+ "POSTGRES_DB",
+ "POSTGRES_PASSWORD",
+ "POSTGRES_PASSWORD_FILE",
+ "AUTH_SECRET",
+ "AUTH_SECRET_FILE",
+ "CUSTOM_OAUTH_CLIENT_ID",
+ "CUSTOM_OAUTH_CLIENT_SECRET",
+ "CUSTOM_OAUTH_CLIENT_SECRET_FILE",
+] as const;
+
+let savedEnv: Record<string, string | undefined>;
+let directory: string;
+
+beforeEach(() => {
+ savedEnv = Object.fromEntries(
+ SECRET_ENV_KEYS.map((key) => [key, process.env[key]]),
+ );
+ directory = mkdtempSync(path.join(tmpdir(), "kaneo-file-secrets-"));
+});
+
+afterEach(() => {
+ for (const key of SECRET_ENV_KEYS) {
+ if (savedEnv[key] === undefined) delete process.env[key];
+ else process.env[key] = savedEnv[key];
+ }
+ rmSync(directory, { recursive: true, force: true });
+});
+
+describe("API integration: file-backed secrets", () => {
+ it("connects to PostgreSQL with only POSTGRES_PASSWORD_FILE", async () => {
+ const testDatabase = new URL(process.env.DATABASE_URL ?? "");
+ const passwordFile = path.join(directory, "postgres-password");
+ writeFileSync(
+ passwordFile,
+ `${decodeURIComponent(testDatabase.password)}\n`,
+ );
+
+ delete process.env.DATABASE_URL;
+ process.env.POSTGRES_HOST = testDatabase.hostname;
+ process.env.POSTGRES_PORT = testDatabase.port || "5432";
+ process.env.POSTGRES_USER = decodeURIComponent(testDatabase.username);
+ process.env.POSTGRES_DB = testDatabase.pathname.replace(/^\//, "");
+ process.env.POSTGRES_PASSWORD = "";
+ process.env.POSTGRES_PASSWORD_FILE = passwordFile;
+
+ const config = resolveDatabaseConfig();
+ expect(config.source).toBe("POSTGRES_ENV");
+
+ const pool = new Pool({ connectionString: config.connectionString });
+ try {
+ const result = await pool.query<{ database: string }>(
+ "select current_database() as database",
+ );
+ expect(result.rows[0]?.database).toBe(process.env.POSTGRES_DB);
+ } finally {
+ await pool.end();
+ }
+ });
+
+ it("uses the AUTH_SECRET_FILE contents as the auth secret", () => {
+ const authFile = path.join(directory, "auth-secret");
+ const secret = "f".repeat(64);
+ writeFileSync(authFile, `${secret}\n`);
+
+ process.env.AUTH_SECRET = "";
+ process.env.AUTH_SECRET_FILE = authFile;
+
+ expect(resolveAuthSecret()).toBe(secret);
+ });
+
+ it("reports custom OAuth as configured with only CUSTOM_OAUTH_CLIENT_SECRET_FILE", async () => {
+ const clientSecretFile = path.join(directory, "custom-oauth-client-secret");
+ writeFileSync(clientSecretFile, "custom-client-secret\n");
+
+ process.env.CUSTOM_OAUTH_CLIENT_ID = "kaneo";
+ process.env.CUSTOM_OAUTH_CLIENT_SECRET = "";
+ process.env.CUSTOM_OAUTH_CLIENT_SECRET_FILE = clientSecretFile;
+
+ const response = await createApp().app.request("/api/config");
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual(
+ expect.objectContaining({ hasCustomOAuth: true }),
+ );
+ });
+});
diff --git a/tests/api/auth-secret.test.ts b/tests/api/auth-secret.test.ts
index 2e4231398..8201b6b1a 100644
--- a/tests/api/auth-secret.test.ts
+++ b/tests/api/auth-secret.test.ts
@@ -1,9 +1,34 @@
-import { describe, expect, it } from "vite-plus/test";
+import { mkdtempSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
import { resolveAuthSecret } from "../../apps/api/src/utils/auth-secret";
const valid = "a".repeat(32);
+const keys = ["AUTH_SECRET", "AUTH_SECRET_FILE"] as const;
describe("AUTH_SECRET resolution", () => {
+ const original: Partial<Record<(typeof keys)[number], string | undefined>> =
+ {};
+ let directory: string;
+
+ beforeEach(() => {
+ directory = mkdtempSync(path.join(tmpdir(), "kaneo-auth-secret-"));
+ for (const key of keys) {
+ original[key] = process.env[key];
+ delete process.env[key];
+ }
+ });
+
+ afterEach(() => {
+ for (const key of keys) {
+ const value = original[key];
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ rmSync(directory, { recursive: true, force: true });
+ });
+
it.each([undefined, ""])(
"refuses to start when AUTH_SECRET is %p",
(value) => {
@@ -27,4 +52,32 @@ describe("AUTH_SECRET resolution", () => {
it("accepts a secret of exactly 32 characters", () => {
expect(resolveAuthSecret(valid)).toBe(valid);
});
+
+ it("reads AUTH_SECRET_FILE when the direct value is absent", () => {
+ const file = path.join(directory, "auth-secret");
+ writeFileSync(file, `${valid}\n`);
+ process.env.AUTH_SECRET_FILE = file;
+
+ expect(resolveAuthSecret()).toBe(valid);
+ unlinkSync(file);
+ expect(resolveAuthSecret()).toBe(valid);
+ });
+
+ it("keeps direct AUTH_SECRET precedence over an invalid file path", () => {
+ process.env.AUTH_SECRET = valid;
+ process.env.AUTH_SECRET_FILE = path.join(directory, "missing");
+
+ expect(resolveAuthSecret()).toBe(valid);
+ });
+
+ it("rejects a missing or short file-backed AUTH_SECRET", () => {
+ const file = path.join(directory, "auth-secret");
+ process.env.AUTH_SECRET_FILE = file;
+ expect(() => resolveAuthSecret()).toThrow(
+ "AUTH_SECRET_FILE could not be read",
+ );
+
+ writeFileSync(file, "short\n");
+ expect(() => resolveAuthSecret()).toThrow(/less than 32/);
+ });
});
diff --git a/tests/api/database/resolve-database-url.test.ts b/tests/api/database/resolve-database-url.test.ts
index 1bc6e9765..4e342ef90 100644
--- a/tests/api/database/resolve-database-url.test.ts
+++ b/tests/api/database/resolve-database-url.test.ts
@@ -1,3 +1,6 @@
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
import {
resolveDatabaseConfig,
@@ -11,13 +14,16 @@ const keys = [
"POSTGRES_DB",
"POSTGRES_USER",
"POSTGRES_PASSWORD",
+ "POSTGRES_PASSWORD_FILE",
] as const;
describe("resolve-database-url", () => {
const original: Partial<Record<(typeof keys)[number], string | undefined>> =
{};
+ let directory: string;
beforeEach(() => {
+ directory = mkdtempSync(path.join(tmpdir(), "kaneo-db-secret-"));
for (const key of keys) {
original[key] = process.env[key];
delete process.env[key];
@@ -33,6 +39,7 @@ describe("resolve-database-url", () => {
process.env[key] = value;
}
}
+ rmSync(directory, { recursive: true, force: true });
});
it("returns DATABASE_URL unchanged when explicitly configured", () => {
@@ -83,6 +90,43 @@ describe("resolve-database-url", () => {
});
});
+ it("derives and URL-encodes POSTGRES_PASSWORD_FILE when no direct password exists", () => {
+ const file = path.join(directory, "db-password");
+ writeFileSync(file, "space &/#%!'\n");
+ process.env.POSTGRES_PASSWORD_FILE = file;
+
+ expect(resolveDatabaseConfig()).toMatchObject({
+ connectionString:
+ "postgresql://kaneo:space%20%26%2F%23%25!'@postgres:5432/kaneo",
+ source: "POSTGRES_ENV",
+ });
+ });
+
+ it("keeps direct database credentials ahead of file credentials", () => {
+ process.env.POSTGRES_PASSWORD = "direct";
+ process.env.POSTGRES_PASSWORD_FILE = path.join(directory, "missing");
+ expect(resolveDatabaseConnectionString()).toBe(
+ "postgresql://kaneo:direct@postgres:5432/kaneo",
+ );
+
+ process.env.DATABASE_URL = "postgresql://app:[email protected]/app";
+ process.env.POSTGRES_PASSWORD = "";
+ expect(resolveDatabaseConnectionString()).toBe(process.env.DATABASE_URL);
+ });
+
+ it("fails when POSTGRES_PASSWORD_FILE is missing or empty", () => {
+ const file = path.join(directory, "db-password");
+ process.env.POSTGRES_PASSWORD_FILE = file;
+ expect(() => resolveDatabaseConfig()).toThrow(
+ "POSTGRES_PASSWORD_FILE could not be read",
+ );
+
+ writeFileSync(file, "\n");
+ expect(() => resolveDatabaseConfig()).toThrow(
+ "POSTGRES_PASSWORD_FILE points to an empty file",
+ );
+ });
+
it("preserves the localhost fallback when only POSTGRES_DB and POSTGRES_USER are set", () => {
process.env.POSTGRES_DB = "kaneo";
process.env.POSTGRES_USER = "kaneo";
diff --git a/tests/api/file-secret.test.ts b/tests/api/file-secret.test.ts
new file mode 100644
index 000000000..2ee123a57
--- /dev/null
+++ b/tests/api/file-secret.test.ts
@@ -0,0 +1,77 @@
+import { mkdtempSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
+import { resolveFileSecret } from "../../apps/api/src/utils/file-secret";
+import getSettings from "../../apps/api/src/utils/get-settings";
+
+const keys = [
+ "CUSTOM_OAUTH_CLIENT_ID",
+ "CUSTOM_OAUTH_CLIENT_SECRET",
+ "CUSTOM_OAUTH_CLIENT_SECRET_FILE",
+] as const;
+
+describe("file-backed secrets", () => {
+ const original: Partial<Record<(typeof keys)[number], string | undefined>> =
+ {};
+ let directory: string;
+
+ beforeEach(() => {
+ directory = mkdtempSync(path.join(tmpdir(), "kaneo-file-secret-"));
+ for (const key of keys) {
+ original[key] = process.env[key];
+ delete process.env[key];
+ }
+ });
+
+ afterEach(() => {
+ for (const key of keys) {
+ const value = original[key];
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ rmSync(directory, { recursive: true, force: true });
+ });
+
+ it("uses a direct value before its file, even when that file is missing", () => {
+ process.env.CUSTOM_OAUTH_CLIENT_SECRET = "direct-secret";
+ process.env.CUSTOM_OAUTH_CLIENT_SECRET_FILE = path.join(
+ directory,
+ "missing",
+ );
+
+ expect(resolveFileSecret("CUSTOM_OAUTH_CLIENT_SECRET")).toBe(
+ "direct-secret",
+ );
+ });
+
+ it("reads a file-backed OAuth secret and exposes OAuth availability", () => {
+ const file = path.join(directory, "oauth-secret");
+ writeFileSync(file, " secret with spaces \r\n");
+ process.env.CUSTOM_OAUTH_CLIENT_ID = "client";
+ process.env.CUSTOM_OAUTH_CLIENT_SECRET_FILE = file;
+
+ expect(resolveFileSecret("CUSTOM_OAUTH_CLIENT_SECRET")).toBe(
+ " secret with spaces ",
+ );
+ expect(getSettings().hasCustomOAuth).toBe(true);
+
+ unlinkSync(file);
+ expect(getSettings().hasCustomOAuth).toBe(true);
+ });
+
+ it("rejects missing and empty files instead of silently disabling OAuth", () => {
+ const file = path.join(directory, "oauth-secret");
+ process.env.CUSTOM_OAUTH_CLIENT_ID = "client";
+ process.env.CUSTOM_OAUTH_CLIENT_SECRET_FILE = file;
+
+ expect(() => getSettings()).toThrow(
+ "CUSTOM_OAUTH_CLIENT_SECRET_FILE could not be read",
+ );
+
+ writeFileSync(file, "\n");
+ expect(() => getSettings()).toThrow(
+ "CUSTOM_OAUTH_CLIENT_SECRET_FILE points to an empty file",
+ );
+ });
+});