|
| 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