api/tests/app.test.ts

181 lines · 6044 bytes

  1// Integration tests against the assembled app (no upstream calls)
  2import { describe, it, expect } from 'vitest'
  3import { buildApp } from '../src/app'
  4
  5const app = buildApp()
  6const env = { API_TOKEN: 'test' }
  7
  8const hit = (path: string, init?: RequestInit) =>
  9  app.fetch(new Request(`http://localhost${path}`, init), env)
 10
 11describe('public routes', () => {
 12  it('health returns ok envelope', async () => {
 13    const res = await hit('/v1/health')
 14    expect(res.status).toBe(200)
 15    expect(await res.json()).toMatchObject({ data: { status: 'ok' } })
 16  })
 17
 18  it('stats has positive counts', async () => {
 19    const res = await hit('/v1/stats')
 20    const { data } = (await res.json()) as any
 21    expect(data.categories).toBeGreaterThan(0)
 22    expect(data.services).toBeGreaterThan(0)
 23  })
 24
 25  it('categories returns wrapped list', async () => {
 26    const res = await hit('/v1/categories')
 27    const body = (await res.json()) as any
 28    expect(Array.isArray(body.data)).toBe(true)
 29    expect(body.data[0]).toHaveProperty('slug')
 30  })
 31
 32  it('unknown service returns NOT_FOUND envelope', async () => {
 33    const res = await hit('/v1/services/nope-nope')
 34    expect(res.status).toBe(404)
 35    expect(await res.json()).toMatchObject({ error: { code: 'NOT_FOUND' } })
 36  })
 37
 38  it('search without q returns BAD_REQUEST envelope', async () => {
 39    const res = await hit('/v1/search')
 40    expect(res.status).toBe(400)
 41    expect(await res.json()).toMatchObject({ error: { code: 'BAD_REQUEST' } })
 42  })
 43
 44  it('search returns results for known term', async () => {
 45    const res = await hit('/v1/search?q=password&limit=3')
 46    const body = (await res.json()) as any
 47    expect(body.data.length).toBeGreaterThan(0)
 48  })
 49
 50  it('services paginates', async () => {
 51    const res = await hit('/v1/services?limit=5')
 52    const body = (await res.json()) as any
 53    expect(body.data).toHaveLength(5)
 54    expect(body.pagination).toMatchObject({ page: 1, limit: 5, hasMore: true })
 55  })
 56})
 57
 58describe('enrich rate limiting', () => {
 59  // A limiter that always denies, recording how many times it was consulted
 60  const denyLimiter = () => {
 61    const calls = { n: 0 }
 62    const limiter = {
 63      limit: async () => {
 64        calls.n++
 65        return { success: false }
 66      },
 67    }
 68    return { limiter, calls }
 69  }
 70  // A KV cache pre-seeded so handlers serve cached data without any upstream call
 71  const seededCache = (value: unknown) => ({
 72    get: async () => ({ value, cachedAt: Date.now() }),
 73    put: async () => {},
 74  })
 75
 76  it('anonymous enrich request is rate-limited', async () => {
 77    const { limiter, calls } = denyLimiter()
 78    const res = await app.fetch(new Request('http://localhost/v1/enrich/privacy/1'), {
 79      API_TOKEN: 'test',
 80      ENRICH_RATE_LIMIT: limiter,
 81    })
 82    expect(res.status).toBe(429)
 83    expect(calls.n).toBe(1)
 84  })
 85
 86  it('valid bearer token bypasses the enrich rate limit', async () => {
 87    const { limiter, calls } = denyLimiter()
 88    const res = await app.fetch(
 89      new Request('http://localhost/v1/enrich/privacy/1', {
 90        headers: { authorization: 'Bearer test' },
 91      }),
 92      { API_TOKEN: 'test', ENRICH_RATE_LIMIT: limiter, CACHE: seededCache({ id: 1 }) },
 93    )
 94    expect(res.status).toBe(200)
 95    expect(calls.n).toBe(0)
 96  })
 97
 98  it('wrong token does not bypass the enrich rate limit', async () => {
 99    const { limiter, calls } = denyLimiter()
100    const res = await app.fetch(
101      new Request('http://localhost/v1/enrich/privacy/1', {
102        headers: { authorization: 'Bearer wrong' },
103      }),
104      { API_TOKEN: 'test', ENRICH_RATE_LIMIT: limiter },
105    )
106    expect(res.status).toBe(429)
107    expect(calls.n).toBe(1)
108  })
109
110  it('REQUIRE_AUTH rejects missing/invalid token with 401', async () => {
111    const env = { API_TOKEN: 'test', REQUIRE_AUTH: 'true' }
112    expect(
113      (await app.fetch(new Request('http://localhost/v1/enrich/privacy/1'), env)).status,
114    ).toBe(401)
115    const wrong = await app.fetch(
116      new Request('http://localhost/v1/enrich/privacy/1', {
117        headers: { authorization: 'Bearer wrong' },
118      }),
119      env,
120    )
121    expect(wrong.status).toBe(401)
122  })
123
124  it('REQUIRE_AUTH still admits a valid token', async () => {
125    const res = await app.fetch(
126      new Request('http://localhost/v1/enrich/privacy/1', {
127        headers: { authorization: 'Bearer test' },
128      }),
129      { API_TOKEN: 'test', REQUIRE_AUTH: 'true', CACHE: seededCache({ id: 1 }) },
130    )
131    expect(res.status).toBe(200)
132  })
133})
134
135describe('middleware scoping', () => {
136  it('public routes are edge cacheable', async () => {
137    const res = await hit('/v1/stats')
138    expect(res.headers.get('cache-control')).toBe('public, s-maxage=300')
139  })
140
141  it('enrich routes are not advertised as public cacheable', async () => {
142    // Seed the cache so the handler serves without an upstream call
143    const cache = {
144      get: async () => ({ value: { id: 1 }, cachedAt: Date.now() }),
145      put: async () => {},
146    }
147    const res = await app.fetch(new Request('http://localhost/v1/enrich/privacy/1'), {
148      API_TOKEN: 'test',
149      CACHE: cache,
150    })
151    expect(res.headers.get('cache-control') ?? '').not.toContain('public')
152  })
153})
154
155describe('mcp', () => {
156  it('lists tools', async () => {
157    const res = await hit('/v1/mcp', {
158      method: 'POST',
159      headers: { 'content-type': 'application/json' },
160      body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
161    })
162    const body = (await res.json()) as any
163    expect(body.result.tools.length).toBeGreaterThan(0)
164  })
165
166  it('runs get_service tool', async () => {
167    const res = await hit('/v1/mcp', {
168      method: 'POST',
169      headers: { 'content-type': 'application/json' },
170      body: JSON.stringify({
171        jsonrpc: '2.0',
172        id: 2,
173        method: 'tools/call',
174        params: { name: 'get_service', arguments: { slug: 'bitwarden' } },
175      }),
176    })
177    const body = (await res.json()) as any
178    const out = JSON.parse(body.result.content[0].text)
179    expect(out.name).toBe('Bitwarden')
180  })
181})