fix(server): send the session token on the sidecar's calls to its own proxy (UF-044)
Since the server stopped trusting loopback callers, the built-in model proxy needs the session token like every other route, but the sidecar's own calls to it sent none. The Models key check read the proxy's 401 as a rejected key, so a working Anthropic key showed "Key found but not responding". Scheduled AI tasks and loops, the dream diary narrative and the profile calls failed the same way; the profile calls also built the port from address().toString(), and the scheduled tasks used the configured port, which the desktop app's port fallback can leave pointing at another Waggle server. self-request.ts now builds the address from the bound port and adds the session token; all these calls and command.ts use it, and the token is never sent to Ollama. An end-to-end test runs the key check through the real middleware and proxy with localhost trust off; it fails without the fix. UF-045 records the persona generator, which posts to a route that does not exist; it is left open.
This commit is contained in:
63
packages/server/tests/local/probe-model-proxy.test.ts
Normal file
63
packages/server/tests/local/probe-model-proxy.test.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* UF-044 end to end: the Models screen's key check goes through this server's
|
||||
* own auth middleware and built-in proxy. Only the upstream Anthropic call is
|
||||
* faked, so a check that reaches the proxy without the session token fails here.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { buildLocalServer } from '../../src/local/index.js';
|
||||
import { injectWithAuth } from '../test-utils.js';
|
||||
|
||||
describe('probe-model through the built-in proxy (UF-044)', () => {
|
||||
let server: FastifyInstance;
|
||||
let tmpDir: string;
|
||||
const realFetch = globalThis.fetch;
|
||||
const priorTrustLocalhost = process.env.WAGGLE_TRUST_LOCALHOST;
|
||||
|
||||
beforeAll(async () => {
|
||||
// The production default: loopback callers need the session token too.
|
||||
// vitest.setup.ts turns localhost trust on for the older suites.
|
||||
process.env.WAGGLE_TRUST_LOCALHOST = '0';
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-probe-proxy-'));
|
||||
server = await buildLocalServer({ dataDir: tmpDir });
|
||||
await server.listen({ port: 0, host: '127.0.0.1' });
|
||||
server.vault.set('anthropic', 'sk-ant-test-key');
|
||||
});
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
afterAll(async () => {
|
||||
await server.close();
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
if (priorTrustLocalhost === undefined) delete process.env.WAGGLE_TRUST_LOCALHOST;
|
||||
else process.env.WAGGLE_TRUST_LOCALHOST = priorTrustLocalhost;
|
||||
});
|
||||
|
||||
it('verifies a working key', async () => {
|
||||
const upstream = vi.fn(async () => new Response(JSON.stringify({
|
||||
id: 'msg_probe',
|
||||
type: 'message',
|
||||
role: 'assistant',
|
||||
model: 'claude-haiku-4-5',
|
||||
content: [{ type: 'text', text: 'h' }],
|
||||
stop_reason: 'max_tokens',
|
||||
usage: { input_tokens: 1, output_tokens: 1 },
|
||||
}), { status: 200, headers: { 'content-type': 'application/json' } }));
|
||||
vi.stubGlobal('fetch', (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
|
||||
return url.startsWith('https://api.anthropic.com/') ? upstream() : realFetch(input, init);
|
||||
});
|
||||
|
||||
const res = await injectWithAuth(server, {
|
||||
method: 'POST',
|
||||
url: '/api/settings/probe-model',
|
||||
payload: { model: 'claude-haiku-4-5' },
|
||||
});
|
||||
|
||||
expect(JSON.parse(res.body)).toMatchObject({ configured: true, verified: true });
|
||||
expect(upstream).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
43
packages/server/tests/local/self-request.test.ts
Normal file
43
packages/server/tests/local/self-request.test.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* UF-044 — requests the sidecar sends to its own routes must carry the session
|
||||
* token (the server does not trust loopback callers) and target the port the
|
||||
* server is actually bound to.
|
||||
*/
|
||||
import { describe, it, expect, afterEach } from 'vitest';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { selfBaseUrl, selfRequestHeaders } from '../../src/local/self-request.js';
|
||||
|
||||
function fakeServer(address: unknown, token: string | undefined): FastifyInstance {
|
||||
return {
|
||||
server: { address: () => address },
|
||||
agentState: { wsSessionToken: token },
|
||||
} as unknown as FastifyInstance;
|
||||
}
|
||||
|
||||
describe('self requests (UF-044)', () => {
|
||||
const priorPort = process.env.WAGGLE_PORT;
|
||||
afterEach(() => {
|
||||
if (priorPort === undefined) delete process.env.WAGGLE_PORT;
|
||||
else process.env.WAGGLE_PORT = priorPort;
|
||||
});
|
||||
|
||||
it('targets the port the server is bound to', () => {
|
||||
process.env.WAGGLE_PORT = '3333';
|
||||
const server = fakeServer({ address: '127.0.0.1', family: 'IPv4', port: 53204 }, 't');
|
||||
expect(selfBaseUrl(server)).toBe('http://127.0.0.1:53204');
|
||||
});
|
||||
|
||||
it('falls back to WAGGLE_PORT, then 3333, before the server listens', () => {
|
||||
process.env.WAGGLE_PORT = '4100';
|
||||
expect(selfBaseUrl(fakeServer(null, 't'))).toBe('http://127.0.0.1:4100');
|
||||
delete process.env.WAGGLE_PORT;
|
||||
expect(selfBaseUrl(fakeServer(null, 't'))).toBe('http://127.0.0.1:3333');
|
||||
});
|
||||
|
||||
it('sends the session token as a bearer credential', () => {
|
||||
expect(selfRequestHeaders(fakeServer(null, 'session-123'))).toEqual({
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer session-123',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -752,6 +752,27 @@ describe('Workspace & Session API', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('probe-model sends the session token to the built-in proxy (UF-044)', async () => {
|
||||
const restoreModel = configureExactProbeModel();
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response('{}', { status: 200 }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
try {
|
||||
await injectWithAuth(server, {
|
||||
method: 'POST',
|
||||
url: '/api/settings/probe-model',
|
||||
payload: { model: exactProbeModel },
|
||||
});
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/v1\/chat\/completions$/);
|
||||
expect(init.headers).toMatchObject({
|
||||
Authorization: `Bearer ${server.agentState.wsSessionToken}`,
|
||||
});
|
||||
} finally {
|
||||
restoreModel();
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it('probe-model reports rejected on a 401 from the model endpoint', async () => {
|
||||
const restoreModel = configureExactProbeModel();
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('unauthorized', { status: 401 })));
|
||||
|
||||
Reference in New Issue
Block a user