api/tests/app.test.ts

196 lines · 6546 bytes

3 symbols in this file
  • app const, line 5
  • env const, line 6
  • hit const, line 8
  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('trackers uses its own limit, not the shared enrich one', async () => {
 99    const enrich = denyLimiter()
100    const trackers = denyLimiter()
101    const res = await app.fetch(
102      new Request('http://localhost/v1/enrich/trackers?url=https://example.com'),
103      {
104        API_TOKEN: 'test',
105        ENRICH_RATE_LIMIT: enrich.limiter,
106        TRACKERS_RATE_LIMIT: trackers.limiter,
107      },
108    )
109    expect(res.status).toBe(429)
110    expect([enrich.calls.n, trackers.calls.n]).toEqual([0, 1])
111  })
112
113  it('wrong token does not bypass the enrich rate limit', async () => {
114    const { limiter, calls } = denyLimiter()
115    const res = await app.fetch(
116      new Request('http://localhost/v1/enrich/privacy/1', {
117        headers: { authorization: 'Bearer wrong' },
118      }),
119      { API_TOKEN: 'test', ENRICH_RATE_LIMIT: limiter },
120    )
121    expect(res.status).toBe(429)
122    expect(calls.n).toBe(1)
123  })
124
125  it('REQUIRE_AUTH rejects missing/invalid token with 401', async () => {
126    const env = { API_TOKEN: 'test', REQUIRE_AUTH: 'true' }
127    expect(
128      (await app.fetch(new Request('http://localhost/v1/enrich/privacy/1'), env)).status,
129    ).toBe(401)
130    const wrong = await app.fetch(
131      new Request('http://localhost/v1/enrich/privacy/1', {
132        headers: { authorization: 'Bearer wrong' },
133      }),
134      env,
135    )
136    expect(wrong.status).toBe(401)
137  })
138
139  it('REQUIRE_AUTH still admits a valid token', async () => {
140    const res = await app.fetch(
141      new Request('http://localhost/v1/enrich/privacy/1', {
142        headers: { authorization: 'Bearer test' },
143      }),
144      { API_TOKEN: 'test', REQUIRE_AUTH: 'true', CACHE: seededCache({ id: 1 }) },
145    )
146    expect(res.status).toBe(200)
147  })
148})
149
150describe('middleware scoping', () => {
151  it('public routes are edge cacheable', async () => {
152    const res = await hit('/v1/stats')
153    expect(res.headers.get('cache-control')).toBe('public, s-maxage=300')
154  })
155
156  it('enrich routes are not advertised as public cacheable', async () => {
157    // Seed the cache so the handler serves without an upstream call
158    const cache = {
159      get: async () => ({ value: { id: 1 }, cachedAt: Date.now() }),
160      put: async () => {},
161    }
162    const res = await app.fetch(new Request('http://localhost/v1/enrich/privacy/1'), {
163      API_TOKEN: 'test',
164      CACHE: cache,
165    })
166    expect(res.headers.get('cache-control') ?? '').not.toContain('public')
167  })
168})
169
170describe('mcp', () => {
171  it('lists tools', async () => {
172    const res = await hit('/v1/mcp', {
173      method: 'POST',
174      headers: { 'content-type': 'application/json' },
175      body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
176    })
177    const body = (await res.json()) as any
178    expect(body.result.tools.length).toBeGreaterThan(0)
179  })
180
181  it('runs get_service tool', async () => {
182    const res = await hit('/v1/mcp', {
183      method: 'POST',
184      headers: { 'content-type': 'application/json' },
185      body: JSON.stringify({
186        jsonrpc: '2.0',
187        id: 2,
188        method: 'tools/call',
189        params: { name: 'get_service', arguments: { slug: 'bitwarden' } },
190      }),
191    })
192    const body = (await res.json()) as any
193    const out = JSON.parse(body.result.content[0].text)
194    expect(out.name).toBe('Bitwarden')
195  })
196})