Skip to content

Commit 6846513

Browse files
committed
wip(plugin-auth): the MCP door refuses a token whose client is disabled
Claude-Session: https://claude.ai/code/session_01QUs3BuLtRmSkjNPDYrwA9T Co-authored-by: Claude <noreply@anthropic.com>
1 parent 158cc2a commit 6846513

4 files changed

Lines changed: 139 additions & 25 deletions

File tree

‎packages/plugins/plugin-auth/src/auth-manager-mcp-access-token.ts‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,10 @@
6363
* unedited, now also answering the token's `iat`) and
6464
* {@link verifyMcpAccessToken}, which adds the consent read
6565
* (`mcp-token-revocation.ts` `mcpConsentAdmits`) through better-auth's own
66-
* storage adapter, reached as `getAuthContext`. `/oauth2/revoke` verifies
67-
* through the claims half alone, because it must still find the grant of a
68-
* token whose consent is already gone.
66+
* storage adapter, reached as `getAuthContext`. The same read refuses a token
67+
* whose client is disabled (objectstack-ai/cloud#3820, card 2).
68+
* `/oauth2/revoke` verifies through the claims half alone, because it must
69+
* still find the grant of a token whose consent is already gone.
6970
*/
7071

7172
import type { JSONWebKeySet } from 'jose';
@@ -202,9 +203,10 @@ export async function verifyMcpAccessTokenClaims(
202203

203204
/**
204205
* The body of `AuthManager#verifyMcpAccessToken`; the method's docblock there
205-
* is its contract. {@link verifyMcpAccessTokenClaims}, then the consent read:
206-
* the token's grant must still stand (`mcpConsentAdmits`), read through
207-
* better-auth's storage adapter, the one the provider writes consents through.
206+
* is its contract. {@link verifyMcpAccessTokenClaims}, then the grant read:
207+
* the token's client must still be enabled and its grant must still stand
208+
* (`mcpConsentAdmits`), read through better-auth's storage adapter, the one
209+
* the provider writes clients and consents through.
208210
* The read is keyed by `azp`, the client the provider mints into every
209211
* access token, so a token without one is refused. A store error, or no
210212
* adapter at all, is a refusal: fail closed.

‎packages/plugins/plugin-auth/src/auth-manager.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4654,6 +4654,10 @@ export class AuthManager {
46544654
* the Console's withdraw (`authorized-clients-withdraw.ts`) revokes the same
46554655
* grant the same way. A server-only
46564656
* `skip_consent` client has no consent row and is admitted without one.
4657+
* The same read refuses a token whose client is disabled, or whose client
4658+
* row is gone (objectstack-ai/cloud#3820, card 2): disabling a client
4659+
* refuses its outstanding tokens on their next call, as the provider
4660+
* already refuses it new ones, and enabling it again serves them again.
46574661
*
46584662
* The caller (runtime dispatcher) maps the returned principal through
46594663
* `resolveAuthzContext` — the single shared authorization resolver — so

‎packages/plugins/plugin-auth/src/mcp-token-revocation.test.ts‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -530,3 +530,85 @@ describe('a grant is revoked in its own organization only', () => {
530530
expect((await r.refresh(clientId, raced!.body.refresh_token)).status).toBe(400);
531531
}, 60_000);
532532
});
533+
534+
describe('[objectstack-ai/cloud#3820, card 2] a disabled client\'s tokens are refused on their next call', () => {
535+
/**
536+
* The write `POST /auth/admin/oauth2/toggle-disabled` makes (`auth-plugin.ts`):
537+
* the `disabled` column of the client's `sys_oauth_application` row, in the
538+
* system context. The route's own gate and the `/mcp` door's 401 are pinned
539+
* over HTTP in `@objectstack/dogfood` `authorized-client-withdraw.dogfood.test.ts`.
540+
*/
541+
async function setDisabled(r: Awaited<ReturnType<typeof rig>>, clientId: string, disabled: boolean): Promise<void> {
542+
const [app] = (await r.rowsAtRest('sys_oauth_application')).filter((row) => row.client_id === clientId);
543+
expect(app, `the client ${clientId} has a row`).toBeDefined();
544+
await (r.engine as any).update('sys_oauth_application', { id: app!.id, disabled }, SYS);
545+
}
546+
547+
it('⭐ a token minted before the disable is refused; the provider refuses its refresh; enabling the client again serves the same grant', async () => {
548+
const r = await rig();
549+
const { clientId, refresh_token, access_token } = await r.connect();
550+
expect(await r.manager.verifyMcpAccessToken(access_token), 'the control: the bearer verifies before the disable')
551+
.toMatchObject({ clientId });
552+
553+
await setDisabled(r, clientId, true);
554+
555+
expect(await r.manager.verifyMcpAccessToken(access_token), 'the bearer minted before the disable is refused').toBeNull();
556+
const refused = await r.refresh(clientId, refresh_token);
557+
expect(refused, 'the provider refuses the disabled client a new token').toMatchObject({
558+
status: 400, body: { error: 'invalid_client', error_description: 'client is disabled' },
559+
});
560+
// A pause, not an end: the grant itself is untouched.
561+
expect(await r.rowsAtRest('sys_oauth_consent')).toHaveLength(1);
562+
expect(await r.rowsAtRest('sys_oauth_refresh_token')).toHaveLength(1);
563+
564+
await setDisabled(r, clientId, false);
565+
566+
expect(await r.manager.verifyMcpAccessToken(access_token), 'enabled again, the same grant is served').toMatchObject({ clientId });
567+
const renewed = await r.refresh(clientId, refresh_token);
568+
expect(renewed.status, JSON.stringify(renewed.body)).toBe(200);
569+
expect(await r.manager.verifyMcpAccessToken(renewed.body.access_token)).toMatchObject({ clientId });
570+
}, 60_000);
571+
572+
it('a disabled `skip_consent` client is refused too: the client is read before the consent', async () => {
573+
const r = await rig();
574+
const clientId = await r.registerClient();
575+
const [app] = (await r.rowsAtRest('sys_oauth_application')).filter((row) => row.client_id === clientId);
576+
await (r.engine as any).update('sys_oauth_application', { id: app!.id, skip_consent: true }, SYS);
577+
const { code } = await r.authorize(clientId, await r.signUp('ops@acme.example.com'));
578+
const { access_token } = await r.exchange(clientId, code);
579+
expect(await r.manager.verifyMcpAccessToken(access_token), 'the control').toMatchObject({ clientId });
580+
581+
await setDisabled(r, clientId, true);
582+
583+
expect(await r.manager.verifyMcpAccessToken(access_token)).toBeNull();
584+
}, 60_000);
585+
586+
it('a token whose client row is gone is refused', async () => {
587+
const r = await rig();
588+
const { clientId, access_token } = await r.connect();
589+
const [app] = (await r.rowsAtRest('sys_oauth_application')).filter((row) => row.client_id === clientId);
590+
591+
await (r.engine as any).delete('sys_oauth_application', { where: { id: app!.id }, ...SYS });
592+
593+
expect(await r.rowsAtRest('sys_oauth_application')).toEqual([]);
594+
expect(await r.rowsAtRest('sys_oauth_consent'), 'the consent alone does not admit the token').toHaveLength(1);
595+
expect(await r.manager.verifyMcpAccessToken(access_token)).toBeNull();
596+
}, 60_000);
597+
598+
it('a store error in the client read refuses the bearer (fail closed)', async () => {
599+
const r = await rig();
600+
const { clientId, access_token } = await r.connect();
601+
const failOnClient = (method: 'find' | 'findOne') => {
602+
const original = (r.driver as any)[method].bind(r.driver);
603+
return vi.spyOn(r.driver as any, method).mockImplementation(async (object: unknown, ...rest: unknown[]) => {
604+
if (object === 'sys_oauth_application') throw new Error('client store unreachable');
605+
return original(object, ...rest);
606+
});
607+
};
608+
const failing = [failOnClient('find'), failOnClient('findOne')];
609+
610+
expect(await r.manager.verifyMcpAccessToken(access_token)).toBeNull();
611+
for (const spy of failing) spy.mockRestore();
612+
expect(await r.manager.verifyMcpAccessToken(access_token), 'the control: the store answers again').toMatchObject({ clientId });
613+
}, 60_000);
614+
});

