SPB Git

Repository Public

gateway.test.ts 8.4 KB 138 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : SP Wallet8 * File             : services/research-runner/test/gateway.test.ts9 * Module           : services10 * Repository       : https://git.spboucher.ai/sp-wallet11 * Project Website  : https://wallet.spboucher.ai12 * Created          : 2026-11-1113 * Last Modified    : 2026-11-1114 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// The model gateway of a job against a fake model API (a local HTTP server): the only paths, the per-job key, the44// credential swap (the agent never holds the real one), the refusal of web / code-execution server tools, token counting on45// plain and streamed answers, and the token budget.46import { createServer, type Server } from 'node:http';47import { afterAll, beforeAll, describe, expect, it } from 'vitest';48import { ModelGateway } from '../src/gateway.ts';4950let upstream: Server, upstreamUrl = '';51const seen: { path: string; headers: Record<string, unknown>; body: any }[] = [];52beforeAll(async () => {53  upstream = createServer((req, res) => {54    const chunks: Buffer[] = [];55    req.on('data', (c: Buffer) => chunks.push(c));56    req.on('end', () => {57      const body = JSON.parse(Buffer.concat(chunks).toString() || '{}');58      seen.push({ path: req.url ?? '', headers: req.headers, body });59      if (req.url === '/v1/messages/count_tokens') { res.writeHead(200, { 'content-type': 'application/json' }).end('{"input_tokens":999}'); return; }60      if (body.stream) {61        res.writeHead(200, { 'content-type': 'text/event-stream' });62        res.write('event: message_start\ndata: {"type":"message_start","message":{"usage":{"input_tokens":100,"cache_read_input_tokens":40,"cache_creation_input_tokens":10,"output_tokens":1}}}\n\n');63        res.write('event: content_block_delta\ndata: {"type":"content_block_delta","delta":{"type":"text_delta","text":"hi"}}\n\n');64        res.end('event: message_delta\ndata: {"type":"message_delta","usage":{"output_tokens":50}}\n\nevent: message_stop\ndata: {"type":"message_stop"}\n\n');65        return;66      }67      res.writeHead(200, { 'content-type': 'application/json', 'set-cookie': 'x=1' }).end(JSON.stringify({ type: 'message', content: [{ type: 'text', text: 'ok' }], usage: { input_tokens: 20, output_tokens: 5 } }));68    });69  });70  await new Promise<void>((r) => upstream.listen(0, '127.0.0.1', r));71  upstreamUrl = `http://127.0.0.1:${(upstream.address() as { port: number }).port}`;72});73afterAll(() => { upstream.close(); });7475const make = async (maxTokens = 1000) => { const g = new ModelGateway({ upstream: upstreamUrl, credential: ['x-api-key', 'REAL-RUNNER-CREDENTIAL'], jobKey: 'job-placeholder', maxTokens }); await g.start(); return g; };76const call = (g: ModelGateway, path: string, body: unknown, o: { key?: string; method?: string; headers?: Record<string, string> } = {}) =>77  fetch(`http://127.0.0.1:${g.port}${path}`, { method: o.method ?? 'POST', headers: { 'content-type': 'application/json', 'x-api-key': o.key ?? 'job-placeholder', 'anthropic-version': '2023-06-01', ...(o.headers ?? {}) }, body: o.method === 'GET' ? undefined : JSON.stringify(body) });7879describe('model gateway', () => {80  it('serves only the message endpoints, only to the job key', async () => {81    const g = await make();82    for (const [m, p] of [['GET', '/v1/messages'], ['POST', '/v1/files'], ['POST', '/v1/messages/batches'], ['GET', '/'], ['POST', '/api/v1/agents'], ['GET', '/v1/models']] as const)83      expect((await call(g, p, {}, { method: m })).status, `${m} ${p}`).toBe(404);84    expect((await call(g, '/v1/messages', { messages: [] }, { key: 'wrong' })).status).toBe(401);85    expect((await call(g, '/v1/messages', { messages: [] }, { key: '' })).status).toBe(401);86    expect(g.usage.requests).toBe(0);87    expect(g.usage.refused).toBe(8);88    expect(seen).toHaveLength(0);                                       // nothing reached the model API89    await g.stop();90  });9192  it('replaces the credentials: the upstream sees the runner\'s, never the placeholder, a cookie or an authorization of the agent', async () => {93    const g = await make();94    const r = await call(g, '/v1/messages', { model: 'm', messages: [{ role: 'user', content: 'x' }] }, { headers: { authorization: 'Bearer agent-made-this-up', cookie: 'a=b', 'anthropic-beta': 'some-beta' } });95    expect(r.status).toBe(200);96    expect(r.headers.get('set-cookie')).toBeNull();97    const last = seen.at(-1)!;98    expect(last.headers['x-api-key']).toBe('REAL-RUNNER-CREDENTIAL');99    expect(last.headers.authorization).toBeUndefined(); expect(last.headers.cookie).toBeUndefined();100    expect(last.headers['anthropic-beta']).toBe('some-beta'); expect(last.headers['anthropic-version']).toBe('2023-06-01');101    expect(JSON.stringify(last)).not.toContain('job-placeholder');102    await g.stop();103  });104105  it('refuses server-side tools that reach the web or run code elsewhere, and remote MCP servers; client tools pass', async () => {106    const g = await make(), before = seen.length;107    for (const type of ['web_search_20250305', 'web_fetch_20250910', 'code_execution_20250825', 'mcp_toolset'])108      expect((await call(g, '/v1/messages', { tools: [{ type, name: 'x' }], messages: [] })).status, type).toBe(403);109    expect((await call(g, '/v1/messages', { mcp_servers: [{ url: 'https://evil.example' }], messages: [] })).status).toBe(403);110    expect((await call(g, '/v1/messages', 'not json')).status).toBe(200); // a JSON string is JSON; it has no tools111    expect(seen.length).toBe(before + 1);112    expect((await call(g, '/v1/messages', { tools: [{ name: 'Bash', description: 'd', input_schema: { type: 'object' } }, { type: 'custom', name: 'Read', input_schema: {} }], messages: [] })).status).toBe(200);113    await g.stop();114  });115116  it('counts tokens of plain and streamed answers (count_tokens is free) and stops serving when the budget is spent', async () => {117    const g = await make(230);118    await (await call(g, '/v1/messages', { messages: [] })).text();119    expect(g.usage).toMatchObject({ inputTokens: 20, outputTokens: 5, total: 25, exhausted: false });120    await (await call(g, '/v1/messages/count_tokens', { messages: [] })).text();121    expect(g.usage.total).toBe(25);122    const body = await (await call(g, '/v1/messages', { stream: true, messages: [] })).text();123    expect(body).toContain('message_stop');                             // the stream is passed through untouched124    expect(g.usage).toMatchObject({ inputTokens: 120, outputTokens: 56, cacheTokens: 50, total: 226, exhausted: false });125    await (await call(g, '/v1/messages', { messages: [] })).text();126    expect(g.usage).toMatchObject({ total: 251, exhausted: true });127    const refused = await call(g, '/v1/messages', { messages: [] });128    expect(refused.status).toBe(429);129    expect(((await refused.json()) as { error: { message: string } }).error.message).toMatch(/token budget of this research job is spent/);130    await g.stop();131  });132133  it('only talks to an https upstream (plain http is for a loopback fake)', () => {134    expect(() => new ModelGateway({ upstream: 'http://api.example.com', credential: null, jobKey: 'k', maxTokens: 1 })).toThrow(/must be https/);135    expect(() => new ModelGateway({ upstream: 'https://api.anthropic.com', credential: null, jobKey: 'k', maxTokens: 1 })).not.toThrow();136  });137});138
Files main
Menu

Theme