Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { env } from 'cloudflare:test'
3
4import { getDb } from '../db/index.ts'
5import { createAuth } from '../lib/auth.ts'
6import { parseRegisterKeyBody, registerKeyAgent } from './agents-api.ts'
7import { requireAgent } from './require-agent.ts'
8
9const makeAuth = () =>
10 createAuth(getDb(env), {
11 secret: 'vitest-only-better-auth-secret-0123456789',
12 baseUrl: 'http://keys.test',
13 })
14
15const keyedRequest = (headers: Record<string, string>) =>
16 new Request('http://keys.test/v1/agents/me', { headers })
17
18describe('registerKeyAgent + API-key requireAgent', () => {
19 it('registers and authenticates with the returned key', async () => {
20 const auth = makeAuth()
21 const outcome = await registerKeyAgent(auth, getDb(env), {
22 name: 'Keyed Agent',
23 })
24 expect(outcome.ok).toBe(true)
25 if (!outcome.ok) return
26 expect(outcome.result.key).toBeTruthy()
27 expect(outcome.result.note).toContain('once')
28
29 const viaBearer = await requireAgent(
30 auth,
31 keyedRequest({ authorization: `Bearer ${outcome.result.key}` }),
32 )
33 expect(viaBearer.ok).toBe(true)
34 if (viaBearer.ok) {
35 expect(viaBearer.principal.kind).toBe('api-key')
36 expect(viaBearer.principal.userId).toBe(outcome.result.userId)
37 }
38
39 // X-Api-Key works too, and keys satisfy public capabilities.
40 const viaHeader = await requireAgent(
41 auth,
42 keyedRequest({ 'x-api-key': outcome.result.key }),
43 { capability: 'manage_subscriptions' },
44 )
45 expect(viaHeader.ok).toBe(true)
46
47 // ...but never privileged/unknown capabilities (no silent bypass).
48 const privileged = await requireAgent(
49 auth,
50 keyedRequest({ 'x-api-key': outcome.result.key }),
51 { capability: 'syncProvider' },
52 )
53 expect(privileged.ok).toBe(false)
54 if (!privileged.ok) {
55 expect(privileged.response.status).toBe(403)
56 const body = (await privileged.response.json()) as {
57 error: { code: string }
58 }
59 expect(body.error.code).toBe('capability_not_granted')
60 }
61 })
62
63 it('rejects invalid keys with a 401', async () => {
64 const auth = makeAuth()
65 const result = await requireAgent(
66 auth,
67 keyedRequest({ authorization: 'Bearer ms_not_a_real_key' }),
68 )
69 expect(result.ok).toBe(false)
70 if (!result.ok) {
71 expect(result.response.status).toBe(401)
72 const body = (await result.response.json()) as { error: { code: string } }
73 expect(body.error.code).toBe('invalid_api_key')
74 }
75 })
76
77 it('uses a custom email when provided and validates bodies', async () => {
78 const auth = makeAuth()
79 const outcome = await registerKeyAgent(auth, getDb(env), {
80 name: 'Mail Agent',
81 email: 'mail-agent@example.com',
82 })
83 expect(outcome.ok).toBe(true)
84
85 // Duplicate email → structured failure, not a throw.
86 const dup = await registerKeyAgent(auth, getDb(env), {
87 name: 'Mail Agent 2',
88 email: 'mail-agent@example.com',
89 })
90 expect(dup).toMatchObject({ ok: false, status: 409 })
91
92 expect(parseRegisterKeyBody({ name: 'x' })).toEqual({
93 name: 'x',
94 email: undefined,
95 })
96 expect(parseRegisterKeyBody({ name: ' ' })).toBeNull()
97 expect(parseRegisterKeyBody({})).toBeNull()
98 expect(parseRegisterKeyBody({ name: 'x', email: 5 })).toBeNull()
99 })
100})
101
102describe('agentsMe (task 5.5)', () => {
103 it('reports identity, grants, limits, and usage for an API key', async () => {
104 const { agentsMe } = await import('./agents-api.ts')
105 const auth = makeAuth()
106 const registered = await registerKeyAgent(auth, getDb(env), {
107 name: 'Me Agent',
108 })
109 expect(registered.ok).toBe(true)
110 if (!registered.ok) return
111
112 const response = await agentsMe(
113 auth,
114 env.SCHEMA_CACHE,
115 keyedRequest({ authorization: `Bearer ${registered.result.key}` }),
116 )
117 expect(response.status).toBe(200)
118 const body = (await response.json()) as {
119 agent: { kind: string; userId: string }
120 grants: Array<string>
121 limits: { requestsPerHour: number }
122 usage: { limit: number; remaining: number; resetAt: number }
123 }
124 expect(body.agent.kind).toBe('api-key')
125 expect(body.agent.userId).toBe(registered.result.userId)
126 expect(body.grants).toContain('getSchema')
127 expect(body.limits.requestsPerHour).toBe(5000)
128 expect(body.usage.limit).toBe(5000)
129 expect(body.usage.resetAt).toBeGreaterThan(0)
130 })
131
132 it('401s without credentials', async () => {
133 const { agentsMe } = await import('./agents-api.ts')
134 const response = await agentsMe(
135 makeAuth(),
136 env.SCHEMA_CACHE,
137 keyedRequest({}),
138 )
139 expect(response.status).toBe(401)
140 })
141})