From db17e0890e0246e5322d99b60f2821448a1ce5db Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Tue, 11 Aug 2026 15:19:14 -0700 Subject: [PATCH] fix: let deployments advertise offline_access so MCP sessions can refresh MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MCP clients were being kicked back to an interactive login on a short cycle, reporting "requires re-authorization (token expired)". Cause: /.well-known/oauth-protected-resource advertised only openid/profile/email plus the audience scope. A client requests exactly the scopes it finds there, and Authentik issues a refresh token only when offline_access is among them — so the client received an access token with nothing to renew it with. Once that token aged out, re-authenticating by hand was the only path forward. This is the same trap the audience scope already documents one comment further up: a scope missing from this document is a scope the client will never ask for, however the IdP is configured. Adds OIDC_OFFLINE_ACCESS (default false). Enabling it appends offline_access to the advertised scopes. Left opt-in rather than always-on because it is only half the fix — the IdP also needs an offline_access scope mapping on the provider, and advertising a scope the IdP doesn't offer risks an invalid_scope rejection that would break authentication outright. A deployment turns this on after configuring its IdP; README documents both halves and how to verify each. Co-Authored-By: Claude Opus 5 (1M context) --- .env.example | 9 +++ README.md | 42 ++++++++++++- .../oauth-protected-resource/route.test.ts | 63 +++++++++++++++++++ .../oauth-protected-resource/route.ts | 13 +++- apps/web/lib/env.ts | 15 +++++ 5 files changed, 140 insertions(+), 2 deletions(-) create mode 100644 apps/web/app/.well-known/oauth-protected-resource/route.test.ts diff --git a/.env.example b/.env.example index f60be24..d0cc0fc 100644 --- a/.env.example +++ b/.env.example @@ -53,6 +53,15 @@ OIDC_AUDIENCE=shared-memory # named the scope mapping something else. #OIDC_AUDIENCE_SCOPE=aud-shared-memory +# Advertise `offline_access` so MCP clients receive a REFRESH token and can +# renew silently. Without it the client only gets a short-lived access token +# and kicks the user back to an interactive login every time it expires. +# +# Enable this ONLY after adding an `offline_access` scope mapping to the MCP +# provider in your IdP — advertising a scope the IdP doesn't offer can fail +# the whole authorization request. See README -> "Keeping sessions alive". +#OIDC_OFFLINE_ACCESS=true + # ----------------------------------------------------------------------------- # Database (Postgres 16 + pgvector — pgvector/pgvector:pg16 image) # ----------------------------------------------------------------------------- diff --git a/README.md b/README.md index dac2f06..1cfc83f 100644 --- a/README.md +++ b/README.md @@ -291,9 +291,49 @@ tokens carry `aud: shared-memory` (or whatever value you chose). - **Client ID:** auto-generated → copy to `.env` as `OIDC_CLIENT_ID_MCP` - **Redirect URIs:** Claude Code prints the exact value when it first connects to the MCP endpoint. Paste it into Authentik then. -- **Scopes:** `openid`, `profile`, `email` +- **Scopes:** `openid`, `profile`, `email` (plus `offline_access` — see + **Keeping sessions alive** below) - **Signing Key:** same cert as the Web provider +#### Keeping sessions alive (`offline_access`) + +Without this, a connected MCP client gets an access token and **no refresh +token**. It cannot renew silently, so the moment the access token expires the +client reports `requires re-authorization (token expired)` and the user has to +log in again — repeatedly, on a short cycle. + +Two changes are required, and **neither works alone**: + +1. **In Authentik**, edit the `shared-memory-mcp` provider and add the built-in + `authentik default OAuth Mapping: offline_access` to its **Scopes**. You can + confirm it took by checking that `offline_access` appears in: + + ```bash + curl -s https://auth.example.com/application/o/shared-memory-mcp/.well-known/openid-configuration \ + | jq .scopes_supported + ``` + +2. **In `.env`**, set `OIDC_OFFLINE_ACCESS=true` and redeploy. + +Step 2 is needed because a client only requests the scopes advertised in our +`/.well-known/oauth-protected-resource` document — the same mechanism that +makes the `aud` scope mapping necessary below. Step 1 is needed because +Authentik only issues a refresh token when a configured mapping is requested. + +It is left opt-in rather than always-on because advertising a scope the IdP +doesn't offer risks an `invalid_scope` rejection that breaks authentication +outright. Configure the IdP first, then flip the flag. + +Verify afterwards with: + +```bash +curl -s https://memory.example.com/.well-known/oauth-protected-resource | jq .scopes_supported +``` + +If interactive login isn't practical at all — a headless container, CI — skip +OAuth and use a static bearer token instead (**D. Static bearer token**, below); +those default to a 90-day lifetime. + #### Setting the `aud` claim The MCP endpoint requires the access token's `aud` claim to equal diff --git a/apps/web/app/.well-known/oauth-protected-resource/route.test.ts b/apps/web/app/.well-known/oauth-protected-resource/route.test.ts new file mode 100644 index 0000000..f7dcd5e --- /dev/null +++ b/apps/web/app/.well-known/oauth-protected-resource/route.test.ts @@ -0,0 +1,63 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +/** + * The resource metadata document is the ONLY way an MCP client learns which + * scopes to request. Authentik evaluates a scope mapping only when the client + * asks for that scope by name — so a scope missing from this document is a + * scope the client will never request, no matter how the IdP is configured. + * + * That is exactly how `offline_access` came to be missing: without it the IdP + * issues an access token and no refresh token, so the client cannot renew + * silently and the user is forced to re-authenticate every time the access + * token expires. + */ + +async function fetchMetadata(): Promise<{ scopes_supported: string[] }> { + vi.resetModules(); + const { GET } = await import("@/app/.well-known/oauth-protected-resource/route"); + return (await GET().json()) as { scopes_supported: string[] }; +} + +afterEach(() => { + delete process.env.OIDC_OFFLINE_ACCESS; + delete process.env.OIDC_AUDIENCE_SCOPE; +}); + +describe("oauth-protected-resource metadata", () => { + test("omits offline_access by default, so deployments without the IdP mapping are unaffected", async () => { + const body = await fetchMetadata(); + + expect(body.scopes_supported).not.toContain("offline_access"); + }); + + test("advertises offline_access when the deployment opts in", async () => { + process.env.OIDC_OFFLINE_ACCESS = "true"; + + const body = await fetchMetadata(); + + expect(body.scopes_supported).toContain("offline_access"); + }); + + test("still advertises the audience scope when offline_access is enabled", async () => { + // Regression guard: the audience scope is what makes `aud` appear on the + // token at all. Dropping it would break authentication outright. + process.env.OIDC_OFFLINE_ACCESS = "true"; + + const body = await fetchMetadata(); + + expect(body.scopes_supported).toContain("aud-test-audience"); + expect(body.scopes_supported).toEqual( + expect.arrayContaining(["openid", "profile", "email"]), + ); + }); + + test("honours an explicit audience scope name alongside offline_access", async () => { + process.env.OIDC_OFFLINE_ACCESS = "true"; + process.env.OIDC_AUDIENCE_SCOPE = "custom-aud-scope"; + + const body = await fetchMetadata(); + + expect(body.scopes_supported).toContain("custom-aud-scope"); + expect(body.scopes_supported).toContain("offline_access"); + }); +}); diff --git a/apps/web/app/.well-known/oauth-protected-resource/route.ts b/apps/web/app/.well-known/oauth-protected-resource/route.ts index d6c9c33..097c85a 100644 --- a/apps/web/app/.well-known/oauth-protected-resource/route.ts +++ b/apps/web/app/.well-known/oauth-protected-resource/route.ts @@ -21,13 +21,24 @@ export function GET() { const audienceScope = env().OIDC_AUDIENCE_SCOPE ?? `aud-${env().OIDC_AUDIENCE}`; + // Same mechanism as the audience scope, different consequence: a client + // only requests `offline_access` if it sees the name here, and without + // that request the IdP returns no refresh token — so the client cannot + // renew and the user gets kicked back to an interactive login whenever + // the access token expires. + // + // Opt-in, because the IdP needs a matching scope mapping; advertising one + // it doesn't offer can fail the whole authorization request. + const scopes = ["openid", "profile", "email", audienceScope]; + if (env().OIDC_OFFLINE_ACCESS) scopes.push("offline_access"); + return NextResponse.json({ resource, // The MCP application's issuer, which is not necessarily the Web UI's — // see mcpIssuer(). Advertising the wrong one sends clients to a discovery // document whose tokens this endpoint will then reject on `iss`. authorization_servers: [mcpIssuer()], // as configured, slash and all - scopes_supported: ["openid", "profile", "email", audienceScope], + scopes_supported: scopes, bearer_methods_supported: ["header"], resource_documentation: `${resource}/`, }); diff --git a/apps/web/lib/env.ts b/apps/web/lib/env.ts index a9c7f02..ca5f6d1 100644 --- a/apps/web/lib/env.ts +++ b/apps/web/lib/env.ts @@ -52,6 +52,20 @@ const envSchema = z.object({ // Defaults to the `aud-` convention used in the README setup. OIDC_AUDIENCE_SCOPE: optional(z.string().min(1)), + // Advertise `offline_access` in the protected-resource metadata. + // + // Without it the IdP issues an access token and NO refresh token, so an + // MCP client cannot renew silently — it has to send the user back through + // an interactive login every time the access token expires. Turning this + // on is what makes long-lived sessions stop dropping out. + // + // Defaults OFF because it is only half the fix: the IdP must also have an + // `offline_access` scope mapping on the provider. Advertising a scope the + // IdP doesn't offer risks an `invalid_scope` rejection that would break + // authentication outright, so a deployment opts in only after configuring + // its IdP. See README -> "Keeping sessions alive". + OIDC_OFFLINE_ACCESS: Bool.optional().default(false), + // Database DATABASE_URL: z.string().url(), @@ -119,6 +133,7 @@ function buildPhaseStub(): Env { CLI_TOKEN_SECRET: "build-phase-secret-not-used-at-runtime-xxxxxxxx", PLUGIN_MARKETPLACE_NAME: "shared-memory", ALLOW_INSECURE_HTTP: false, + OIDC_OFFLINE_ACCESS: false, }; } -- 2.52.0