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

require-agent.worker.test.ts

133 lines4.1 KB

1import { beforeAll, describe, expect, it } from 'vitest'
2import { env } from 'cloudflare:test'
3import { SignJWT, exportJWK, generateKeyPair } from 'jose'
4​
5import { getDb } from '../db/index.ts'
6import { createAuth } from '../lib/auth.ts'
7import type { Auth } from '../lib/auth.ts'
8import { requireAgent } from './require-agent.ts'
9​
10const BASE = 'http://agents.test'
11const ISSUER = `${BASE}/api/auth`
12​
13let auth: Auth
14let agentId: string
15let hostId: string
16let agentKeys: Awaited<ReturnType<typeof generateKeyPair>>
17​
18async function freshAgentJwt(): Promise<string> {
19 // jti is replay-protected — every request needs a fresh token.
20 return new SignJWT({ aud: `${ISSUER}/capability/execute` })
21 .setProtectedHeader({ alg: 'EdDSA', typ: 'agent+jwt' })
22 .setIssuer(hostId)
23 .setSubject(agentId)
24 .setIssuedAt()
25 .setJti(crypto.randomUUID())
26 .setExpirationTime('2m')
27 .sign(agentKeys.privateKey)
29​
30const protectedRequest = (headers: Record<string, string> = {}) =>
31 new Request(`${BASE}/v1/agents/me`, { headers })
32​
33beforeAll(async () => {
34 auth = createAuth(getDb(env), {
35 secret: 'vitest-only-better-auth-secret-0123456789',
36 baseUrl: BASE,
37 })
38​
39 const hostKeys = await generateKeyPair('Ed25519', { extractable: true })
40 agentKeys = await generateKeyPair('Ed25519', { extractable: true })
41 hostId = crypto.randomUUID()
42​
43 const hostJwt = await new SignJWT({
44 aud: ISSUER,
45 host_public_key: await exportJWK(hostKeys.publicKey),
46 agent_public_key: await exportJWK(agentKeys.publicKey),
47 })
48 .setProtectedHeader({ alg: 'EdDSA', typ: 'host+jwt' })
49 .setIssuer(hostId)
50 .setIssuedAt()
51 .setJti(crypto.randomUUID())
52 .setExpirationTime('5m')
53 .sign(hostKeys.privateKey)
54​
55 const response = await auth.handler(
56 new Request(`${ISSUER}/agent/register`, {
57 method: 'POST',
58 headers: {
59 'Content-Type': 'application/json',
60 Authorization: `Bearer ${hostJwt}`,
61 },
62 body: JSON.stringify({
63 name: 'require-agent-test',
64 mode: 'autonomous',
65 capabilities: ['getSchema'],
66 }),
67 }),
68 )
69 expect(response.ok).toBe(true)
70 const registration = (await response.json()) as {
71 agent_id?: string
72 host_id?: string
73 status?: string
74 }
75 expect(registration.status).toBe('active')
76 agentId = registration.agent_id ?? ''
77 hostId = registration.host_id ?? hostId
78 expect(agentId).not.toBe('')
79})
80​
81describe('requireAgent', () => {
82 it('authenticates a valid agent JWT (200 path)', async () => {
83 const result = await requireAgent(
84 auth,
85 protectedRequest({ authorization: `Bearer ${await freshAgentJwt()}` }),
86 )
87 expect(result.ok).toBe(true)
88 if (result.ok && result.principal.kind === 'agent') {
89 expect(result.principal.agentId).toBe(agentId)
90 expect(result.principal.mode).toBe('autonomous')
91 expect(result.principal.capabilities).toContain('getSchema')
92 } else {
93 expect.fail('expected an agent principal')
94 }
95 })
96​
97 it('rejects requests without a JWT (401)', async () => {
98 const result = await requireAgent(auth, protectedRequest())
99 expect(result.ok).toBe(false)
100 if (!result.ok) {
101 expect(result.response.status).toBe(401)
102 const body = (await result.response.json()) as {
103 error: { code: string }
104 }
105 expect(body.error.code).toBe('unauthorized')
106 }
107 })
108​
109 it('rejects garbage JWTs (401)', async () => {
110 const result = await requireAgent(
111 auth,
112 protectedRequest({ authorization: 'Bearer not.a.jwt' }),
113 )
114 expect(result.ok).toBe(false)
115 if (!result.ok) expect(result.response.status).toBe(401)
116 })
117​
118 it('enforces capability grants (403)', async () => {
119 const result = await requireAgent(
120 auth,
121 protectedRequest({ authorization: `Bearer ${await freshAgentJwt()}` }),
122 { capability: 'manage_subscriptions' },
123 )
124 expect(result.ok).toBe(false)
125 if (!result.ok) {
126 expect(result.response.status).toBe(403)
127 const body = (await result.response.json()) as {
128 error: { code: string }
129 }
130 expect(body.error.code).toBe('capability_not_granted')
131 }
132 })
133})