Skip to content

Build your personal knowledge base with Trilium Notes

fix(oauth): only answer the provider round-trip with a redirect

Elian Doran0a3d3106077c
diff --git a/apps/server/spec/sync/sync-protocol.spec.ts b/apps/server/spec/sync/sync-protocol.spec.ts
index 8096fbc956..b033b6f3f5 100644
--- a/apps/server/spec/sync/sync-protocol.spec.ts
+++ b/apps/server/spec/sync/sync-protocol.spec.ts
@@ -51,12 +51,14 @@ describe("sync protocol with built-in OIDC enabled (#10548)", () => {
});
it("engages the OIDC middleware (sanity check that this suite tests what it claims)", async () => {
- // /authenticate only exists inside the express-openid-connect router. When the
- // reactive middleware is active it handles the route (and errors with 500 because
- // the issuer above is unreachable); were OAuth unconfigured, the request would fall
- // through to the 404 handler and this suite would silently test nothing.
+ // /authenticate only exists inside the express-openid-connect router. When the reactive
+ // middleware is active it handles the route; the issuer above is unreachable, so the round-trip
+ // fails and is answered with a redirect back to the app root carrying the failure on the session
+ // (see failRoundTrip). Were OAuth unconfigured, the request would instead fall through to the
+ // 404 handler and this suite would silently test nothing — which is what this asserts.
const res = await supertest(app).get("/authenticate");
- expect(res.status).toBe(500);
+ expect(res.status).toBe(302);
+ expect(res.headers.location).toBe("/");
});
it("performs the full desktop sync round-trip: login, push, pull, finished", async () => {
diff --git a/apps/server/src/services/open_id.spec.ts b/apps/server/src/services/open_id.spec.ts
index 75af5c03c4..e52f083261 100644
--- a/apps/server/src/services/open_id.spec.ts
+++ b/apps/server/src/services/open_id.spec.ts
@@ -548,11 +548,13 @@ describe("createReactiveOidcMiddleware", () => {
};
}
- async function run(middleware: RequestHandler) {
+ async function run(middleware: RequestHandler, url = "/authenticate") {
const next = vi.fn() as unknown as NextFunction;
// A failed round-trip redirects back to the app root and flags the session, so both have to be
- // present for the middleware to drive them.
- const req = { method: "GET", url: "/authenticate", session: {} } as ExpressRequest;
+ // present for the middleware to drive them. `path` mirrors Express's query-stripped getter,
+ // which decides whether a failure is answered with a redirect or handed to the error chain.
+ const [path] = url.split("?");
+ const req = { method: "GET", url, path, session: {} } as ExpressRequest;
const res = { headersSent: false, redirect: vi.fn() } as unknown as ExpressResponse;
await middleware(req, res, next);
return { next, req, res, redirect: res.redirect as unknown as ReturnType<typeof vi.fn> };
@@ -716,6 +718,50 @@ describe("createReactiveOidcMiddleware", () => {
expect(req.session.ssoConnectionFailed).toBeTruthy();
});
+ // This middleware is mounted ahead of every route, so a failed lazy init is reached by ordinary
+ // traffic too. Redirecting those would hand an XHR a 302 to HTML where it expects JSON, so only the
+ // provider round-trip — a full-page navigation — is answered that way.
+ it("hands non-navigation requests to the error chain instead of redirecting", async () => {
+ const t = setup();
+ t.setConfigured(true);
+ const failure = new Error("fetch failed");
+ t.oidcHandler.mockImplementation(((_req, _res, next) => next(failure)) as RequestHandler);
+
+ const { req, redirect, next } = await run(t.middleware, "/api/notes/root");
+
+ expect(redirect).not.toHaveBeenCalled();
+ expect(next).toHaveBeenCalledWith(failure);
+ expect(req.session.ssoConnectionFailed).toBeUndefined();
+ });
+
+ // The redirect target is itself covered by this middleware. A transient failure self-heals (the init
+ // promise is reset, so the next request retries), but a persistent one — a malformed oauthBaseUrl
+ // that auth() rejects every time — would bounce "/" to "/" until the browser gave up, turning a JSON
+ // error that named the bad config into an opaque ERR_TOO_MANY_REDIRECTS.
+ it("does not redirect the app root to itself", async () => {
+ const t = setup();
+ t.setConfigured(true);
+ const failure = new Error("invalid config");
+ t.isRpInitiatedLogoutSupported.mockRejectedValue(failure);
+
+ const { redirect, next } = await run(t.middleware, "/");
+
+ expect(redirect).not.toHaveBeenCalled();
+ expect(next).toHaveBeenCalledWith(failure);
+ });
+
+ // The callback carries ?code=&state=, so the guard has to compare against the query-stripped path.
+ it("still redirects the callback when it arrives with query parameters", async () => {
+ const t = setup();
+ t.setConfigured(true);
+ t.oidcHandler.mockImplementation(((_req, _res, next) => next(new Error("token exchange failed"))) as RequestHandler);
+
+ const { req, redirect } = await run(t.middleware, "/callback?code=abc&state=xyz");
+
+ expect(redirect).toHaveBeenCalledWith("/");
+ expect(req.session.ssoConnectionFailed).toContain("token exchange failed");
+ });
+
// Once the library has begun answering (e.g. it already started the redirect to the provider), we
// can't redirect on top of it — the error has to go to Express instead of causing a double response.
it("defers to the error chain when the response has already started", async () => {
diff --git a/apps/server/src/services/open_id.ts b/apps/server/src/services/open_id.ts
index 7b9481c3ce..0101fa7ccc 100644
--- a/apps/server/src/services/open_id.ts
+++ b/apps/server/src/services/open_id.ts
@@ -133,14 +133,18 @@ function deriveFaviconUrl(baseUrl: string) {
}
}
-function generateOAuthConfig(endSessionSupported = false) {
- const authRoutes = {
- callback: "/callback",
- login: "/authenticate",
- postLogoutRedirect: "/login",
- logout: "/logout",
- };
+/**
+ * The routes express-openid-connect owns. Hoisted out of {@link generateOAuthConfig} so
+ * {@link OIDC_NAVIGATION_PATHS} is derived from the same source rather than repeating the literals.
+ */
+const OIDC_ROUTES = {
+ callback: "/callback",
+ login: "/authenticate",
+ postLogoutRedirect: "/login",
+ logout: "/logout",
+} as const;
+function generateOAuthConfig(endSessionSupported = false) {
const logoutParams = {
};
@@ -157,7 +161,7 @@ function generateOAuthConfig(endSessionSupported = false) {
response_type: "code",
scope: "openid profile email",
},
- routes: authRoutes,
+ routes: { ...OIDC_ROUTES },
// 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)
@@ -355,12 +359,37 @@ function failRoundTrip(req: Request, res: Response, next: NextFunction, error: u
return next(error);
}
+ // Redirecting only makes sense for the provider round-trip itself, which is a full-page navigation.
+ // This middleware is mounted ahead of every route, so without this guard two things break:
+ //
+ // - An `/api/*` XHR caught by a failed lazy init would receive a 302 to HTML where it expects JSON.
+ // - A failure on `/` would redirect `/` to `/`. Transient failures self-heal (the init promise is
+ // reset, so the next request retries), but a persistent one — a malformed `oauthBaseUrl` that
+ // `auth()` rejects on every build, say — would loop the browser until it gave up, replacing a
+ // JSON error that named the bad config with an opaque ERR_TOO_MANY_REDIRECTS.
+ //
+ // Everything else keeps the old behaviour and goes to the generic handler, which answers JSON.
+ if (!OIDC_NAVIGATION_PATHS.has(req.path)) {
+ return next(error);
+ }
+
// Bounded: this rides in the session store until the next bootstrap consumes it, and a deep cause
// chain would otherwise be unbounded.
req.session.ssoConnectionFailed = detail.slice(0, MAX_CONNECTION_FAILURE_DETAIL_LENGTH);
return res.redirect("/");
}
+/**
+ * The subset of {@link OIDC_ROUTES} the user reaches by navigating, and therefore the only paths where
+ * answering a failure with a redirect (rather than an error) is right. `postLogoutRedirect` is excluded:
+ * it is where the library sends the browser afterwards, not a route it handles.
+ */
+const OIDC_NAVIGATION_PATHS = new Set<string>([
+ OIDC_ROUTES.login,
+ OIDC_ROUTES.callback,
+ OIDC_ROUTES.logout
+]);
+
/** Upper bound on the technical detail carried to the client; enough for a full cause chain. */
const MAX_CONNECTION_FAILURE_DETAIL_LENGTH = 300;