Skip to content

Commit 9bcc1b5

Browse files
committed
test(dogfood): pin the authorized-assistant withdraw over HTTP; docs + changeset
Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibxU7nr4BXM7e8qMfwq
1 parent a6e995a commit 9bcc1b5

5 files changed

Lines changed: 301 additions & 0 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
'@objectstack/client': patch
4+
---
5+
6+
feat(auth): withdraw an authorized AI assistant, for the person themself and for a platform administrator
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
Two new routes beside the authorized-clients reads, each keyed by the consent `id` those reads answer on every row:
12+
13+
- `POST /api/v1/auth/authorized-clients/withdraw` with `{ "id": "…" }` withdraws one of the signed-in person's own authorized assistants. Only that person's grant is withdrawn: an id that names someone else's grant answers `404 RESOURCE_NOT_FOUND`, byte for byte the same as an id that names nothing, and leaves it in place.
14+
- `POST /api/v1/auth/admin/authorized-clients/withdraw` with `{ "userId": "…", "id": "…" }` does the same for a person a platform administrator manages, behind the same gate as `GET /api/v1/auth/admin/authorized-clients`: anyone else is refused once (`401` anonymous, `403 PERMISSION_DENIED` otherwise), whoever the body names and whether or not the person or the grant exists.
15+
16+
A withdraw revokes the grant the way `/oauth2/revoke` does: the consent row, then the client's refresh tokens. The assistant's token is refused on its next MCP call, and it must be authorized again to reconnect. Both routes take a closed body (an unknown key, or a missing or empty value, is `400 VALIDATION_ERROR`) and no query parameter, and answer `{ success: true, data: { id } }` with `Cache-Control: no-store`.
17+
18+
`@objectstack/client` adds `oauth.authorizedClients.withdraw(id)` and `oauth.authorizedClients.withdrawForUser(userId, id)`, both answering `AuthorizedClientWithdrawal` (`{ id }`).
19+
20+
better-auth's own `POST /api/v1/auth/oauth2/delete-consent` is unchanged and stays outside the SDK: it answers an unknown id and another person's id differently, and leaves the refresh tokens behind. Use the new routes instead.

