Skip to content

Build your personal knowledge base with Trilium Notes

fix(oauth): degrade to local logout when provider lacks end_session_endpoint

Elian Doran357b38d5d1ed
diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts
index 73840f0197..4800c8176f 100644
--- a/apps/server/src/app.ts
+++ b/apps/server/src/app.ts
@@ -113,8 +113,12 @@ export default async function buildApp() {
// Mount the OIDC middleware whenever OAuth is configured — not only once an account is enrolled —
// so the provider round-trip is available for the owner's first (enrollment) sign-in too.
- if (openID.isOpenIDConfigured())
- app.use(auth(openID.generateOAuthConfig()));
+ if (openID.isOpenIDConfigured()) {
+ // Probe the provider's discovery document once here so RP-Initiated Logout is only enabled when
+ // the provider supports it (otherwise POST /logout 500s); see isRpInitiatedLogoutSupported.
+ const endSessionSupported = await openID.isRpInitiatedLogoutSupported();
+ app.use(auth(openID.generateOAuthConfig(endSessionSupported)));
+ }
await assets.register(app);
routes.register(app);
diff --git a/apps/server/src/services/open_id.spec.ts b/apps/server/src/services/open_id.spec.ts
index 4b4dce28ba..df271be705 100644
--- a/apps/server/src/services/open_id.spec.ts
+++ b/apps/server/src/services/open_id.spec.ts
@@ -3,7 +3,7 @@ import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import config from "./config.js";
import openIDEncryption from "./encryption/open_id_encryption.js";
-import openID, { resolveOAuthIdentity } from "./open_id.js";
+import openID, { resolveOAuthIdentity, supportsRpInitiatedLogout } from "./open_id.js";
import sql from "./sql.js";
import sqlInit from "./sql_init.js";
@@ -185,6 +185,14 @@ describe("open_id", () => {
expect(openID.generateOAuthConfig().clientAuthMethod).toBe("client_secret_post");
});
+ it("enables RP-Initiated Logout (idpLogout) only when the provider supports it", () => {
+ setOauthConfig(true);
+ // Default off, and on only when discovery confirmed an end_session_endpoint at startup.
+ expect(openID.generateOAuthConfig().idpLogout).toBe(false);
+ expect(openID.generateOAuthConfig(false).idpLogout).toBe(false);
+ expect(openID.generateOAuthConfig(true).idpLogout).toBe(true);
+ });
+
it("returns the session unchanged when the DB is not initialized", async () => {
const cfg = buildConfig();
const spy = vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);
@@ -355,4 +363,64 @@ describe("open_id", () => {
expect(resolveOAuthIdentity({ name: 42, email: null }, undefined)).toEqual({ name: "", email: "" });
});
});
+
+ describe("supportsRpInitiatedLogout", () => {
+ it("is true only for a non-empty string end_session_endpoint", () => {
+ expect(supportsRpInitiatedLogout({ end_session_endpoint: "https://idp.example/logout" })).toBe(true);
+ expect(supportsRpInitiatedLogout({ end_session_endpoint: "" })).toBe(false);
+ // Provider without the endpoint (Google, Authelia) — the case that crashes idpLogout.
+ expect(supportsRpInitiatedLogout({ authorization_endpoint: "https://idp.example/auth" })).toBe(false);
+ // Non-string / non-object inputs are rejected rather than coerced.
+ expect(supportsRpInitiatedLogout({ end_session_endpoint: 42 })).toBe(false);
+ expect(supportsRpInitiatedLogout(null)).toBe(false);
+ expect(supportsRpInitiatedLogout(undefined)).toBe(false);
+ expect(supportsRpInitiatedLogout("not an object")).toBe(false);
+ });
+ });
+
+ describe("isRpInitiatedLogoutSupported", () => {
+ const wellKnownUrl = "https://issuer.example.com/.well-known/openid-configuration";
+
+ function mockFetch(impl: (url: string) => Partial<Response> | Promise<Partial<Response>>) {
+ return vi.spyOn(globalThis, "fetch").mockImplementation(
+ ((url: string) => Promise.resolve(impl(url))) as typeof fetch
+ );
+ }
+
+ it("fetches the issuer's discovery document and reflects end_session_endpoint", async () => {
+ setOauthConfig(true);
+ const fetchSpy = mockFetch(() => ({
+ ok: true,
+ json: () => Promise.resolve({ end_session_endpoint: "https://issuer.example.com/logout" })
+ }));
+
+ expect(await openID.isRpInitiatedLogoutSupported()).toBe(true);
+ expect(fetchSpy).toHaveBeenCalledWith(wellKnownUrl, expect.anything());
+ });
+
+ it("is false when discovery omits end_session_endpoint", async () => {
+ setOauthConfig(true);
+ mockFetch(() => ({ ok: true, json: () => Promise.resolve({}) }));
+ expect(await openID.isRpInitiatedLogoutSupported()).toBe(false);
+ });
+
+ it("fails closed (false) on a non-OK response or a thrown fetch", async () => {
+ setOauthConfig(true);
+
+ mockFetch(() => ({ ok: false, status: 404, json: () => Promise.resolve({}) }));
+ expect(await openID.isRpInitiatedLogoutSupported()).toBe(false);
+
+ vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("network down"));
+ expect(await openID.isRpInitiatedLogoutSupported()).toBe(false);
+ });
+
+ it("does not attempt discovery when no issuer is configured", async () => {
+ setOauthConfig(true);
+ mfa.oauthIssuerBaseUrl = "";
+ const fetchSpy = mockFetch(() => ({ ok: true, json: () => Promise.resolve({}) }));
+
+ expect(await openID.isRpInitiatedLogoutSupported()).toBe(false);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/apps/server/src/services/open_id.ts b/apps/server/src/services/open_id.ts
index b8d14578fb..bd70749b51 100644
--- a/apps/server/src/services/open_id.ts
+++ b/apps/server/src/services/open_id.ts
@@ -132,7 +132,7 @@ function deriveFaviconUrl(baseUrl: string) {
}
}
-function generateOAuthConfig() {
+function generateOAuthConfig(endSessionSupported = false) {
const authRoutes = {
callback: "/callback",
login: "/authenticate",
@@ -159,7 +159,12 @@ function generateOAuthConfig() {
prompt: "consent",
},
routes: authRoutes,
- idpLogout: true,
+ // Only enable RP-Initiated Logout when the provider actually advertises an end_session_endpoint
+ // (see isRpInitiatedLogoutSupported). With idpLogout on, express-openid-connect unconditionally
+ // builds a redirect to that endpoint at logout; providers without one (e.g. Google, Authelia)
+ // would otherwise crash POST /logout with a 500. When false, logout falls back to clearing the
+ // local session and redirecting to postLogoutRedirect.
+ idpLogout: endSessionSupported,
logoutParams,
afterCallback: async (req: Request, res: Response, session: Session) => {
if (!sqlInit.isDbInitialized()) return session;
@@ -243,10 +248,69 @@ export default {
clearSavedUser,
isTokenValid,
isUserSaved,
+ isRpInitiatedLogoutSupported,
};
const GOOGLE_ISSUER = "https://accounts.google.com";
+// Cap the startup discovery probe so a slow/unreachable provider can't stall server boot.
+const DISCOVERY_TIMEOUT_MS = 10_000;
+
+/**
+ * Probes the configured OIDC issuer's discovery document to decide whether RP-Initiated Logout is
+ * available, i.e. whether `idpLogout` can be safely enabled in {@link generateOAuthConfig}. The issuer
+ * is fixed in config.ini/env and only changes on restart, so this is resolved once at startup rather
+ * than per logout. Any fetch/parse failure is treated as "unsupported" so a transient network blip
+ * degrades to a working local logout rather than breaking it.
+ */
+async function isRpInitiatedLogoutSupported() {
+ const issuer = config.MultiFactorAuthentication.oauthIssuerBaseUrl.replace(/\/+$/, "");
+ if (!issuer) {
+ return false;
+ }
+
+ // The discovery document lives at `{issuer}/.well-known/openid-configuration` — appended to the full
+ // issuer (which may carry a path, e.g. Keycloak realms) rather than resolved against the origin root.
+ const metadataUrl = `${issuer}/.well-known/openid-configuration`;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), DISCOVERY_TIMEOUT_MS);
+ try {
+ const response = await fetch(metadataUrl, { signal: controller.signal });
+ if (!response.ok) {
+ getLog().info(`OAuth: discovery for ${issuer} returned HTTP ${response.status}; treating RP-Initiated Logout as unsupported.`);
+ return false;
+ }
+ const metadata: unknown = await response.json();
+ return supportsRpInitiatedLogout(metadata);
+ } catch (error) {
+ getLog().info(`OAuth: discovery fetch for ${issuer} failed, treating RP-Initiated Logout as unsupported. ${error instanceof Error ? error.message : error}`);
+ return false;
+ } finally {
+ clearTimeout(timeout);
+ }
+}
+
+/**
+ * The single field of the OIDC discovery document we consume. The full metadata is large and arrives as
+ * untrusted network JSON, so rather than pull in (and pin) openid-client's transitive `ServerMetadata`
+ * type for one property, we mirror just what we read and validate it at runtime.
+ */
+interface OidcDiscoveryMetadata {
+ end_session_endpoint?: string;
+}
+
+/**
+ * Pure predicate: does an OIDC discovery document advertise a usable `end_session_endpoint`? Extracted
+ * from the network probe so the support decision can be unit-tested without a live provider.
+ */
+export function supportsRpInitiatedLogout(metadata: unknown) {
+ if (typeof metadata !== "object" || metadata === null) {
+ return false;
+ }
+ const { end_session_endpoint } = metadata as OidcDiscoveryMetadata;
+ return typeof end_session_endpoint === "string" && end_session_endpoint.length > 0;
+}
+
/**
* Chooses the token-endpoint client authentication method based on the issuer.
*