Skip to content

Commit 0bed2ac

Browse files
committed
fix(plugin-auth): #30918 stamp only the consent that admitted the MCP call
Since #30879, verifyMcpAccessToken admits a token only while its consent stands: the consent for (azp, sub, organization) exists and was created no later than the token's iat (mcpConsentAdmits). The stamp now picks its consent by that same rule, so it can only land on the consent that admitted the call. - A revoked consent refuses the call, so nothing is stamped. - After a re-grant, a token of the earlier grant is refused. The new consent is not stamped with the old token's use even when the re-grant lands between the verdict and the after-response stamp, because it is newer than the token. AuthManager hands the stamp the verified token's iat (decoded from the token the verifier has just admitted). The stamp's consent read also selects created_at. The real-engine tests mint tokens with the iat the provider mints. A client_id-only token is now refused by the verifier. Two new cases cover the composition: revoke, then re-grant; and the re-grant race on the real engine. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4d1LNDAUs8pz7DNjQFC
1 parent e465506 commit 0bed2ac

5 files changed

Lines changed: 161 additions & 33 deletions

File tree

‎.changeset/30918-plugin-auth-authorized-clients.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,4 @@ Two new reads, both ObjectStack mounts ahead of the better-auth catch-all and bo
1414

1515
Each row carries exactly `id` (the consent id, the key `POST /oauth2/delete-consent` takes), `clientId`, `name`, `scopes`, `organizationId`, `authorizedAt` and `lastUsedAt`. Nothing in it identifies or reconstructs a token. The answer is newest first, at most 200 rows, with `truncated: true` when the person holds more, and it is sent with `Cache-Control: no-store`.
1616

