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.

fix(admin): harden system probes and test email

Tin850bab0a3bdc
diff --git a/apps/api/src/admin/controllers/send-test-email.ts b/apps/api/src/admin/controllers/send-test-email.ts
index 54409150a..558b5a622 100644
--- a/apps/api/src/admin/controllers/send-test-email.ts
+++ b/apps/api/src/admin/controllers/send-test-email.ts
@@ -7,6 +7,7 @@ import { HTTPException } from "hono/http-exception";
import { ApiError } from "../../errors/api-error";
import type { AdminAuditRequest } from "../audit/admin-audit-request";
import { recordAdminAction } from "../audit/record-admin-action";
+import { safeErrorCode } from "../system/safe-error-code";
import { createAttemptLimiter } from "../system/attempt-limiter";
const testEmailLimiter = createAttemptLimiter({
@@ -73,13 +74,21 @@ async function sendAdminTestEmail(
if (!result.success) throw notConfigured();
- await recordAdminAction({
- ...audit,
- action: "email.test_sent",
- targetType: "user",
- targetId: userId,
- targetLabel: email,
- });
+ try {
+ await recordAdminAction({
+ ...audit,
+ action: "email.test_sent",
+ targetType: "user",
+ targetId: userId,
+ targetLabel: email,
+ });
+ } catch (error) {
+ // SMTP already accepted the message; an audit failure cannot undo it.
+ console.error("Admin audit entry could not be recorded:", {
+ action: "email.test_sent",
+ code: safeErrorCode(error),
+ });
+ }
return { sent: true as const, to: email };
}
diff --git a/apps/api/src/admin/system/describe-auth.test.ts b/apps/api/src/admin/system/describe-auth.test.ts
index 483954976..7c8a17e5e 100644
--- a/apps/api/src/admin/system/describe-auth.test.ts
+++ b/apps/api/src/admin/system/describe-auth.test.ts
@@ -7,6 +7,14 @@ const githubStatus = () =>
describe("describeAuth", () => {
afterEach(() => vi.unstubAllEnvs());
+ it("disables password registration when the login form is disabled", () => {
+ vi.stubEnv("DISABLE_REGISTRATION", "false");
+ vi.stubEnv("DISABLE_PASSWORD_REGISTRATION", "false");
+ vi.stubEnv("DISABLE_LOGIN_FORM", "true");
+
+ expect(describeAuth().passwordRegistration).toBe(false);
+ });
+
it("doesn't combine the OAuth and legacy GitHub credential pairs", () => {
vi.stubEnv("GITHUB_OAUTH_CLIENT_ID", "oauth-id");
vi.stubEnv("GITHUB_OAUTH_CLIENT_SECRET", "");
diff --git a/apps/api/src/admin/system/describe-auth.ts b/apps/api/src/admin/system/describe-auth.ts
index 0e8acaf68..718ae3e31 100644
--- a/apps/api/src/admin/system/describe-auth.ts
+++ b/apps/api/src/admin/system/describe-auth.ts
@@ -1,4 +1,4 @@
-import getSettings from "../../utils/get-settings";
+import { isSmtpConfigured } from "@kaneo/email";
import { resolveFileSecret } from "../../utils/file-secret";
import { getGithubSsoOAuthCredentials } from "../../utils/github-sso-env";
import { credentialSetStatus } from "./credential-set-status";
@@ -35,7 +35,10 @@ function customOAuthEndpoint() {
* leave here: never client ids, secrets, or provider URLs.
*/
export function describeAuth() {
- const settings = getSettings();
+ const disableLoginForm = process.env.DISABLE_LOGIN_FORM === "true";
+ const disableRegistration = process.env.DISABLE_REGISTRATION === "true";
+ const disablePasswordRegistration =
+ process.env.DISABLE_PASSWORD_REGISTRATION === "true";
const github = getGithubSsoOAuthCredentials();
const providers: AuthProvider[] = [
{
@@ -62,7 +65,7 @@ export function describeAuth() {
},
{
id: "custom",
- name: settings.customOAuthName ?? "OIDC",
+ name: env("CUSTOM_OAUTH_NAME") || "OIDC",
status: credentialSetStatus([
env("CUSTOM_OAUTH_CLIENT_ID"),
customOAuthSecret(),
@@ -72,17 +75,21 @@ export function describeAuth() {
];
return {
- passwordSignIn: !settings.disableLoginForm,
+ passwordSignIn: !disableLoginForm,
// Mirrors isEmailCodeSignInAvailable in auth.ts.
emailOtpSignIn:
- settings.hasSmtp &&
- !settings.disableEmailOtpSignIn &&
- !settings.disableLoginForm,
- registration: !settings.disableRegistration,
+ isSmtpConfigured() &&
+ process.env.DISABLE_EMAIL_OTP_SIGN_IN !== "true" &&
+ !disableLoginForm,
+ registration: !disableRegistration,
passwordRegistration:
- !settings.disableRegistration && !settings.disablePasswordRegistration,
- guestAccess: settings.hasGuestAccess,
- workspaceCreation: !settings.disableWorkspaceCreation,
+ !disableRegistration && !disablePasswordRegistration && !disableLoginForm,
+ guestAccess:
+ process.env.DISABLE_GUEST_ACCESS !== "true" &&
+ !disableRegistration &&
+ !disablePasswordRegistration &&
+ !disableLoginForm,
+ workspaceCreation: process.env.DISABLE_WORKSPACE_CREATION !== "true",
providers,
};
}
diff --git a/apps/api/src/admin/system/list-integration-providers.ts b/apps/api/src/admin/system/list-integration-providers.ts
index 47b76f660..f0a0cb5f9 100644
--- a/apps/api/src/admin/system/list-integration-providers.ts
+++ b/apps/api/src/admin/system/list-integration-providers.ts
@@ -1,11 +1,10 @@
import { count, eq } from "drizzle-orm";
-import db from "../../database";
import { integrationTable } from "../../database/schema";
import { integrationPlugins } from "../../plugins";
import { resolveGithubPrivateKey } from "../../plugins/github/utils/github-app";
import { credentialSetStatus } from "./credential-set-status";
import type { ServiceStatus } from "./service-status";
-import { withTimeout } from "./with-timeout";
+import { withDatabaseTimeout } from "./with-database-timeout";
type IntegrationProvider = {
type: string;
@@ -28,9 +27,9 @@ function instanceSetupStatus(type: string): ServiceStatus | null {
async function countConnectedProjects(timeoutMs: number) {
try {
- const rows = await withTimeout(
- () =>
- db
+ const rows = await withDatabaseTimeout(
+ async (tx) =>
+ tx
.select({ type: integrationTable.type, value: count() })
.from(integrationTable)
.where(eq(integrationTable.isActive, true))
diff --git a/apps/api/src/admin/system/probe-database.test.ts b/apps/api/src/admin/system/probe-database.test.ts
new file mode 100644
index 000000000..110606a38
--- /dev/null
+++ b/apps/api/src/admin/system/probe-database.test.ts
@@ -0,0 +1,43 @@
+import { PgDialect } from "drizzle-orm/pg-core";
+import type { SQL } from "drizzle-orm";
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+import { probeDatabase } from "./probe-database";
+
+const { execute } = vi.hoisted(() => ({
+ execute:
+ vi.fn<(query: SQL) => Promise<{ rows: Record<string, unknown>[] }>>(),
+}));
+
+vi.mock("../../database", () => ({
+ default: {
+ execute,
+ transaction: (work: (tx: { execute: typeof execute }) => unknown) =>
+ work({ execute }),
+ },
+}));
+
+describe("probeDatabase", () => {
+ afterEach(() => vi.useRealTimers());
+
+ it("shares one deadline between the version and migration queries", async () => {
+ vi.useFakeTimers();
+ execute.mockImplementation(async (query) => {
+ const text = new PgDialect().sqlToQuery(query).sql;
+ if (text.includes("server_version")) {
+ await new Promise((resolve) => setTimeout(resolve, 80));
+ return { rows: [{ version: "17" }] };
+ }
+ if (text.includes("count(*)")) return new Promise(() => {});
+ return { rows: [] };
+ });
+ let result: Awaited<ReturnType<typeof probeDatabase>> | undefined;
+ const pending = probeDatabase(100).then((value) => {
+ result = value;
+ });
+
+ await vi.advanceTimersByTimeAsync(100);
+
+ expect(result).toMatchObject({ status: "down", errorCode: "TIMEOUT" });
+ await pending;
+ });
+});
diff --git a/apps/api/src/admin/system/probe-database.ts b/apps/api/src/admin/system/probe-database.ts
index 2a3da646e..56daae94d 100644
--- a/apps/api/src/admin/system/probe-database.ts
+++ b/apps/api/src/admin/system/probe-database.ts
@@ -1,8 +1,7 @@
import { sql } from "drizzle-orm";
-import db from "../../database";
import { safeErrorCode } from "./safe-error-code";
import type { ServiceStatus } from "./service-status";
-import { withTimeout } from "./with-timeout";
+import { withDatabaseTimeout } from "./with-database-timeout";
type DatabaseProbe = {
status: ServiceStatus;
@@ -12,39 +11,32 @@ type DatabaseProbe = {
errorCode: string | null;
};
-async function countAppliedMigrations(timeoutMs: number) {
- try {
- const result = await withTimeout(
- () =>
- db.execute<{ applied: number }>(
- sql`select count(*)::int as applied from drizzle.__drizzle_migrations`,
- ),
- timeoutMs,
- );
- return result.rows[0]?.applied ?? null;
- } catch {
- return null;
- }
-}
-
export async function probeDatabase(timeoutMs: number): Promise<DatabaseProbe> {
const started = performance.now();
try {
- const result = await withTimeout(
- () =>
- db.execute<{ version: string }>(
- sql`select current_setting('server_version') as version`,
- ),
- timeoutMs,
- );
- const latencyMs = Math.round(performance.now() - started);
- return {
- status: "ok",
- serverVersion: result.rows[0]?.version ?? null,
- latencyMs,
- migrationsApplied: await countAppliedMigrations(timeoutMs),
- errorCode: null,
- };
+ return await withDatabaseTimeout(async (tx, signal) => {
+ const result = await tx.execute<{ version: string }>(
+ sql`select current_setting('server_version') as version`,
+ );
+ const latencyMs = Math.round(performance.now() - started);
+ signal.throwIfAborted();
+ let migrationsApplied: number | null = null;
+ try {
+ const migrations = await tx.execute<{ applied: number }>(
+ sql`select count(*)::int as applied from drizzle.__drizzle_migrations`,
+ );
+ migrationsApplied = migrations.rows[0]?.applied ?? null;
+ } catch {
+ // Migration metadata is optional; connectivity was already checked.
+ }
+ return {
+ status: "ok",
+ serverVersion: result.rows[0]?.version ?? null,
+ latencyMs,
+ migrationsApplied,
+ errorCode: null,
+ };
+ }, timeoutMs);
} catch (error) {
return {
status: "down",
diff --git a/apps/api/src/admin/system/probe-email.test.ts b/apps/api/src/admin/system/probe-email.test.ts
new file mode 100644
index 000000000..82677b137
--- /dev/null
+++ b/apps/api/src/admin/system/probe-email.test.ts
@@ -0,0 +1,23 @@
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+import { probeEmail } from "./probe-email";
+
+vi.mock("@kaneo/email", () => ({
+ verifySmtpConnection: () => new Promise(() => {}),
+}));
+
+describe("probeEmail", () => {
+ afterEach(() => vi.useRealTimers());
+
+ it("uses the probe deadline even when SMTP verification stalls", async () => {
+ vi.useFakeTimers();
+ let result: Awaited<ReturnType<typeof probeEmail>> | undefined;
+ const pending = probeEmail(100).then((value) => {
+ result = value;
+ });
+
+ await vi.advanceTimersByTimeAsync(100);
+
+ expect(result).toMatchObject({ status: "down", errorCode: "TIMEOUT" });
+ await pending;
+ });
+});
diff --git a/apps/api/src/admin/system/probe-email.ts b/apps/api/src/admin/system/probe-email.ts
index d70f1c7fe..2559b1119 100644
--- a/apps/api/src/admin/system/probe-email.ts
+++ b/apps/api/src/admin/system/probe-email.ts
@@ -14,7 +14,7 @@ export async function probeEmail(timeoutMs: number): Promise<EmailProbe> {
// nodemailer bounds each phase itself; the outer limit covers DNS.
const result = await withTimeout(
() => verifySmtpConnection(timeoutMs),
- timeoutMs + 500,
+ timeoutMs,
);
if (result.status === "not_configured") {
return { status: "not_configured", configured: false, errorCode: null };
diff --git a/apps/api/src/admin/system/probe-redis.test.ts b/apps/api/src/admin/system/probe-redis.test.ts
new file mode 100644
index 000000000..8b7f9c2fb
--- /dev/null
+++ b/apps/api/src/admin/system/probe-redis.test.ts
@@ -0,0 +1,26 @@
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+import { probeRedis } from "./probe-redis";
+
+const subscriber = vi.hoisted(() => ({ status: "ready" }));
+vi.mock("../../redis", () => ({
+ isRedisConfigured: () => true,
+ resolveRedisMode: () => ({ mode: "standalone" }),
+ getRedisPub: () => ({ ping: async () => "PONG" }),
+ getRedisSub: () => subscriber,
+}));
+
+describe("probeRedis", () => {
+ afterEach(() => {
+ subscriber.status = "ready";
+ });
+
+ it("reports a disconnected subscriber despite a healthy publisher", async () => {
+ subscriber.status = "reconnecting";
+ await expect(probeRedis(100)).resolves.toMatchObject({
+ status: "down",
+ errorCode: "SUBSCRIBER_NOT_READY",
+ });
+ subscriber.status = "ready";
+ await expect(probeRedis(100)).resolves.toMatchObject({ status: "ok" });
+ });
+});
diff --git a/apps/api/src/admin/system/probe-redis.ts b/apps/api/src/admin/system/probe-redis.ts
index c8380c736..0ee74c7c6 100644
--- a/apps/api/src/admin/system/probe-redis.ts
+++ b/apps/api/src/admin/system/probe-redis.ts
@@ -1,4 +1,9 @@
-import { getRedisPub, isRedisConfigured, resolveRedisMode } from "../../redis";
+import {
+ getRedisPub,
+ getRedisSub,
+ isRedisConfigured,
+ resolveRedisMode,
+} from "../../redis";
import { safeErrorCode } from "./safe-error-code";
import type { ServiceStatus } from "./service-status";
import { withTimeout } from "./with-timeout";
@@ -25,6 +30,9 @@ export async function probeRedis(timeoutMs: number): Promise<RedisProbe> {
try {
await withTimeout(() => getRedisPub().ping(), timeoutMs);
+ if (getRedisSub().status !== "ready") {
+ return { status: "down", mode, errorCode: "SUBSCRIBER_NOT_READY" };
+ }
return { status: "ok", mode, errorCode: null };
} catch (error) {
return { status: "down", mode, errorCode: safeErrorCode(error) };
diff --git a/apps/api/src/admin/system/with-database-timeout.ts b/apps/api/src/admin/system/with-database-timeout.ts
new file mode 100644
index 000000000..de256d36d
--- /dev/null
+++ b/apps/api/src/admin/system/with-database-timeout.ts
@@ -0,0 +1,30 @@
+import { sql } from "drizzle-orm";
+import db from "../../database";
+import { withTimeout } from "./with-timeout";
+
+type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];
+
+/** Bound the response and the SQL work, without changing the shared pool. */
+export function withDatabaseTimeout<T>(
+ work: (tx: Transaction, signal: AbortSignal) => Promise<T>,
+ timeoutMs: number,
+): Promise<T> {
+ const deadline = performance.now() + timeoutMs;
+ return withTimeout(
+ (signal) =>
+ db.transaction(async (tx) => {
+ // A queued pool checkout may finish after the response timed out.
+ signal.throwIfAborted();
+ const remainingMs = Math.max(
+ 1,
+ Math.ceil(deadline - performance.now()),
+ );
+ await tx.execute(
+ sql`select set_config('statement_timeout', ${String(remainingMs)}, true)`,
+ );
+ signal.throwIfAborted();
+ return work(tx, signal);
+ }),
+ timeoutMs,
+ );
+}
diff --git a/apps/docs/core/operations/administration.mdx b/apps/docs/core/operations/administration.mdx
index 8eefd85d7..5b7af92e3 100644
--- a/apps/docs/core/operations/administration.mdx
+++ b/apps/docs/core/operations/administration.mdx
@@ -83,7 +83,7 @@ Only instance administrators signed in with a session can read the audit log, in
Open **Settings → Administration → System** to check this instance and the services it relies on. The page checks again each time you open it or choose **Refresh**.
-- **Instance**: the Kaneo version, API uptime, PostgreSQL (version, applied migrations, response time), live updates (open WebSocket connections on this API instance), Redis, and S3-compatible file storage.
+- **Instance**: the Kaneo version, API uptime, PostgreSQL (version, applied migrations, response time), live updates (open WebSocket connections on this API instance), Redis publisher and subscriber connectivity, and S3-compatible file storage.
- **Email**: whether SMTP is configured and whether Kaneo can connect and sign in to the mail server. Nothing is sent by this check.
- **Sign-in**: which sign-in and registration options are on, and whether GitHub, Google, Discord, and your custom OAuth/OIDC provider are configured.
- **Integrations**: every integration provider, how many projects are connected to it, and whether the GitHub App is set up. Other providers are connected per project and need no instance settings.
@@ -103,7 +103,7 @@ When you run more than one API instance behind a load balancer, the checks and c
### Send a test email
-Choose **Send test email** to send a short test message to your own account's address. Kaneo can't send it to anyone else. If the mail server rejects it, you see the error category (for example `EAUTH 535` for a wrong password), and the API logs the same. You can send 5 test emails every 10 minutes.
+Choose **Send test email** to send a short test message to your own account's address. Kaneo can't send it to anyone else. If the mail server rejects it, you see the error category (for example `EAUTH 535` for a wrong password), and the API logs the same. You can send 5 test emails every 10 minutes. Test email connections, greetings, and idle sockets time out after 10 seconds.
The button is disabled until `SMTP_HOST` and `SMTP_FROM` are set. See [SMTP configuration](/core/installation/environment-variables#smtp-configuration) for the settings.
diff --git a/packages/email/src/send-email.tsx b/packages/email/src/send-email.tsx
index a1d3750d9..1cb6892d0 100644
--- a/packages/email/src/send-email.tsx
+++ b/packages/email/src/send-email.tsx
@@ -245,11 +245,21 @@ export const sendTestEmail = async (
const emailTemplate = await render(
TestEmail({ email: to, instance: instanceHost(), ...data }),
);
- await transporter.sendMail({
- from: process.env.SMTP_FROM,
- to,
- subject,
- html: emailTemplate,
+ const testTransport = nodemailer.createTransport({
+ ...getSmtpTransportOptions(),
+ connectionTimeout: 10_000,
+ greetingTimeout: 10_000,
+ socketTimeout: 10_000,
});
- return { success: true };
+ try {
+ await testTransport.sendMail({
+ from: process.env.SMTP_FROM,
+ to,
+ subject,
+ html: emailTemplate,
+ });
+ return { success: true };
+ } finally {
+ testTransport.close();
+ }
};
diff --git a/packages/email/src/send-test-email.test.ts b/packages/email/src/send-test-email.test.ts
new file mode 100644
index 000000000..9ded1e113
--- /dev/null
+++ b/packages/email/src/send-test-email.test.ts
@@ -0,0 +1,43 @@
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+import { sendTestEmail } from "./send-email";
+
+const smtp = vi.hoisted(() => ({
+ createTransport: vi.fn(),
+ sharedSend: vi.fn(),
+ testSend: vi.fn(),
+ close: vi.fn(),
+}));
+vi.mock("nodemailer", () => ({
+ createTransport: smtp.createTransport.mockImplementation((options) =>
+ options.connectionTimeout
+ ? { sendMail: smtp.testSend, close: smtp.close }
+ : { sendMail: smtp.sharedSend },
+ ),
+}));
+vi.mock("dotenv-mono", () => ({ config: () => {} }));
+
+describe("sendTestEmail", () => {
+ afterEach(() => vi.unstubAllEnvs());
+
+ it("bounds only the test transport and closes it after a stalled send fails", async () => {
+ vi.stubEnv("SMTP_HOST", "smtp.example.test");
+ vi.stubEnv("SMTP_FROM", "[email protected]");
+ smtp.testSend.mockRejectedValue(
+ Object.assign(new Error("timeout"), { code: "ETIMEDOUT" }),
+ );
+
+ await expect(
+ sendTestEmail("[email protected]", "Test", {}),
+ ).rejects.toMatchObject({ code: "ETIMEDOUT" });
+
+ expect(smtp.createTransport).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ connectionTimeout: 10_000,
+ greetingTimeout: 10_000,
+ socketTimeout: 10_000,
+ }),
+ );
+ expect(smtp.sharedSend).not.toHaveBeenCalled();
+ expect(smtp.close).toHaveBeenCalledOnce();
+ });
+});
diff --git a/tests/api-integration/admin-system-database-timeout.test.ts b/tests/api-integration/admin-system-database-timeout.test.ts
new file mode 100644
index 000000000..b66eee4ad
--- /dev/null
+++ b/tests/api-integration/admin-system-database-timeout.test.ts
@@ -0,0 +1,38 @@
+import { sql } from "drizzle-orm";
+import { describe, expect, it, vi } from "vite-plus/test";
+import db, { getDatabasePool } from "../../apps/api/src/database";
+import { listIntegrationProviders } from "../../apps/api/src/admin/system/list-integration-providers";
+import { probeDatabase } from "../../apps/api/src/admin/system/probe-database";
+import { ensureTestDatabaseMigrated } from "./helpers/database";
+
+describe("system database probe timeout", () => {
+ it("stops timed-out status and integration queries on PostgreSQL", async () => {
+ await ensureTestDatabaseMigrated();
+ const blocker = await getDatabasePool().connect();
+ try {
+ await blocker.query("begin");
+ await blocker.query(
+ "lock table drizzle.__drizzle_migrations, integration in access exclusive mode",
+ );
+
+ await Promise.all([probeDatabase(100), listIntegrationProviders(100)]);
+
+ await vi.waitFor(
+ async () => {
+ const result = await db.execute<{ active: number }>(sql`
+ select count(*)::int as active from pg_stat_activity
+ where datname = current_database()
+ and state = 'active' and pid <> pg_backend_pid()
+ and query ilike 'select%count(%'
+ and (query like '%__drizzle_migrations%' or query like '%"integration"%')
+ `);
+ expect(result.rows[0]?.active).toBe(0);
+ },
+ { timeout: 1000 },
+ );
+ } finally {
+ await blocker.query("rollback");
+ blocker.release();
+ }
+ });
+});
diff --git a/tests/api-integration/admin-system-status.test.ts b/tests/api-integration/admin-system-status.test.ts
index 2adc27fdf..52831073a 100644
--- a/tests/api-integration/admin-system-status.test.ts
+++ b/tests/api-integration/admin-system-status.test.ts
@@ -1,6 +1,7 @@
import { createHash, randomUUID } from "node:crypto";
import { readFileSync } from "node:fs";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import * as adminAudit from "../../apps/api/src/admin/audit/record-admin-action";
import db, { schema } from "../../apps/api/src/database";
import { mockAnonymousSession, mockAuthenticatedSession } from "./helpers/auth";
import { createInstanceAdmin } from "./helpers/admin/create-instance-admin";
@@ -30,6 +31,7 @@ vi.mock("@kaneo/email", async (importOriginal) => ({
vi.mock("../../apps/api/src/redis", async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
getRedisPub: () => ({ ping: redis.ping }),
+ getRedisSub: () => ({ status: "ready" }),
}));
beforeEach(async () => {
@@ -287,6 +289,27 @@ describe("admin system status", () => {
body.integrations.find((provider) => provider.type === "github")?.status,
).toBe("ok");
});
+ it("reports an unreadable OIDC secret as a warning without failing the page", async () => {
+ const admin = await createInstanceAdmin();
+ mockAuthenticatedSession(admin);
+
+ const response = await withEnv(
+ {
+ CUSTOM_OAUTH_CLIENT_ID: "oidc-client",
+ CUSTOM_OAUTH_CLIENT_SECRET: "",
+ CUSTOM_OAUTH_CLIENT_SECRET_FILE: "/missing-kaneo-oidc-secret",
+ CUSTOM_OAUTH_DISCOVERY_URL: "https://idp.example.test/discovery",
+ },
+ () => projectAccessApi()("/admin/system"),
+ );
+
+ expect(response.status).toBe(200);
+ const body = (await response.json()) as SystemStatus;
+ expect(
+ body.auth.providers.find((provider) => provider.id === "custom")?.status,
+ ).toBe("warning");
+ });
+
it("reports email sign-in codes only when the login form can use them", async () => {
smtp.configured.mockReturnValue(true);
const admin = await createInstanceAdmin();
@@ -361,6 +384,32 @@ describe("admin test email", () => {
expect(JSON.stringify(rows)).not.toContain("victim@");
});
+ it("reports an accepted email as sent when its audit insert fails", async () => {
+ smtp.configured.mockReturnValue(true);
+ const admin = await createInstanceAdmin();
+ mockAuthenticatedSession(admin);
+ vi.spyOn(adminAudit, "recordAdminAction").mockRejectedValue(
+ new Error("query parameters contain private-audit-value"),
+ );
+ const log = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ const response = await projectAccessApi()("/admin/system/test-email", {
+ method: "POST",
+ });
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ sent: true, to: admin.email });
+ expect(smtp.send).toHaveBeenCalledTimes(1);
+ expect(log).toHaveBeenCalledWith(
+ "Admin audit entry could not be recorded:",
+ {
+ action: "email.test_sent",
+ code: "UNKNOWN",
+ },
+ );
+ expect(JSON.stringify(log.mock.calls)).not.toContain("private-audit-value");
+ });
+
it("returns a safe error when the mail server rejects the message", async () => {
smtp.configured.mockReturnValue(true);
smtp.send.mockRejectedValue(