‎packages/plugins/plugin-auth/src/mcp-token-revocation.ts‎

Lines changed: 45 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,11 @@
1717
* - **The MCP door reads it on every request** ({@link mcpConsentAdmits},
1818
* called by `verifyMcpAccessToken`). A token whose consent is gone, or
1919
* whose consent was created after the token was issued (revoked, then
20-
* granted again), verifies as no principal. A store error refuses too.
21-
* `@objectstack/spec` `IAuthService.verifyMcpAccessToken` already says
22-
* this: a falsy value when the token is revoked, and callers fail CLOSED.
20+
* granted again), verifies as no principal, and so does a token whose
21+
* client is disabled (objectstack-ai/cloud#3820, card 2). A store error
22+
* refuses too. `@objectstack/spec` `IAuthService.verifyMcpAccessToken`
23+
* already says this: a falsy value when the token is revoked, and callers
24+
* fail CLOSED.
2325
* - **`/oauth2/revoke` deletes it** ({@link answerMcpTokenRevocation}) and
2426
* revokes the grant's refresh family: the client's refresh tokens for that
2527
* user, except those minted under another organization
@@ -196,38 +198,62 @@ async function grantRowsOf(
196198
const consentsOf = (store: OAuthGrantStore, grant: McpGrantKey) =>
197199
grantRowsOf(store, 'oauthConsent', grant, isConsentFor);
198200

199-
/** Whether the client is a server-only `skip_consent` client: one that never has a consent row. */
200-
async function isSkipConsentClient(store: OAuthGrantStore, clientId: string): Promise<boolean> {
201-
const client = (await store.findOne({
201+
/** The client row as the adapter answers it (the provider's field names), or `null` when there is none. */
202+
async function clientOf(
203+
store: OAuthGrantStore,
204+
clientId: string,
205+
): Promise<{ skipConsent?: unknown; disabled?: unknown } | null> {
206+
return (await store.findOne({
202207
model: 'oauthClient',
203208
where: [{ field: 'clientId', value: clientId }],
204-
})) as { skipConsent?: unknown } | null;
205-
return client?.skipConsent === true;
209+
})) as { skipConsent?: unknown; disabled?: unknown } | null;
210+
}
211+
212+
/** Whether the client is a server-only `skip_consent` client: one that never has a consent row. */
213+
async function isSkipConsentClient(store: OAuthGrantStore, clientId: string): Promise<boolean> {
214+
return (await clientOf(store, clientId))?.skipConsent === true;
206215
}
207216

208217
/**
209-
* The consent read the MCP door makes on every request: does the grant a
218+
* The grant read the MCP door makes on every request: does the grant a
210219
* verified token was minted under still stand?
211220
*
212-
* Admits when the consent for (`azp`, `sub`, organization) exists and was
213-
* created no later than the token was issued (compared in whole seconds, the
214-
* unit of `iat`). Refuses when it is missing, when it is newer than the token
215-
* (revoked and granted again: the old token belongs to the old grant), when
216-
* `iat` or the row's `createdAt` cannot be read, and when there is no store.
217-
* A store error propagates, and the verifier answers it as a refusal.
221+
* First the client (objectstack-ai/cloud#3820, card 2): a token whose client
222+
* is disabled (`sys_oauth_application.disabled`, the Disable action and
223+
* `POST /auth/admin/oauth2/toggle-disabled`), or whose client row is gone, is
224+
* refused. The provider already refuses a disabled client a new token
225+
* (`invalid_client` at the token endpoint, `client_disabled` at authorize)
226+
* and answers its tokens inactive at introspection, by the same truthy test
227+
* on the same column. Only this door read none of it, so a token minted
228+
* before the disable was served until it expired, up to the provider's
229+
* 3600 s access-token life. Disabling pauses the grant; it does not end it:
230+
* the consent and the refresh family stay, so once the client is enabled
231+
* again the same token and its refresh are served again. Ending the grant is
232+
* the withdraw (`authorized-clients-withdraw.ts`) or `/oauth2/revoke`.
233+
*
234+
* Then the consent: admits when the consent for (`azp`, `sub`,
235+
* organization) exists and was created no later than the token was issued
236+
* (compared in whole seconds, the unit of `iat`). Refuses when it is missing,
237+
* when it is newer than the token (revoked and granted again: the old token
238+
* belongs to the old grant), when `iat` or the row's `createdAt` cannot be
239+
* read, and when there is no store. A server-only `skip_consent` client,
240+
* which has no consent row at all, is admitted without one (ruling A,
241+
* step 5), read off the client row already in hand. A store error
242+
* propagates, and the verifier answers it as a refusal.
218243
*
219-
* One indexed read for a client that consents. Only when that read finds no
220-
* consent is the client read, so that a server-only `skip_consent` client,
221-
* which has no consent row at all, is admitted (ruling A, step 5).
244+
* Two indexed reads per call: the client by its unique `client_id`, and the
245+
* consent by (`client_id`, `user_id`).
222246
*/
223247
export async function mcpConsentAdmits(
224248
store: OAuthGrantStore | undefined,
225249
grant: McpGrantKey,
226250
issuedAt: number | undefined,
227251
): Promise<boolean> {
228252
if (!store) return false;
253+
const client = await clientOf(store, grant.clientId);
254+
if (!client || client.disabled) return false;
229255
const [consent] = await consentsOf(store, grant);
230-
if (!consent) return isSkipConsentClient(store, grant.clientId);
256+
if (!consent) return client.skipConsent === true;
231257
if (typeof issuedAt !== 'number' || !Number.isFinite(issuedAt)) return false;
232258
const createdAtMs =
233259
consent.createdAt instanceof Date || typeof consent.createdAt === 'string' || typeof consent.createdAt === 'number'

0 commit comments

Comments
 (0)