File size: 2,643 Bytes
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { afterEach, describe, expect, it, vi } from 'vitest';
import { ApiError, createApi, csrfMiddleware, getJson, readCookie, setCsrfToken, unwrap } from './client';

describe('api client', () => {
  afterEach(() => {
    setCsrfToken(null);
    vi.restoreAllMocks();
  });

  it('reads cookies', () => {
    expect(readCookie('fpt_csrf', 'a=1; fpt_csrf=tok%2B1; b=2')).toBe('tok+1');
    expect(readCookie('missing', 'a=1')).toBeNull();
  });

  it('adds the CSRF header only on unsafe methods', async () => {
    setCsrfToken('csrf-123');
    const post = new Request('http://x/api/runs', { method: 'POST' });
    const get = new Request('http://x/api/runs');
    const opts = {} as never;
    const p = (await csrfMiddleware.onRequest!({ request: post, schemaPath: '', params: {}, options: opts, id: '1' })) as Request;
    const g = (await csrfMiddleware.onRequest!({ request: get, schemaPath: '', params: {}, options: opts, id: '2' })) as Request;
    expect(p.headers.get('X-CSRF-Token')).toBe('csrf-123');
    expect(g.headers.get('X-CSRF-Token')).toBeNull();
  });

  it('sends typed requests and maps the backend error model to ApiError', async () => {
    const seen: Request[] = [];
    const fetchImpl = vi.fn(async (req: Request) => {
      seen.push(req);
      return new Response(JSON.stringify({ detail: 'kill switch engaged', code: 'KILL_SWITCH', request_id: 'rid1' }), {
        status: 423, headers: { 'Content-Type': 'application/json' },
      });
    }) as unknown as typeof fetch;
    setCsrfToken('t1');
    const api = createApi('http://localhost', fetchImpl);
    const err = await unwrap(api.POST('/api/runs', { body: { modules: ['P2P'], playwright_mode: 'stub', include_p2: false } })).catch((e: unknown) => e);
    expect(err).toBeInstanceOf(ApiError);
    expect((err as ApiError).status).toBe(423);
    expect((err as ApiError).code).toBe('KILL_SWITCH');
    expect((err as ApiError).requestId).toBe('rid1');
    expect(seen[0].headers.get('X-CSRF-Token')).toBe('t1');
    expect(await seen[0].json()).toEqual({ modules: ['P2P'], playwright_mode: 'stub', include_p2: false });
  });

  it('getJson returns null on 204 and throws on errors', async () => {
    vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(new Response(null, { status: 204 }));
    expect(await getJson('/api/runs/x/gate')).toBeNull();
    vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(new Response(JSON.stringify({ detail: 'no', code: 'FORBIDDEN' }), { status: 403 }));
    await expect(getJson('/api/audit')).rejects.toMatchObject({ status: 403, code: 'FORBIDDEN' });
  });
});