Skip to content

Commit 9688e17

Browse files
committed
fix(plugin-auth): #30918 report each distinct last-use failure once, and a withdrawn consent is no failure
Contract review 6686013581, should-fix 1, 3 and 4. - Should-fix 1. The stamper reported only the first failure in a process. A consent withdrawn between the stamp's read and its write made the engine's by-id update throw RECORD_NOT_FOUND, which spent that one report, so a later real outage went unreported. The real store now answers RECORD_NOT_FOUND on the stamp as done, since there is no grant left to stamp. The stamper reports each DISTINCT failure message once per process, capped at 16 messages. Pinned on the real engine by a withdrawal race and a three-hour sequence of two different errors. - Should-fix 3. The module and method docs and the plugin-auth changeset now say "at most once per consent per hour in each process". - Should-fix 4. Rule 7 gains a case for an organization owner and an organization admin naming a person who is only in another organization. They get the same 403 bytes as for a person inside their organization. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4d1LNDAUs8pz7DNjQFC
1 parent 121bdd3 commit 9688e17

5 files changed

Lines changed: 170 additions & 23 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, from the verified token and the server clock alone. A store failure never fails the MCP call and is logged once at `error`. 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 its one error.
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.

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

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4423,8 +4423,8 @@ export class AuthManager {
44234423
*
44244424
* [#30918] A token that verifies also schedules, AFTER the verdict and off
44254425
* the request's path, the coarse last-use stamp on the consent it was minted
4426-
* under (`mcp-client-last-use.ts`): at most one write per consent per hour,
4427-
* from this verified principal and the server's clock. The stamp reads and
4426+
* under (`mcp-client-last-use.ts`): at most one write per consent per hour
4427+
* in each process, from this verified principal and the server's clock. The stamp reads and
44284428
* writes nothing the verdict depends on, and its failure is never this
44294429
* method's failure.
44304430
*/
@@ -4454,8 +4454,9 @@ export class AuthManager {
44544454
/**
44554455
* [#30918] Settle the last-use stamp of the consent `principal`'s token was
44564456
* minted under, after the response (`run-after-response.ts`). At most one
4457-
* write per consent per hour, from the verified principal and the server's
4458-
* clock alone; the first failure in this process is reported at `error`
4457+
* write per consent per hour in each process, from the verified principal
4458+
* and the server's clock alone; each distinct failure is reported once per
4459+
* process at `error`
44594460
* (`error` when the host logger carries it, else `warn`, called through the
44604461
* property — see {@link audienceLogError}; `console.error` when the manager
44614462
* was given no logger, so the report is never silent).
@@ -4465,12 +4466,12 @@ export class AuthManager {
44654466
const stamper = (this.mcpClientLastUse ??= new McpClientLastUseStamper(
44664467
mcpClientLastUseStoreFor(() => this.getDataEngine()),
44674468
{
4468-
onFirstFailure: (error) => {
4469+
onNewFailure: (error) => {
44694470
const message =
44704471
'[AuthManager] The last-use time of authorized AI assistants could not be recorded: '
44714472
+ 'the authorized-clients reads keep answering the last stamp that landed as if it were current. '
44724473
+ 'Check that schema sync has added sys_oauth_consent.last_used_at and that the data engine is reachable; '
4473-
+ 'each consent is retried once an hour, and only this first failure is reported.';
4474+
+ 'each consent is retried once an hour, and each distinct failure is reported once per process.';
44744475
const meta = { error: error instanceof Error ? error.message : String(error) };
44754476
if (this.config.logger) this.audienceLogError(message, meta);
44764477
else console.error(message, meta);

‎packages/plugins/plugin-auth/src/authorized-clients-read.real-plugin.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -476,6 +476,49 @@ describe('#30918 GET /admin/authorized-clients — another person\'s grants', ()
476476
}
477477
});
478478

479+
it('rule 7, outside their organizations: an organization admin or owner naming a person of ANOTHER organization gets the same one refusal', async () => {
480+
const rig = await arrange();
481+
await grantBob(rig);
482+
// Alice joins Beta only, and grants a client there: Olivia and Oscar hold
483+
// Acme, so Alice is a person outside every organization they administer.
484+
await rig.engine.insert('sys_member', {
485+
organization_id: ORG_BETA,
486+
user_id: rig.ids.alice,
487+
role: 'member',
488+
created_at: new Date(),
489+
});
490+
await rig.registerClient('client_beta_only', 'Beta Assistant');
491+
await rig.grant(rig.ids.alice, 'client_beta_only', {
492+
referenceId: ORG_BETA,
493+
createdAt: new Date('2026-11-04T09:00:00.000Z'),
494+
});
495+
const orgsOf = (userId: string) =>
496+
((rig.engine.tables.get('sys_member') ?? []) as any[])
497+
.filter((row) => row.user_id === userId)
498+
.map((row) => row.organization_id);
499+
expect(orgsOf(rig.ids.alice), 'precondition: the target is in Beta only').toEqual([ORG_BETA]);
500+
501+
for (const [who, email] of [
502+
['orgAdmin', ORG_ADMIN_EMAIL],
503+
['orgOwner', OWNER_EMAIL],
504+
] as const) {
505+
const cookie = await rig.signIn(email);
506+
const callerId = (await rig.sessionUser(cookie))?.id;
507+
expect(orgsOf(callerId), `precondition: ${who} is in Acme only`).toEqual([ORG_ACME]);
508+
expect((await rig.sessionUser(cookie))?.isPlatformAdmin, `precondition: ${who} holds no platform standing`).toBe(false);
509+
510+
const outside = await readJson(await rig.get(`${ADMIN_AUTHORIZED_CLIENTS_PATH}?userId=${rig.ids.alice}`, cookie));
511+
const inside = await readJson(await rig.get(`${ADMIN_AUTHORIZED_CLIENTS_PATH}?userId=${rig.ids.bob}`, cookie));
512+
expect(outside.status, `${who}: ${outside.text}`).toBe(403);
513+
expect(outside.body.error.code, who).toBe('PERMISSION_DENIED');
514+
// The same bytes for a person inside and outside their organization:
515+
// the gate reads no organization, so neither answer says which it is.
516+
expect(outside.text, who).toBe(inside.text);
517+
expect(outside.text).not.toContain('client_beta_only');
518+
expect(outside.text).not.toContain(rig.ids.alice);
519+
}
520+
});
521+
479522
it('a platform administrator naming nobody, a repeated or unknown parameter is 400; an id naming no user is 404', async () => {
480523
const rig = await arrange();
481524
await grantBob(rig);

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

Lines changed: 80 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@
1818
* - NOT CLIENT-CONTROLLABLE: the provider's own update-consent door strips a
1919
* last-use member from its body, and a token that does not verify, or
2020
* names no `azp` client, stamps nothing;
21-
* - a failing store never fails the MCP call and is reported once.
21+
* - a failing store never fails the MCP call, and each distinct failure is
22+
* reported once; a consent withdrawn between the stamp's read and its
23+
* write is no failure, so it cannot spend the report a real outage needs.
2224
*
2325
* The access rules of the two reads are pinned on the real plugin in
2426
* `authorized-clients-read.real-plugin.test.ts`.
@@ -378,8 +380,84 @@ describe('[#30918] a failing store', () => {
378380
}
379381
expect(attempts, 'one attempt per hour, however many calls').toBe(2);
380382
const reports = r.logger.error.mock.calls.filter(([message]) => String(message).includes('last-use time'));
381-
expect(reports, 'reported once per process').toHaveLength(1);
383+
expect(reports, 'the same failure is reported once per process').toHaveLength(1);
382384
expect(String(reports[0][0])).toContain('sys_oauth_consent.last_used_at');
383385
expect(reports[0][1]).toEqual({ error: 'no such column: last_used_at' });
384386
}, 60_000);
387+
388+
it('reports each DISTINCT failure once, so an earlier failure never silences a later, different one', async () => {
389+
const r = await rig();
390+
await r.consent();
391+
const failures: Record<number, string> = {
392+
[HOUR_10]: 'SQLITE_BUSY: database is locked',
393+
[HOUR_11]: 'no such column: last_used_at',
394+
[HOUR_11 + 60 * MINUTE]: 'SQLITE_BUSY: database is locked',
395+
};
396+
let attempts = 0;
397+
const realUpdate = (r.engine.update as any).getMockImplementation();
398+
vi.mocked(r.engine.update).mockImplementation((async (object: string, ...rest: unknown[]) => {
399+
if (object === 'sys_oauth_consent') {
400+
attempts += 1;
401+
throw new Error(failures[Math.floor(Date.now() / (60 * MINUTE)) * 60 * MINUTE]);
402+
}
403+
return realUpdate(object, ...rest);
404+
}) as never);
405+
406+
for (const at of [HOUR_10 + 5 * MINUTE, HOUR_11 + 5 * MINUTE, HOUR_11 + 65 * MINUTE]) {
407+
vi.setSystemTime(at);
408+
await r.manager.verifyMcpAccessToken(await r.mint());
409+
await drain();
410+
}
411+
expect(attempts, 'one attempt in each of the three hours').toBe(3);
412+
const reports = r.logger.error.mock.calls.filter(([message]) => String(message).includes('last-use time'));
413+
expect(
414+
reports.map(([, meta]) => meta),
415+
'the locked store, then the missing column; the locked store again is not reported twice',
416+
).toEqual([{ error: 'SQLITE_BUSY: database is locked' }, { error: 'no such column: last_used_at' }]);
417+
}, 60_000);
418+
419+
it('a consent withdrawn between the stamp\'s read and its write is no failure: nothing is reported, and a later outage still is', async () => {
420+
const r = await rig();
421+
const withdrawn = await r.consent();
422+
// The race on the real engine: the stamp reads the consent, then the
423+
// person withdraws it (the row is deleted) before the stamp's write lands.
424+
let withdrawAfterNextRead = true;
425+
const realFind = (r.engine.find as any).getMockImplementation();
426+
vi.mocked(r.engine.find).mockImplementation((async (object: string, ...rest: unknown[]) => {
427+
const rows = await realFind(object, ...rest);
428+
if (object === 'sys_oauth_consent' && withdrawAfterNextRead) {
429+
withdrawAfterNextRead = false;
430+
await r.engine.delete('sys_oauth_consent', { where: { id: withdrawn }, ...SYS } as never);
431+
}
432+
return rows;
433+
}) as never);
434+
const realUpdate = (r.engine.update as any).getMockImplementation();
435+
let updateErrors: string[] = [];
436+
vi.mocked(r.engine.update).mockImplementation((async (object: string, ...rest: unknown[]) => {
437+
try {
438+
return await realUpdate(object, ...rest);
439+
} catch (error) {
440+
updateErrors.push(String((error as { code?: unknown }).code));
441+
throw error;
442+
}
443+
}) as never);
444+
445+
await r.manager.verifyMcpAccessToken(await r.mint());
446+
await drain();
447+
expect(updateErrors, 'the write did land on a row that was gone').toEqual(['RECORD_NOT_FOUND']);
448+
const reportsOf = () => r.logger.error.mock.calls.filter(([message]) => String(message).includes('last-use time'));
449+
expect(reportsOf(), 'a withdrawn consent has nothing to stamp, so it is not reported').toHaveLength(0);
450+
451+
// A later real outage, in the same process, is still reported.
452+
await r.consent();
453+
updateErrors = [];
454+
vi.mocked(r.engine.update).mockImplementation((async (object: string, ...rest: unknown[]) => {
455+
if (object === 'sys_oauth_consent') throw new Error('no such column: last_used_at');
456+
return realUpdate(object, ...rest);
457+
}) as never);
458+
vi.setSystemTime(HOUR_11 + 5 * MINUTE);
459+
await r.manager.verifyMcpAccessToken(await r.mint());
460+
await drain();
461+
expect(reportsOf().map(([, meta]) => meta)).toEqual([{ error: 'no such column: last_used_at' }]);
462+
}, 60_000);
385463
});

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

Lines changed: 39 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@
3232
* arrived, and a row is written only when its stored hour is older than the
3333
* current one. So:
3434
*
35-
* - **at most one write per consent per hour**, however many MCP calls the
36-
* client makes in it. An assistant can make hundreds of tool calls a
35+
* - **at most one write per consent per hour in each process**, however
36+
* many MCP calls the client makes in it. An assistant can make hundreds of tool calls a
3737
* minute; a per-request write would turn every one into a write on an
3838
* identity table. An hour is the granularity a person needs to answer
3939
* "is this laptop's assistant still acting as me?" and the granularity
@@ -54,10 +54,16 @@
5454
*
5555
* The MCP request does not wait for the stamp: the manager schedules it after
5656
* the response (`run-after-response.ts`). A failed read or write loses that
57-
* hour's stamp and nothing else. It is reported once per process at `error`,
58-
* because the reads keep answering an older stamp as if it were current, and
59-
* the hour is retried in the next hour, not on the next call, so a store
60-
* outage never becomes a write per request.
57+
* hour's stamp and nothing else. Each DISTINCT failure (by its message) is
58+
* reported once per process at `error`, because the reads keep answering an
59+
* older stamp as if it were current, and the hour is retried in the next
60+
* hour, not on the next call, so a store outage never becomes a write or a
61+
* log line per request. Keying the report on the message, not on "the first
62+
* failure", is what keeps one benign failure from silencing a later real
63+
* one (the missing column, an unreachable store). The benign one is also
64+
* not a failure at all: a consent withdrawn between the read and the write
65+
* leaves nothing to stamp, so the real store answers that write's
66+
* `RECORD_NOT_FOUND` as done.
6167
*/
6268

6369
/** The stamp's granularity: one clock hour. */
@@ -66,6 +72,13 @@ export const MCP_CLIENT_LAST_USE_GRANULARITY_MS = 60 * 60 * 1000;
6672
/** How many (client, user, organization) keys one process remembers. */
6773
export const MCP_CLIENT_LAST_USE_MEMO_CAP = 10_000;
6874

75+
/**
76+
* How many distinct failure messages one process reports. A bound, so a store
77+
* whose error text varies per row cannot turn the report into a log line per
78+
* consent; past it the stamper stays silent, as one consent's hour is.
79+
*/
80+
export const MCP_CLIENT_LAST_USE_FAILURE_REPORT_CAP = 16;
81+
6982
/** The verified principal, exactly as `verifyMcpAccessToken` returns it. */
7083
export interface VerifiedMcpPrincipal {
7184
userId: string;
@@ -86,7 +99,7 @@ export interface StampableConsent {
8699
export interface McpClientLastUseStore {
87100
/** Every consent `userId` holds for `clientId`, across organizations. */
88101
consentsFor(clientId: string, userId: string): Promise<StampableConsent[]>;
89-
/** Write `at` as the consent's stamp. */
102+
/** Write `at` as the consent's stamp. A consent that is gone by now is a no-op. */
90103
stamp(consentId: string, at: Date): Promise<void>;
91104
}
92105

@@ -155,7 +168,16 @@ export function mcpClientLastUseStoreFor(getEngine: () => unknown): McpClientLas
155168
}));
156169
},
157170
async stamp(consentId, at) {
158-
await engine().update('sys_oauth_consent', { id: consentId, last_used_at: at }, { context: SYSTEM_CTX });
171+
try {
172+
await engine().update('sys_oauth_consent', { id: consentId, last_used_at: at }, { context: SYSTEM_CTX });
173+
} catch (error) {
174+
// The consent was read a moment ago and withdrawn since (the person,
175+
// or a revoke, deleted the row): there is no grant left to stamp, so
176+
// the engine's by-id 404 (`recordNotFoundError`, `@objectstack/core`)
177+
// is the stamp's done, not its failure.
178+
if ((error as { code?: unknown } | null)?.code === 'RECORD_NOT_FOUND') return;
179+
throw error;
180+
}
159181
},
160182
};
161183
}
@@ -168,14 +190,15 @@ export function mcpClientLastUseStoreFor(getEngine: () => unknown): McpClientLas
168190
export class McpClientLastUseStamper {
169191
/** (client, user, organization) → the hour start this process last settled. */
170192
private readonly settled = new Map<string, number>();
171-
private failureReported = false;
193+
/** The failure messages this process has already reported. */
194+
private readonly reportedFailures = new Set<string>();
172195

173196
constructor(
174197
private readonly store: McpClientLastUseStore,
175198
private readonly opts: {
176199
now?: () => number;
177-
/** Told about the FIRST failure in this process only. */
178-
onFirstFailure?: (error: unknown) => void;
200+
/** Told about each DISTINCT failure (by message) once in this process. */
201+
onNewFailure?: (error: unknown) => void;
179202
} = {},
180203
) {}
181204

@@ -203,10 +226,12 @@ export class McpClientLastUseStamper {
203226
if (consent.lastUsedAt && consent.lastUsedAt.getTime() >= hour) return;
204227
await this.store.stamp(consent.id, new Date(hour));
205228
} catch (error) {
206-
if (this.failureReported) return;
207-
this.failureReported = true;
229+
const message = error instanceof Error ? error.message : String(error);
230+
if (this.reportedFailures.has(message)) return;
231+
if (this.reportedFailures.size >= MCP_CLIENT_LAST_USE_FAILURE_REPORT_CAP) return;
232+
this.reportedFailures.add(message);
208233
try {
209-
this.opts.onFirstFailure?.(error);
234+
this.opts.onNewFailure?.(error);
210235
} catch {
211236
// A report is best-effort; the stamp never becomes the caller's failure.
212237
}

0 commit comments

Comments
 (0)