‎content/docs/ai/connect-mcp.mdx‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,20 @@ drive this MCP server. Same word, different layer.
376376
person publishes in the UI); it is served only to a token that carries it,
377377
never to an API key or a session, and every authoring call is still checked
378378
against the caller's own metadata permission.
379+
- **A person can withdraw an assistant they authorized, at any time.**
380+
`GET /api/v1/auth/authorized-clients` lists the assistants the signed-in
381+
person authorized (each row's `id` is the grant), and
382+
`POST /api/v1/auth/authorized-clients/withdraw` with `{ "id": "…" }` revokes
383+
one: the grant and the client's refresh tokens are deleted, so the
384+
assistant's token is refused on its very next call and the assistant must
385+
be authorized again to reconnect. Only the person's own grant is withdrawn;
386+
an id that is someone else's answers `404`, exactly as one that names
387+
nothing. A platform administrator does the same for a person with
388+
`GET /api/v1/auth/admin/authorized-clients?userId=…` and
389+
`POST /api/v1/auth/admin/authorized-clients/withdraw` with
390+
`{ "userId": "…", "id": "…" }`; anyone else is refused `403`. The SDK
391+
spells them `oauth.authorizedClients.list()` / `withdraw(id)` and
392+
`listForUser(userId)` / `withdrawForUser(userId, id)`.
379393
- **Action bodies run as trusted app code** once invoked (the `ai.exposed`
380394
gate and `requiredPermissions` are checked at *invoke* time). Treat writing
381395
an action as a code-review-worthy act — that's the real security boundary.

‎packages/qa/dogfood/test/admin-platform-admin-standing.dogfood.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,13 @@ const ADMITTED = [
246246
// ADR-0068 gate first, then the closed `{ userId }` query; no stored state
247247
// moves, so it has no individual effect pin below.
248248
'GET /api/v1/auth/admin/authorized-clients',
249+
// #31048 — withdraw one of another person's authorized AI assistants: an
250+
// ObjectStack raw mount whose FIRST statement is the ADR-0068 gate, then the
251+
// closed `{ userId, id }` body. The probe names a consent the target does
252+
// not hold, so the admin reaches the handler and gets 404 and nothing
253+
// moves; the withdraw's effect is pinned in
254+
// `authorized-client-withdraw.dogfood.test.ts`.
255+
'POST /api/v1/auth/admin/authorized-clients/withdraw',
249256
'POST /api/v1/auth/admin/unlock-user',
250257
'POST /api/v1/auth/admin/import-users',
251258
'POST /api/v1/auth/admin/oauth2/toggle-disabled',
@@ -727,6 +734,9 @@ describe('#9482: what an ObjectStack platform admin gets from every /admin/ rout
727734
// `400 VALIDATION_ERROR` past the gate, which the `diedBeforeTheGate`
728735
// predicate below reads as a void reading.
729736
'GET /api/v1/auth/admin/authorized-clients': { query: `?userId=${targetUserId}` },
737+
// #31048. Both body keys are required: with none the handler answers
738+
// `400 VALIDATION_ERROR` past the gate, a void reading below.
739+
'POST /api/v1/auth/admin/authorized-clients/withdraw': { body: { userId: targetUserId, id: 'standing-probe-consent' } },
730740
'POST /api/v1/auth/admin/oauth2/toggle-disabled': { body: { client_id: 'standing-probe-client', disabled: false } },
731741
'POST /api/v1/auth/admin/sso/register': {
732742
body: {

‎packages/qa/dogfood/test/admin-route-nonadmin-refusal.dogfood.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,12 @@ function expectationsFor(targetUserId: string): Record<string, RouteExpectation>
289289
query: `?userId=${targetUserId}`,
290290
note: 'a read: the gate runs before the query is read, so anon and member are refused whoever userId names; the admin gets 200 { clients, truncated } for the target',
291291
},
292+
// ── #31048 — withdraw one of another person's authorized AI assistants ──
293+
'POST /api/v1/auth/admin/authorized-clients/withdraw': {
294+
bucket: 'objectstack-gate',
295+
body: { userId: targetUserId, id: 'refusal-probe-consent' },
296+
note: 'the gate runs ahead of any body read, so anon and member are refused whoever the body names; the admin passes it and lands on 404 RESOURCE_NOT_FOUND for the consent the target does not hold',
297+
},
292298
// ── #30958 — the SCIM connection-credential door (mint + revoke) ────────
293299
//
294300
// Both mounts run `gateAdmin(c)` as their first statement, ahead of any body
Lines changed: 251 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,251 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#31048] Withdrawing an authorized AI assistant, over HTTP on the real
5+
* showcase stack: the assistant's token is refused at the MCP door on its very
6+
* next call, and its refresh grant mints nothing.
7+
*
8+
* The consent page tells a person they can withdraw an assistant's access at
9+
* any time. The console lists the assistants a person authorized
10+
* (`GET /auth/authorized-clients`, and `GET /auth/admin/authorized-clients` for
11+
* an administrator); these pins hold the two withdraws beside them:
12+
*
13+
* - `POST /auth/authorized-clients/withdraw { id }`: the person withdraws
14+
* their own. Another member naming that id gets the same 404 as an id that
15+
* names nothing, and the assistant keeps working.
16+
* - `POST /auth/admin/authorized-clients/withdraw { userId, id }`: a platform
17+
* administrator withdraws a person's; a member is refused 403 and nothing
18+
* moves.
19+
*
20+
* Each withdraw deletes the consent through better-auth's own adapter, so
21+
* plugin-audit's generic writer records it exactly as it records the grant:
22+
* a `create` row when the consent page writes the consent, a `delete` row when
23+
* the withdraw removes it, credited to the person who withdrew it. The access
24+
* matrix (unknown ids, foreign keys, every non-admin caller) is pinned on the
25+
* real plugin in `plugin-auth` `authorized-clients-read.real-plugin.test.ts`.
26+
*/
27+
28+
import { createHash, randomBytes } from 'node:crypto';
29+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
30+
import { type VerifyStack } from '@objectstack/verify';
31+
import { MCPServerPlugin } from '@objectstack/mcp';
32+
import { AuditPlugin } from '@objectstack/plugin-audit';
33+
import { bootShowcase } from './showcase-boot.js';
34+
35+
const SYS = { context: { isSystem: true } };
36+
const PASSWORD = 'Member-Pass-123';
37+
const REDIRECT_URI = 'http://127.0.0.1:33420/callback';
38+
const SCOPE = 'openid profile email offline_access data:read';
39+
40+
const OWNER_EMAIL = 'withdraw.owner.31048@verify.test';
41+
const OTHER_EMAIL = 'withdraw.other.31048@verify.test';
42+
43+
interface AgentGrant {
44+
clientId: string;
45+
accessToken: string;
46+
refreshToken: string;
47+
}
48+
49+
const rowsOf = (r: any): any[] => (Array.isArray(r) ? r : Array.isArray(r?.value) ? r.value : (r?.records ?? []));
50+
51+
describe('#31048 withdrawing an authorized AI assistant refuses its token on the next call', () => {
52+
let stack: VerifyStack;
53+
let adminToken: string;
54+
let ql: any;
55+
let resource: string;
56+
let priorOidc: string | undefined;
57+
let ownerId: string;
58+
let ownerSession: string;
59+
let otherSession: string;
60+
61+
const tokenEndpoint = (form: Record<string, string>) =>
62+
stack.api('/auth/oauth2/token', {
63+
method: 'POST',
64+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
65+
body: new URLSearchParams(form).toString(),
66+
});
67+
68+
/** DCR → sign-in → authorize with the MCP resource → consent → code exchange. */
69+
const consentAgent = async (email: string): Promise<AgentGrant> => {
70+
const reg = await stack.api('/auth/oauth2/register', {
71+
method: 'POST',
72+
headers: { 'content-type': 'application/json' },
73+
body: JSON.stringify({
74+
client_name: 'withdraw pin',
75+
redirect_uris: [REDIRECT_URI],
76+
grant_types: ['authorization_code', 'refresh_token'],
77+
response_types: ['code'],
78+
token_endpoint_auth_method: 'none',
79+
application_type: 'native',
80+
scope: SCOPE,
81+
}),
82+
});
83+
const regBody: any = await reg.json();
84+
expect(reg.status, JSON.stringify(regBody)).toBe(201);
85+
const signIn = await stack.api('/auth/sign-in/email', {
86+
method: 'POST',
87+
headers: { 'content-type': 'application/json' },
88+
body: JSON.stringify({ email, password: PASSWORD }),
89+
});
90+
expect(signIn.status, await signIn.clone().text()).toBe(200);
91+
const cookie = ((signIn.headers as any).getSetCookie() as string[]).map((c) => c.split(';')[0]).join('; ');
92+
const verifier = randomBytes(32).toString('base64url');
93+
const challenge = createHash('sha256').update(verifier).digest('base64url');
94+
const qs = new URLSearchParams({
95+
client_id: regBody.client_id,
96+
redirect_uri: REDIRECT_URI,
97+
response_type: 'code',
98+
scope: SCOPE,
99+
state: 'st',
100+
code_challenge: challenge,
101+
code_challenge_method: 'S256',
102+
resource,
103+
});
104+
const az = await stack.api(`/auth/oauth2/authorize?${qs}`, { headers: { cookie }, redirect: 'manual' });
105+
const loc = az.headers.get('location') ?? '';
106+
let code = new URL(loc, 'http://localhost:3000').searchParams.get('code');
107+
if (!code) {
108+
const consent = await stack.api('/auth/oauth2/consent', {
109+
method: 'POST',
110+
headers: { 'content-type': 'application/json', cookie, origin: 'http://localhost:3000' },
111+
body: JSON.stringify({ accept: true, oauth_query: loc.slice(loc.indexOf('?')) }),
112+
});
113+
const cb: any = await consent.json().catch(() => null);
114+
code = new URL(cb?.redirect_uri ?? cb?.url).searchParams.get('code');
115+
}
116+
const tok = await tokenEndpoint({
117+
grant_type: 'authorization_code',
118+
code: code!,
119+
redirect_uri: REDIRECT_URI,
120+
client_id: regBody.client_id,
121+
code_verifier: verifier,
122+
resource,
123+
});
124+
const tj: any = await tok.json();
125+
expect(tok.status, JSON.stringify(tj)).toBe(200);
126+
expect(tj.refresh_token, 'offline_access yields a refresh token').toBeTruthy();
127+
return { clientId: regBody.client_id, accessToken: tj.access_token, refreshToken: tj.refresh_token };
128+
};
129+
130+
const initialize = (token: string) =>
131+
stack.api('/mcp', {
132+
method: 'POST',
133+
headers: {
134+
'Content-Type': 'application/json',
135+
Accept: 'application/json, text/event-stream',
136+
Authorization: `Bearer ${token}`,
137+
},
138+
body: JSON.stringify({
139+
jsonrpc: '2.0',
140+
id: 1,
141+
method: 'initialize',
142+
params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'withdraw-pin', version: '0.0.0' } },
143+
}),
144+
});
145+
146+
const refresh = (grant: AgentGrant) =>
147+
tokenEndpoint({ grant_type: 'refresh_token', refresh_token: grant.refreshToken, client_id: grant.clientId, resource });
148+
149+
/** The consent id the own read answers for `clientId`. */
150+
const consentIdOf = async (session: string, clientId: string): Promise<string> => {
151+
const res = await stack.apiAs(session, 'GET', '/auth/authorized-clients');
152+
const body: any = await res.json();
153+
expect(res.status, JSON.stringify(body)).toBe(200);
154+
const row = body.data.clients.find((c: any) => c.clientId === clientId);
155+
expect(row, `the own read lists ${clientId}`).toBeDefined();
156+
return String(row.id);
157+
};
158+
159+
const consentRows = async (id: string) => rowsOf(await ql.find('sys_oauth_consent', { where: { id }, limit: 5, ...SYS }));
160+
161+
/** plugin-audit's rows for one consent, polled: generic rows land after the response. */
162+
const auditRowsFor = async (id: string, action: string): Promise<any[]> => {
163+
let rows: any[] = [];
164+
for (let i = 0; i < 40; i++) {
165+
rows = rowsOf(
166+
await ql.find('sys_audit_log', { where: { object_name: 'sys_oauth_consent', record_id: id, action }, limit: 10, ...SYS }),
167+
);
168+
if (rows.length) return rows;
169+
await new Promise((r) => setTimeout(r, 250));
170+
}
171+
return rows;
172+
};
173+
174+
beforeAll(async () => {
175+
// The OAuth authorization server is opt-in, read when the auth manager is
176+
// constructed, so it precedes the boot. plugin-audit is what turns the
177+
// adapter's consent writes into generic audit rows.
178+
priorOidc = process.env.OS_OIDC_PROVIDER_ENABLED;
179+
process.env.OS_OIDC_PROVIDER_ENABLED = 'true';
180+
stack = await bootShowcase({ extraPlugins: [new MCPServerPlugin(), new AuditPlugin()] });
181+
adminToken = await stack.signIn();
182+
ql = await stack.kernel.getServiceAsync('objectql');
183+
resource = ((await stack.kernel.getServiceAsync('auth')) as any).getMcpResourceUrl();
184+
185+
ownerSession = await stack.signUp(OWNER_EMAIL, PASSWORD);
186+
const me = await stack.apiAs(ownerSession, 'GET', '/auth/get-session');
187+
ownerId = String(((await me.json()) as any)?.user?.id ?? '');
188+
expect(ownerId).not.toBe('');
189+
otherSession = await stack.signUp(OTHER_EMAIL, PASSWORD);
190+
}, 300_000);
191+
192+
afterAll(async () => {
193+
await stack?.stop?.();
194+
if (priorOidc === undefined) delete process.env.OS_OIDC_PROVIDER_ENABLED;
195+
else process.env.OS_OIDC_PROVIDER_ENABLED = priorOidc;
196+
});
197+
198+
it('the own door: another member\'s attempt is the same 404 as an unknown id and moves nothing; the person\'s own withdraw refuses the token and its refresh', async () => {
199+
const grant = await consentAgent(OWNER_EMAIL);
200+
const id = await consentIdOf(ownerSession, grant.clientId);
201+
const served = await initialize(grant.accessToken);
202+
expect(served.status, `precondition: the token is served ${await served.clone().text()}`).toBe(200);
203+
expect((await auditRowsFor(id, 'create')).length, 'the grant is audited by the generic writer').toBeGreaterThan(0);
204+
205+
const others = await stack.apiAs(otherSession, 'POST', '/auth/authorized-clients/withdraw', { id });
206+
const unknown = await stack.apiAs(otherSession, 'POST', '/auth/authorized-clients/withdraw', { id: 'consent_nobody_31048' });
207+
const othersText = await others.text();
208+
expect(others.status, othersText).toBe(404);
209+
expect(JSON.parse(othersText).error.code).toBe('RESOURCE_NOT_FOUND');
210+
expect(othersText, 'the refusal says nothing about whether the id exists').toBe(await unknown.text());
211+
expect(await consentRows(id), 'the owner\'s consent stays').toHaveLength(1);
212+
const stillServed = await initialize(grant.accessToken);
213+
expect(stillServed.status, await stillServed.clone().text()).toBe(200);
214+
215+
const withdrawn = await stack.apiAs(ownerSession, 'POST', '/auth/authorized-clients/withdraw', { id });
216+
const withdrawnBody: any = await withdrawn.json();
217+
expect(withdrawn.status, JSON.stringify(withdrawnBody)).toBe(200);
218+
expect(withdrawnBody).toEqual({ success: true, data: { id } });
219+
220+
expect(await consentRows(id)).toEqual([]);
221+
const refused = await initialize(grant.accessToken);
222+
expect(refused.status, `the withdrawn token is refused on its next call ${await refused.clone().text()}`).toBe(401);
223+
const renewed = await refresh(grant);
224+
const renewedBody: any = await renewed.json();
225+
expect(renewed.status, `the refresh grant mints nothing ${JSON.stringify(renewedBody)}`).toBe(400);
226+
expect(renewedBody?.error).toBe('invalid_grant');
227+
228+
const deletes = await auditRowsFor(id, 'delete');
229+
expect(deletes, 'the withdraw is audited as the grant is: a generic delete row').toHaveLength(1);
230+
expect(deletes[0].user_id, 'credited to the person who withdrew it').toBe(ownerId);
231+
});
232+
233+
it('the admin door: a member is refused 403 and nothing moves; a platform administrator withdraws the person\'s grant', async () => {
234+
const grant = await consentAgent(OWNER_EMAIL);
235+
const id = await consentIdOf(ownerSession, grant.clientId);
236+
237+
const member = await stack.apiAs(otherSession, 'POST', '/auth/admin/authorized-clients/withdraw', { userId: ownerId, id });
238+
const memberText = await member.text();
239+
expect(member.status, memberText).toBe(403);
240+
expect(JSON.parse(memberText).error.code).toBe('PERMISSION_DENIED');
241+
expect(await consentRows(id)).toHaveLength(1);
242+
243+
const admin = await stack.apiAs(adminToken, 'POST', '/auth/admin/authorized-clients/withdraw', { userId: ownerId, id });
244+
const adminBody: any = await admin.json();
245+
expect(admin.status, JSON.stringify(adminBody)).toBe(200);
246+
expect(adminBody).toEqual({ success: true, data: { id } });
247+
expect(await consentRows(id)).toEqual([]);
248+
const refused = await initialize(grant.accessToken);
249+
expect(refused.status, await refused.clone().text()).toBe(401);
250+
});
251+
});

0 commit comments

Comments
 (0)