17-
`lastUsedAt` is the start of the most recent clock hour in which the client made a verified MCP call under that consent, or `null` when none has been recorded. The server writes it after `verifyMcpAccessToken` admits a token with an `azp` client: off the request path, at most once per consent per hour in each process (several processes may each write the same hour start), from the verified token and the server clock alone. A store failure never fails the MCP call, and each distinct failure is logged once per process at `error`; a consent withdrawn between the stamp's read and its write is not a failure. It lands in the new `sys_oauth_consent.last_used_at` column, so a deployment picks it up at its next schema sync. Until then the reads answer `500` and the stamp logs that error once per process.
17+
`lastUsedAt` is the start of the most recent clock hour in which the client made a verified MCP call under that consent, or `null` when none has been recorded. The server writes it after `verifyMcpAccessToken` admits a token, and only on the consent that admitted it: the consent for the token's client, person and organization, created no later than the token was issued, the rule the verifier's own consent read applies. So a revoked consent, or a token of an earlier grant, stamps nothing. The write is off the request path, at most once per consent per hour in each process (several processes may each write the same hour start), from the verified token and the server clock alone. A store failure never fails the MCP call, and each distinct failure is logged once per process at `error`; a consent withdrawn between the stamp's read and its write is not a failure. It lands in the new `sys_oauth_consent.last_used_at` column, so a deployment picks it up at its next schema sync. Until then the reads answer `500` and the stamp logs that error once per process.

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,9 @@
2727
* body is one literal of exactly the {@link McpAccessTokenHost} members that
2828
* method reads, plus a `.call`. `verifyMcpAccessToken` is no longer `async`:
2929
* it returns the moved function's own promise with one `.then` on it, which
30-
* hands a verified principal to the coarse last-use stamp
31-
* (`mcp-client-last-use.ts`, #30918) and resolves to the same value.
30+
* hands a verified principal (and the verified token, for its `iat`) to the
31+
* coarse last-use stamp (`mcp-client-last-use.ts`, #30918) and resolves to
32+
* the same value.
3233
*
3334
* A method goes as a closure that calls it on the manager at call time, so a
3435
* test double or spy set on the manager is still the one a body reaches —

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

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
22

33
import type { Auth, BetterAuthOptions } from 'better-auth';
4-
import type { JSONWebKeySet } from 'jose';
4+
import { decodeJwt, type JSONWebKeySet } from 'jose';
55
import type { SCIMIdentityState, SCIMTransactionContext } from '@better-auth/scim';
66
// better-auth value imports (betterAuth + plugins) are deferred via dynamic
77
// import() in getOrCreateAuth() / buildPluginList() so that disabled plugins
@@ -4530,9 +4530,10 @@ export class AuthManager {
45304530
* [#30918] A token that verifies also schedules, AFTER the verdict and off
45314531
* the request's path, the coarse last-use stamp on the consent it was minted
45324532
* under (`mcp-client-last-use.ts`): at most one write per consent per hour
4533-
* in each process, from this verified principal and the server's clock. The stamp reads and
4534-
* writes nothing the verdict depends on, and its failure is never this
4535-
* method's failure.
4533+
* in each process, from this verified token and the server's clock, and
4534+
* only on the consent that admitted it (the consent read above, by the same
4535+
* rule). The stamp reads and writes nothing the verdict depends on, and its
4536+
* failure is never this method's failure.
45364537
*/
45374538
verifyMcpAccessToken(
45384539
token: string,
@@ -4548,9 +4549,12 @@ export class AuthManager {
45484549
};
45494550
// [#30918] A token that verified is a verified MCP call: its consent's
45504551
// coarse last-use stamp is settled after the response, never awaited here,
4551-
// and from the verified principal only (`mcp-client-last-use.ts`).
4552+
// and from the verified token only (`mcp-client-last-use.ts`). The
4553+
// verifier has just admitted the token by its consent (#30879,
4554+
// `mcpConsentAdmits`), so a revoked consent refuses the call and stamps
4555+
// nothing; the stamp picks its consent by the same rule.
45524556
return verifyMcpAccessToken.call(host, token).then((principal) => {
4553-
if (principal) this.scheduleMcpClientLastUse(principal);
4557+
if (principal) this.scheduleMcpClientLastUse(principal, token);
45544558
return principal;
45554559
});
45564560
}
@@ -4568,8 +4572,20 @@ export class AuthManager {
45684572
* property — see {@link audienceLogError}; `console.error` when the manager
45694573
* was given no logger, so the report is never silent).
45704574
*/
4571-
private scheduleMcpClientLastUse(principal: { userId: string; clientId?: string; organizationId?: string }): void {
4575+
private scheduleMcpClientLastUse(
4576+
principal: { userId: string; clientId?: string; organizationId?: string },
4577+
token: string,
4578+
): void {
45724579
if (!principal.clientId) return;
4580+
// The token has just verified, so its payload is the one the signature
4581+
// covers: its `iat` is what the verifier admitted the consent against.
4582+
let issuedAt: number | undefined;
4583+
try {
4584+
const iat = decodeJwt(token).iat;
4585+
issuedAt = typeof iat === 'number' ? iat : undefined;
4586+
} catch {
4587+
issuedAt = undefined;
4588+
}
45734589
const stamper = (this.mcpClientLastUse ??= new McpClientLastUseStamper(
45744590
mcpClientLastUseStoreFor(() => this.getDataEngine()),
45754591
{
@@ -4586,7 +4602,7 @@ export class AuthManager {
45864602
},
45874603
));
45884604
runAfterResponse(
4589-
() => stamper.record(principal),
4605+
() => stamper.record({ ...principal, ...(issuedAt !== undefined ? { issuedAt } : {}) }),
45904606
() => {
45914607
// `record` never rejects; its own failure report is above.
45924608
},

‎packages/plugins/plugin-auth/src/mcp-client-last-use.real-engine.test.ts‎

Lines changed: 93 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,12 @@ const drain = async () => {
9292
for (let i = 0; i < 25; i++) await new Promise((resolve) => setImmediate(resolve));
9393
};
9494

95+
/** The stamp's own consent read: the one query that selects `last_used_at` by client and user. */
96+
function isStampRead(query: unknown): boolean {
97+
const q = query as { fields?: unknown; where?: Record<string, unknown> } | undefined;
98+
return Array.isArray(q?.fields) && q.fields.includes('last_used_at') && !!q.where && 'client_id' in q.where;
99+
}
100+
95101
async function rig() {
96102
const engine = new ObjectQL();
97103
engines.push(engine);
@@ -110,7 +116,10 @@ async function rig() {
110116
const manager = makeManager();
111117
const api: any = await manager.getApi();
112118

113-
// Every read and write of the consent table, counted at the engine.
119+
// Every write of the consent table, and every read the STAMP makes of it
120+
// (the one that selects `last_used_at`), counted at the engine. The
121+
// verifier's own per-call consent read (#30879) goes through better-auth's
122+
// adapter and never selects the stamp, so it is not counted here.
114123
let consentWrites = 0;
115124
let consentReads = 0;
116125
const realUpdate = engine.update.bind(engine);
@@ -120,15 +129,20 @@ async function rig() {
120129
return (realUpdate as any)(object, ...rest);
121130
}) as never);
122131
vi.spyOn(engine, 'find').mockImplementation((async (object: string, ...rest: unknown[]) => {
123-
if (object === 'sys_oauth_consent') consentReads += 1;
132+
if (object === 'sys_oauth_consent' && isStampRead(rest[0])) consentReads += 1;
124133
return (realFind as any)(object, ...rest);
125134
}) as never);
126135

127-
/** A token for this deployment's MCP resource, signed by the jwt plugin at the current (fake) time. */
136+
/**
137+
* A token for this deployment's MCP resource, signed by the jwt plugin at
138+
* the current (fake) time, with the `iat` the provider mints into every
139+
* access token (the verifier's consent read compares it, #30879).
140+
*/
128141
const mint = async (claims: Record<string, unknown> = {}): Promise<string> =>
129142
(await api.signJWT({
130143
body: {
131144
payload: {
145+
iat: Math.floor(Date.now() / 1000),
132146
sub: USER,
133147
azp: CLIENT,
134148
scope: 'data:read',
@@ -164,9 +178,16 @@ async function rig() {
164178
return value == null || value === '' ? null : new Date(value).toISOString();
165179
};
166180

181+
/** The person withdraws a consent: the row is deleted, as `/oauth2/delete-consent` and `/oauth2/revoke` delete it. */
182+
const withdraw = async (consentId: string): Promise<void> => {
183+
const ctx = await manager.getAuthContext();
184+
await ctx.adapter.delete({ model: 'oauthConsent', where: [{ field: 'id', value: consentId }] });
185+
};
186+
167187
return {
168188
engine,
169189
manager,
190+
withdraw,
170191
makeManager,
171192
api,
172193
logger,
@@ -287,9 +308,9 @@ describe('[#30918] nothing a client sends reaches the stamp', () => {
287308
expect(await r.manager.verifyMcpAccessToken(foreignKey)).toBeNull();
288309
expect(await r.manager.verifyMcpAccessToken(expired)).toBeNull();
289310
expect(await r.manager.verifyMcpAccessToken('not.a.token')).toBeNull();
290-
const principal = await r.manager.verifyMcpAccessToken(noAzp);
291-
expect(principal, 'a client_id-only token still verifies').toMatchObject({ userId: USER });
292-
expect(principal?.clientId).toBeUndefined();
311+
// #30879 keys the verifier's consent read by `azp`, so a token without one
312+
// is refused before the stamp could see it.
313+
expect(await r.manager.verifyMcpAccessToken(noAzp), 'a client_id-only token is refused').toBeNull();
293314

294315
// Positive control on the same process: a verified token for another
295316
// client stamps, so the stamp path is live while the five above did not.
@@ -403,7 +424,8 @@ describe('[#30918] a failing store', () => {
403424
return realUpdate(object, ...rest);
404425
}) as never);
405426

406-
for (const at of [HOUR_10 + 5 * MINUTE, HOUR_11 + 5 * MINUTE, HOUR_11 + 65 * MINUTE]) {
427+
// Every call after the consent was granted (10:17), so the verifier admits each.
428+
for (const at of [HOUR_10 + 20 * MINUTE, HOUR_11 + 5 * MINUTE, HOUR_11 + 65 * MINUTE]) {
407429
vi.setSystemTime(at);
408430
await r.manager.verifyMcpAccessToken(await r.mint());
409431
await drain();
@@ -425,7 +447,7 @@ describe('[#30918] a failing store', () => {
425447
const realFind = (r.engine.find as any).getMockImplementation();
426448
vi.mocked(r.engine.find).mockImplementation((async (object: string, ...rest: unknown[]) => {
427449
const rows = await realFind(object, ...rest);
428-
if (object === 'sys_oauth_consent' && withdrawAfterNextRead) {
450+
if (object === 'sys_oauth_consent' && withdrawAfterNextRead && isStampRead(rest[0])) {
429451
withdrawAfterNextRead = false;
430452
await r.engine.delete('sys_oauth_consent', { where: { id: withdrawn }, ...SYS } as never);
431453
}
@@ -461,3 +483,66 @@ describe('[#30918] a failing store', () => {
461483
expect(reportsOf().map(([, meta]) => meta)).toEqual([{ error: 'no such column: last_used_at' }]);
462484
}, 60_000);
463485
});
486+
487+
describe('[#30918 × #30879] the stamp lands only on the consent that admitted the call', () => {
488+
it('a revoked consent stamps nothing; a consent granted again is not stamped by a token of the old grant', async () => {
489+
const r = await rig();
490+
const first = await r.consent();
491+
const oldToken = await r.mint();
492+
expect(await r.manager.verifyMcpAccessToken(oldToken)).toMatchObject({ userId: USER, clientId: CLIENT });
493+
await vi.waitFor(async () => expect(await r.stampOf(first)).toBe(iso(HOUR_10)));
494+
await drain();
495+
const writes = r.writes();
496+
497+
// Withdrawn: the verifier refuses the token, so nothing is stamped, in
498+
// this hour or the next.
499+
await r.withdraw(first);
500+
vi.setSystemTime(HOUR_11 + 3 * MINUTE);
501+
expect(await r.manager.verifyMcpAccessToken(oldToken), 'a revoked consent refuses its token').toBeNull();
502+
await drain();
503+
expect(r.writes(), 'a revoked consent stamps nothing').toBe(writes);
504+
505+
// Granted again: the old token belongs to the old grant and is refused;
506+
// the new consent stays unstamped until a token of ITS grant is used.
507+
vi.setSystemTime(HOUR_11 + 4 * MINUTE);
508+
const again = await r.consent();
509+
expect(await r.manager.verifyMcpAccessToken(oldToken), 'a token older than the consent is refused').toBeNull();
510+
await drain();
511+
expect(await r.stampOf(again)).toBeNull();
512+
expect(r.writes()).toBe(writes);
513+
514+
vi.setSystemTime(HOUR_11 + 5 * MINUTE);
515+
expect(await r.manager.verifyMcpAccessToken(await r.mint())).toMatchObject({ userId: USER });
516+
await vi.waitFor(async () => expect(await r.stampOf(again)).toBe(iso(HOUR_11)));
517+
}, 60_000);
518+
519+
it('a re-grant that lands between the verdict and the stamp is not stamped with the old token\'s use', async () => {
520+
const r = await rig();
521+
const first = await r.consent();
522+
const oldToken = await r.mint();
523+
let regranted: string | undefined;
524+
525+
// The race on the real engine: the verdict admits the old token under its
526+
// consent; before the stamp (which runs after the response) reads, the
527+
// person revokes and grants again, two minutes later.
528+
let regrantBeforeStampRead = true;
529+
const realFind = (r.engine.find as any).getMockImplementation();
530+
vi.mocked(r.engine.find).mockImplementation((async (object: string, ...rest: unknown[]) => {
531+
if (object === 'sys_oauth_consent' && regrantBeforeStampRead && isStampRead(rest[0])) {
532+
regrantBeforeStampRead = false;
533+
await r.withdraw(first);
534+
vi.setSystemTime(HOUR_10 + 19 * MINUTE);
535+
regranted = await r.consent();
536+
}
537+
return realFind(object, ...rest);
538+
}) as never);
539+
540+
expect(await r.manager.verifyMcpAccessToken(oldToken), 'the verdict admits the token under its consent').toMatchObject({
541+
userId: USER,
542+
});
543+
await drain();
544+
expect(regranted, 'the re-grant ran inside the stamp').toBeDefined();
545+
expect(r.writes(), 'the new consent is newer than the token, so it is not stamped').toBe(0);
546+
expect(await r.stampOf(regranted!)).toBeNull();
547+
}, 60_000);
548+
});

0 commit comments

Comments
 (0)