Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions docs/operations/runbooks/resume-oauth.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,21 @@ exact callbacks and use PKCE S256 with authorization-code and refresh grants.
The implementation retains the deployed MCP protocol versions and does not
claim CIMD or the newer MCP transport profile.

MCP discovery and its 401 challenge advertise `resume offline_access` so deployed
ChatGPT clients using MCP 2025-06-18 or earlier request renewal during explicit
consent. This is a compatibility exception to the newer guidance that
authorization-server-only scopes should not appear in protected-resource
metadata. `/api/resume` discovery and challenges, and 403 scope challenges,
continue to request only `resume`.

Existing grants without renewal need the assistant to refresh discovery and
reauthorize with explicit consent to `resume offline_access`. The current provider
stores both configured scopes for dynamic clients even when registration
requests only `resume`; this does not grant consent or issue a refresh token by
itself. No saved client's scopes are widened and no refresh grant is issued
silently. Verify the assistant's actual consent and a call after the five-minute
access-token expiry before claiming renewal works.

Access JWTs expire in five minutes. Refresh lasts at most seven days while the
linked browser session stays active. Verification checks signature, type,
issuer, audience, expiry, scope, DPoP and current session/client/consent records.
Expand Down
21 changes: 21 additions & 0 deletions src/__tests__/resume-access.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,27 @@ it('requires an ordinary signed-in session to issue capabilities', async () => {
expect(await createResumeApiAccess()).toMatchObject({ ok: false });
});

it('requests renewal only for MCP authentication and keeps missing resume scope distinct', async () => {
state.requestHeaders = new Headers();
const action = vi.fn(async () => new Response());
for (const path of ['/api/resume', '/api/mcp']) {
const unauthenticated = await withResumeAccess(request(undefined, path), action, true);
expect(unauthenticated.status).toBe(401);
expect(unauthenticated.headers.get('www-authenticate')).toContain(
`scope="${path === '/api/mcp' ? 'resume offline_access' : 'resume'}"`
);
const oauth = await import('@/lib/resume-oauth');
vi.spyOn(oauth, 'verifyResumeOAuth').mockRejectedValueOnce(
Object.assign(new Error('Missing scope'), { name: 'ResumeOAuthScopeError' })
);
const forbidden = await withResumeAccess(request('synthetic-oauth-token', path), action);
expect(forbidden.status).toBe(403);
expect(forbidden.headers.get('www-authenticate')).toContain('scope="resume"');
expect(forbidden.headers.get('www-authenticate')).toContain('error="insufficient_scope"');
}
expect(action).not.toHaveBeenCalled();
});

