Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

auth.test.ts

413 lines12.5 KB

1import { memoryCredentialStore } from '@tanstack/ai/byok/server'
2import { describe, expect, it, vi } from 'vitest'
3import { EventType, defineAgent, toolDefinition } from '@tanstack/ai'
4import { memoryPersistence } from '@tanstack/ai-persistence'
5import {
6 HARNESS_EVENTS,
7 createHarnessHost,
8 defineCommand,
9 defineHarness,
10 definePlugin,
11 oauthConnector,
12 scrubSecrets,
13} from '../src'
14import {
15 buildAuthorizationUrl,
16 createPkce,
17 deviceLogin,
18 exchangeCode,
19 loopbackLogin,
20 refreshCredential,
21} from '../src/oauth'
22import { mockAdapter, text, toolCall } from './helpers'
23import type { HarnessRunContext, SessionEvent } from '../src'
24import type { OAuthConfig } from '../src/oauth'
25​
26const oauth: OAuthConfig = {
27 authorizationUrl: 'https://auth.example/authorize',
28 tokenUrl: 'https://auth.example/token',
29 deviceUrl: 'https://auth.example/device',
30 clientId: 'client-1',
31 scopes: ['repo', 'read:user'],
33​
34/** A fake token endpoint that records each form body. */
35function tokenEndpoint(responses: Array<Record<string, unknown>>) {
36 const bodies: Array<URLSearchParams> = []
37 const fake: typeof fetch = async (_input, init) => {
38 bodies.push(new URLSearchParams(String(init?.body)))
39 return new Response(JSON.stringify(responses.shift() ?? {}), {
40 headers: { 'content-type': 'application/json' },
41 })
42 }
43 return { fake, bodies }
45​
46describe('PKCE and URLs', () => {
47 it('makes an S256 challenge from the verifier', async () => {
48 const { verifier, challenge } = await createPkce()
49 const digest = await crypto.subtle.digest(
50 'SHA-256',
51 new TextEncoder().encode(verifier),
52 )
53 const expected = Buffer.from(digest).toString('base64url')
54 expect(challenge).toBe(expected)
55 expect(verifier.length).toBeGreaterThanOrEqual(43)
56 })
57​
58 it('builds the authorization URL with state, PKCE, and scopes', () => {
59 const url = new URL(
60 buildAuthorizationUrl(oauth, {
61 redirectUri: 'http://127.0.0.1:5000/callback',
62 state: 's1',
63 challenge: 'c1',
64 }),
65 )
66 expect(url.searchParams.get('client_id')).toBe('client-1')
67 expect(url.searchParams.get('code_challenge_method')).toBe('S256')
68 expect(url.searchParams.get('scope')).toBe('repo read:user')
69 expect(url.searchParams.get('state')).toBe('s1')
70 })
71})
72​
73describe('token exchange', () => {
74 it('trades a code for tokens and refreshes them', async () => {
75 const { fake, bodies } = tokenEndpoint([
76 {
77 access_token: 'a1',
78 refresh_token: 'r1',
79 expires_in: 3600,
80 scope: 'repo',
81 },
82 { access_token: 'a2', expires_in: 3600 },
83 ])
84 const first = await exchangeCode(oauth, {
85 code: 'code-1',
86 verifier: 'v1',
87 redirectUri: 'http://127.0.0.1/callback',
88 fetch: fake,
89 })
90 expect(first).toMatchObject({
91 type: 'oauth',
92 accessToken: 'a1',
93 refreshToken: 'r1',
94 scopes: ['repo'],
95 })
96 expect(bodies[0]?.get('code_verifier')).toBe('v1')
97​
98 const refreshed = await refreshCredential(oauth, first, { fetch: fake })
99 // The old refresh token stays when the server sends no new one.
100 expect(refreshed).toMatchObject({ accessToken: 'a2', refreshToken: 'r1' })
101 expect(bodies[1]?.get('grant_type')).toBe('refresh_token')
102 })
103​
104 it('reports an OAuth error', async () => {
105 const { fake } = tokenEndpoint([{ error: 'bad_verification_code' }])
106 await expect(
107 exchangeCode(oauth, {
108 code: 'x',
109 verifier: 'y',
110 redirectUri: 'z',
111 fetch: fake,
112 }),
113 ).rejects.toThrow('bad_verification_code')
114 })
115})
116​
117describe('loopback login', () => {
118 it('receives the code on 127.0.0.1 and rejects a wrong state', async () => {
119 const { fake } = tokenEndpoint([{ access_token: 'loop-token' }])
120 const signedIn = loopbackLogin(oauth, {
121 fetch: fake,
122 onUrl: (url) => {
123 const parsed = new URL(url)
124 const redirect = new URL(parsed.searchParams.get('redirect_uri')!)
125 expect(redirect.hostname).toBe('127.0.0.1')
126 redirect.searchParams.set('code', 'the-code')
127 redirect.searchParams.set('state', parsed.searchParams.get('state')!)
128 void fetch(redirect)
129 },
130 })
131 await expect(signedIn).resolves.toMatchObject({ accessToken: 'loop-token' })
132​
133 const forged = loopbackLogin(oauth, {
134 fetch: fake,
135 onUrl: (url) => {
136 const redirect = new URL(new URL(url).searchParams.get('redirect_uri')!)
137 redirect.searchParams.set('code', 'x')
138 redirect.searchParams.set('state', 'forged')
139 void fetch(redirect)
140 },
141 })
142 await expect(forged).rejects.toThrow('state does not match')
143 })
144})
145​
146describe('device login', () => {
147 it('shows the code and polls until the user approves', async () => {
148 const responses: Array<Record<string, unknown>> = [
149 {
150 device_code: 'd1',
151 user_code: 'ABCD-1234',
152 verification_uri: 'https://auth.example/device',
153 interval: 1,
154 },
155 { error: 'authorization_pending' },
156 { access_token: 'device-token' },
157 ]
158 const fake: typeof fetch = async () =>
159 new Response(JSON.stringify(responses.shift()), {
160 headers: { 'content-type': 'application/json' },
161 })
162 const onCode = vi.fn()
163 const credential = await deviceLogin(oauth, {
164 fetch: fake,
165 onCode,
166 sleep: async () => {},
167 })
168 expect(onCode).toHaveBeenCalledWith({
169 userCode: 'ABCD-1234',
170 verificationUri: 'https://auth.example/device',
171 expiresAt: expect.any(Number),
172 })
173 expect(credential).toMatchObject({ accessToken: 'device-token' })
174 })
175})
176​
177describe('oauthConnector', () => {
178 it('asks for sign-in, connects, and gives tools a token', async () => {
179 const seenTokens: Array<string> = []
180 const responses: Array<Record<string, unknown>> = [
181 {
182 device_code: 'd1',
183 user_code: 'WXYZ',
184 verification_uri: 'https://gh.example/device',
185 interval: 1,
186 },
187 { access_token: 'gh-token' },
188 ]
189 const fake: typeof fetch = async () =>
190 new Response(JSON.stringify(responses.shift()), {
191 headers: { 'content-type': 'application/json' },
192 })
193 const github = oauthConnector({
194 id: 'github',
195 label: 'GitHub',
196 oauth,
197 login: 'device',
198 fetch: fake,
199 tools: (token) => [
200 toolDefinition({
201 name: 'list_issues',
202 description: 'List issues',
203 }).server<HarnessRunContext>(async (_args, ctx) => {
204 seenTokens.push(await token({ run: ctx.context.run }))
205 return ['#1']
206 }),
207 ],
208 })
209 const persistence = memoryPersistence()
210 const credentials = memoryCredentialStore()
211 const { adapter } = mockAdapter([
212 () => toolCall('list_issues', {}),
213 () => text('Sign in first.'),
214 () => toolCall('list_issues', {}),
215 () => text('One issue.'),
216 ])
217 const host = createHarnessHost({ persistence, credentials })
218 const session = await host.open(
219 defineHarness({
220 name: 'test/connector',
221 adapter,
222 plugins: () => [github],
223 }),
224 {
225 threadId: 't',
226 user: { id: 'user-1' },
227 },
228 )
229 const events: Array<SessionEvent> = []
230 const reader = new AbortController()
231 const reading = (async () => {
232 for await (const entry of session.events({ signal: reader.signal }))
233 events.push(entry)
234 })()
235​
236 // Before sign-in, the tool asks for it.
237 await session.send('list my issues')
238 expect(seenTokens).toEqual([])
239 expect(
240 events.some(
241 (entry) =>
242 entry.event.type === 'CUSTOM' &&
243 entry.event.name === HARNESS_EVENTS.authRequired &&
244 (entry.event.value as { connector: string }).connector === 'github',
245 ),
246 ).toBe(true)
247​
248 await expect(session.runCommand({ name: 'connect:github' })).resolves.toBe(
249 'Connected to GitHub.',
250 )
251 const saved = await credentials.get({
252 scope: { threadId: 't', userId: 'user-1' },
253 id: 'github',
254 })
255 expect(saved).toMatchObject({ accessToken: 'gh-token' })
256​
257 await session.send('list my issues again')
258 expect(seenTokens).toEqual(['gh-token'])
259 // The model never sees the token.
260 const transcript = JSON.stringify(await session.transcript())
261 expect(transcript).toContain('list my issues again')
262 expect(transcript).not.toContain('gh-token')
263​
264 await session.runCommand({ name: 'disconnect:github' })
265 expect(
266 await credentials.list({
267 threadId: 't',
268 userId: 'user-1',
269 }),
270 ).toEqual([])
271 reader.abort()
272 await reading
273 await host.close()
274 })
275})
276​
277describe('commands on close', () => {
278 it('ends a command that ignores its signal when the session closes', async () => {
279 let started: () => void = () => {}
280 const running = new Promise<void>((resolve) => {
281 started = resolve
282 })
283 const plugin = definePlugin({
284 name: 'test/stuck',
285 setup: () => ({
286 commands: {
287 stuck: defineCommand({
288 description: 'Waits for ever',
289 run: () => {
290 started()
291 return new Promise(() => {})
292 },
293 }),
294 },
295 }),
296 })
297 const host = createHarnessHost({
298 persistence: memoryPersistence(),
299 credentials: memoryCredentialStore(),
300 })
301 const session = await host.open(
302 defineHarness({
303 name: 'test/stuck',
304 adapter: mockAdapter(() => text('ok')).adapter,
305 plugins: () => [plugin],
306 }),
307 { threadId: 't1' },
308 )
309 const command = session.runCommand({ name: 'stuck' })
310 await running
311 await host.close()
312 expect(command.status()).toBe('cancelled')
313 })
314})
315​
316describe('scrubSecrets', () => {
317 it('removes known secrets from text', () => {
318 expect(scrubSecrets('token gh-abcdef1234 failed', ['gh-abcdef1234'])).toBe(
319 'token [redacted] failed',
320 )
321 })
322})
323​
324describe('errors a session publishes', () => {
325 it('redacts a credential the command read, also in its JSON form', async () => {
326 const secret = 'sk-"live"-123456'
327 const plugin = definePlugin({
328 name: 'test/leaky',
329 setup: () => ({
330 commands: {
331 leak: defineCommand({
332 description: 'Call the API',
333 run: async (_input, { credentials }) => {
334 const credential = await credentials.require('acme')
335 const value =
336 credential.type === 'api_key' ? credential.value : ''
337 throw new Error(
338 `fetch failed: Bearer ${value} ${JSON.stringify({ value })}`,
339 )
340 },
341 }),
342 },
343 }),
344 })
345 const persistence = memoryPersistence()
346 const credentials = memoryCredentialStore()
347 await credentials.set({
348 scope: { threadId: 't1' },
349 id: 'acme',
350 credential: { type: 'api_key', value: secret },
351 })
352 const { adapter } = mockAdapter(() => text('ok'))
353 const host = createHarnessHost({ persistence, credentials })
354 const session = await host.open(
355 defineHarness({
356 name: 'test/scrub',
357 adapter,
358 plugins: () => [plugin],
359 }),
360 {
361 threadId: 't1',
362 },
363 )
364 const errors: Array<string> = []
365 session.onEvent(EventType.RUN_ERROR, ({ event }) => {
366 errors.push(event.message)
367 })
368​
369 await expect(session.runCommand({ name: 'leak' })).rejects.toThrow()
370​
371 expect(errors).toEqual([
372 'fetch failed: Bearer [redacted] {"value":"[redacted]"}',
373 ])
374 await host.close()
375 })
376​
377 it('redacts a key that a background agent read', async () => {
378 const secret = 'sk-agent-123456'
379 const leaky = defineAgent({
380 name: 'leaky',
381 description: 'Calls the API',
382 run: async (ctx) => {
383 const key = await ctx.keys.require('acme')
384 throw new Error(`fetch failed: Bearer ${key}`)
385 },
386 })
387 const persistence = memoryPersistence()
388 const credentials = memoryCredentialStore()
389 await credentials.set({
390 scope: { threadId: 't1' },
391 id: 'acme',
392 credential: { type: 'api_key', value: secret },
393 })
394 const { adapter } = mockAdapter(() => text('ok'))
395 const host = createHarnessHost({ persistence, credentials })
396 const session = await host.open(
397 defineHarness({ name: 'test/scrub', adapter, agents: [leaky] }),
398 {
399 threadId: 't1',
400 },
401 )
402 const errors: Array<string> = []
403 session.onEvent(EventType.RUN_ERROR, ({ event }) => {
404 errors.push(event.message)
405 })
406​
407 const run = session.agents.leaky.run()
408 await expect(run).rejects.toThrow('[redacted]')
409​
410 expect(errors).toEqual(['fetch failed: Bearer [redacted]'])
411 await host.close()
412 })
413})