it('omits fallback_reason on an AI-generated API response', async () => {
state.generate.mockResolvedValue({
object: {
Expand Down
162 changes: 157 additions & 5 deletions src/__tests__/resume-oauth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { getAuth } from '@/lib/auth';
import { db } from '@/lib/db';
import { getResumeApiUserId, withResumeAccess } from '@/lib/resume-access';
import { getResumeOAuthRequest, consentResumeOAuth } from '@/lib/actions/resume-oauth-actions';
import { GET as discovery } from '@/app/.well-known/[...metadata]/route';
const state = vi.hoisted(() => ({ headers: new Headers() }));
const origin = 'http://localhost:4366';
const secret = 'oauth-local-synthetic-test-secret-20261008';
Expand Down Expand Up @@ -115,7 +116,7 @@ beforeAll(() => {
});
afterAll(() => sql.close());
it('advertises resource-bound OAuth endpoints through real provider discovery', async () => {
const response = await getAuth().handler(
const response = await discovery(
new Request(`${origin}/.well-known/oauth-authorization-server/api/auth`)
);
expect(response.status).toBe(200);
Expand All @@ -124,11 +125,160 @@ it('advertises resource-bound OAuth endpoints through real provider discovery',
expect(metadata.registration_endpoint).toBe(`${origin}/api/auth/oauth2/register`);
expect(metadata.code_challenge_methods_supported).toEqual(['S256']);
expect(metadata.grant_types_supported).not.toContain('client_credentials');
const protectedResponse = await getAuth().handler(
new Request(`${origin}/.well-known/oauth-protected-resource/api/mcp`)
for (const suffix of ['', '/api/mcp']) {
const request = new Request(`${origin}/.well-known/oauth-protected-resource${suffix}`);
const provider = await getAuth().handler(request.clone());
const protectedResponse = await discovery(request);
expect(protectedResponse.status).toBe(provider.status);
expect([...protectedResponse.headers]).toEqual([...provider.headers]);
expect(await protectedResponse.json()).toEqual({
...(await provider.json()),
scopes_supported: ['resume', 'offline_access'],
});
}
const resume = await discovery(
new Request(`${origin}/.well-known/oauth-protected-resource/api/resume`)
);
expect(await protectedResponse.json()).toMatchObject({ resource, scopes_supported: ['resume'] });
expect(await resume.json()).toMatchObject({ scopes_supported: ['resume'] });
});
it('preserves provider errors and authorization-server metadata without rewriting them', async () => {
const handler = vi.spyOn(getAuth(), 'handler');
try {
for (const status of [302, 400, 500]) {
const response = new Response('Provider response', {
status,
headers: { 'x-provider': 'retained' },
});
handler.mockResolvedValueOnce(response);
expect(
await discovery(new Request(`${origin}/.well-known/oauth-protected-resource/api/mcp`))
).toBe(response);
}
const response = Response.json({ scopes_supported: ['resume', 'offline_access'] });
handler.mockResolvedValueOnce(response);
expect(
await discovery(new Request(`${origin}/.well-known/oauth-authorization-server/api/auth`))
).toBe(response);
} finally {
handler.mockRestore();
}
});
it('adds renewal guidance when provider metadata omits optional supported scopes', async () => {
const handler = vi.spyOn(getAuth(), 'handler');
const metadata = { resource, authorization_servers: [`${origin}/api/auth`] };
try {
const provider = Response.json(metadata, {
status: 203,
statusText: 'Non-Authoritative Information',
headers: { 'cache-control': 'no-store', 'x-provider': 'retained' },
});
handler.mockResolvedValueOnce(provider);
const response = await discovery(
new Request(`${origin}/.well-known/oauth-protected-resource/api/mcp`)
);
expect(response.status).toBe(provider.status);
expect(response.statusText).toBe(provider.statusText);
expect([...response.headers]).toEqual([...provider.headers]);
expect(await response.json()).toEqual({
...metadata,
scopes_supported: ['offline_access'],
});
} finally {
handler.mockRestore();
}
});
it.each(['', '/api/mcp'])('preserves bodyless provider HEAD discovery for %s', async (suffix) => {
const request = new Request(`${origin}/.well-known/oauth-protected-resource${suffix}`, {
method: 'HEAD',
});
const provider = await getAuth().handler(request.clone());
const response = await discovery(request);
expect(response.status).toBe(provider.status);
expect([...response.headers]).toEqual([...provider.headers]);
expect(await response.text()).toBe('');
});
it.each(['discovery', 'challenge', 'resume-only registration'])(
'renews an expired owner grant using scopes from app %s',
async (source) => {
let scope: string;
if (source === 'discovery') {
const response = await discovery(
new Request(`${origin}/.well-known/oauth-protected-resource/api/mcp`)
);
scope = (await response.json()).scopes_supported.join(' ');
} else {
const response = await withResumeAccess(
new Request(resource),
async () => new Response(),
true
);
expect(response.status).toBe(401);
scope = response.headers.get('www-authenticate')!.match(/scope="([^"]+)"/)![1];
}
const registration = await send('/oauth2/register', {
client_name: `Synthetic ${source} Assistant`,
redirect_uris: [redirect],
token_endpoint_auth_method: 'none',
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
scope: source === 'resume-only registration' ? 'resume' : scope,
});
expect(registration.status).toBe(201);
const client = await registration.json();
if (source === 'resume-only registration') {
// The maintained provider stores all registration scopes even when DCR requests fewer.
expect(client.scope.split(' ')).toEqual(['offline_access', 'resume']);
expect(
JSON.parse(
sql.prepare('SELECT scopes FROM oauthClient WHERE clientId=?').get(client.client_id)
.scopes as string
)
).toEqual(['offline_access', 'resume']);
expect(
sql.prepare('SELECT COUNT(*) n FROM oauthConsent WHERE clientId=?').get(client.client_id).n
).toBe(0);
}
const signedQuery = await consentQuery(client.client_id, true, { scope });
expect(await getResumeOAuthRequest(signedQuery)).toMatchObject({
ok: true,
scopes: ['resume', 'offline_access'],
signed_in: true,
});
const accepted = await consentResumeOAuth(signedQuery, true);
expect(accepted.ok).toBe(true);
if (!accepted.ok) throw new Error(accepted.error);
const issued = await token({
grant_type: 'authorization_code',
client_id: client.client_id,
redirect_uri: redirect,
code_verifier: verifier,
resource,
code: new URL(accepted.redirect_uri).searchParams.get('code')!,
});
expect(issued.status).toBe(200);
const tokens = await issued.json();
expect(tokens.refresh_token).toBeTruthy();
expect(tokens.expires_in).toBe(300);
expect(await (await invoke(tokens.access_token)).json()).toEqual({ user: 'oauth-owner' });
vi.useFakeTimers({ toFake: ['Date'] });
try {
vi.setSystemTime(Date.now() + 301_000);
expect((await invoke(tokens.access_token)).status).toBe(401);
const renewed = await token({
grant_type: 'refresh_token',
client_id: client.client_id,
refresh_token: tokens.refresh_token,
resource,
});
expect(renewed.status).toBe(200);
expect(await (await invoke((await renewed.json()).access_token)).json()).toEqual({
user: 'oauth-owner',
});
} finally {
vi.useRealTimers();
}
}
);
it('qualifies registration, consent, PKCE, replay resistance, owner identity, refresh and immediate session revocation', async () => {
const registration = await send('/oauth2/register', {
client_name: 'Synthetic Assistant',
Expand Down Expand Up @@ -157,7 +307,9 @@ it('qualifies registration, consent, PKCE, replay resistance, owner identity, re
const denied = await consentResumeOAuth(signedQuery, false);
expect(denied.ok).toBe(true);
if (denied.ok) expect(denied.redirect_uri).toContain('access_denied');
expect(sql.prepare('SELECT COUNT(*) n FROM oauthConsent').get().n).toBe(0);
expect(
sql.prepare('SELECT COUNT(*) n FROM oauthConsent WHERE clientId=?').get(client.client_id).n
).toBe(0);
const accepted = await consentResumeOAuth(signedQuery, true);
expect(accepted.ok).toBe(true);
if (!accepted.ok) throw new Error(accepted.error);
Expand Down
23 changes: 22 additions & 1 deletion src/app/.well-known/[...metadata]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,26 @@ export async function GET(request: Request) {
].includes(path)
)
return new Response('Not found', { status: 404 });
return getAuth().handler(request);
const response = await getAuth().handler(request);
if (
request.method === 'GET' &&
response.ok &&
[
'/.well-known/oauth-protected-resource',
'/.well-known/oauth-protected-resource/api/mcp',
].includes(path)
) {
const metadata = await response.json();
const scopes = metadata.scopes_supported ?? [];
return Response.json(
{
...metadata,
scopes_supported: scopes.includes('offline_access')
? scopes
: [...scopes, 'offline_access'],
},
response
);
}
return response;
}
2 changes: 1 addition & 1 deletion src/lib/resume-access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ export async function withResumeAccess(
status: insufficientScope ? 403 : 401,
headers: {
'Cache-Control': 'private, no-store',
'WWW-Authenticate': `Bearer resource_metadata="${new URL(request.url).origin}/.well-known/oauth-protected-resource${path}", scope="resume", error="${insufficientScope ? 'insufficient_scope' : 'invalid_token'}"`,
'WWW-Authenticate': `Bearer resource_metadata="${new URL(request.url).origin}/.well-known/oauth-protected-resource${path}", scope="${path === '/api/mcp' && !insufficientScope ? 'resume offline_access' : 'resume'}", error="${insufficientScope ? 'insufficient_scope' : 'invalid_token'}"`,
},
}
);
Expand Down
Loading