Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions agent-service-api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"type": "commonjs",
"dependencies": {
"@ibm-vibe/config": "*",
"@ibm-vibe/outbound-guard": "*",
"@ibm-vibe/utils": "*",
"axios": "^1.20.0",
"cors": "^2.8.5",
Expand Down
40 changes: 39 additions & 1 deletion agent-service-api/src/config/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ describe('agent-service-api config', () => {
loadAgentServiceApiConfig: jest.fn().mockReturnValue({
server: { port: 1234 },
backend: { url: 'http://backend.test' },
defaults: { requestTimeout: 1111, healthCheckInterval: 2222 }
defaults: { requestTimeout: 1111, healthCheckInterval: 2222 },
outbound: { allowLoopback: true, allowPrivateNetworks: false }
})
}));

Expand All @@ -16,4 +17,41 @@ describe('agent-service-api config', () => {
expect(config.DEFAULT_TIMEOUT).toBe(1111);
expect(config.HEALTH_CHECK_INTERVAL).toBe(2222);
});

it('denies this service port and the backend port for outbound requests', () => {
jest.resetModules();
jest.doMock('@ibm-vibe/config', () => ({
loadAgentServiceApiConfig: jest.fn().mockReturnValue({
server: { port: 5003 },
backend: { url: 'http://localhost:5100' },
defaults: { requestTimeout: 1111, healthCheckInterval: 2222 },
outbound: { allowLoopback: true, allowPrivateNetworks: false }
})
}));

const config = require('../index');

expect(config.OUTBOUND_CONFIG).toEqual({
allowLoopback: true,
allowPrivateNetworks: false,
denyPorts: [5003, 5100]
});
});

it('uses the scheme default port when the backend URL has none', () => {
jest.resetModules();
jest.doMock('@ibm-vibe/config', () => ({
loadAgentServiceApiConfig: jest.fn().mockReturnValue({
server: { port: 5003 },
backend: { url: 'https://backend.test' },
defaults: { requestTimeout: 1111, healthCheckInterval: 2222 },
outbound: { allowLoopback: false, allowPrivateNetworks: true }
})
}));

const config = require('../index');

expect(config.OUTBOUND_CONFIG.denyPorts).toEqual([5003, 443]);
expect(config.OUTBOUND_CONFIG.allowPrivateNetworks).toBe(true);
});
});
14 changes: 14 additions & 0 deletions agent-service-api/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,17 @@ export const BACKEND_CONFIG = agentServiceApiConfig.backend;
export const DEFAULT_TIMEOUT = agentServiceApiConfig.defaults.requestTimeout;
export const HEALTH_CHECK_INTERVAL = agentServiceApiConfig.defaults.healthCheckInterval;
export const POLLER_CONFIG = agentServiceApiConfig.poller;

const backendUrl = new URL(BACKEND_CONFIG.url);
const backendPort = backendUrl.port ? Number(backendUrl.port) : backendUrl.protocol === 'https:' ? 443 : 80;

/**
* Outbound guard settings. This service's own port and the backend port are always refused
* as outbound targets, even when loopback is allowed. Otherwise /execute-test could read back
* the backend's unauthenticated endpoints.
*/
export const OUTBOUND_CONFIG = {
allowLoopback: agentServiceApiConfig.outbound.allowLoopback,
allowPrivateNetworks: agentServiceApiConfig.outbound.allowPrivateNetworks,
denyPorts: [SERVER_CONFIG.port, backendPort]
};
63 changes: 63 additions & 0 deletions agent-service-api/src/services/__tests__/api-service.guard.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import axios from 'axios';
import { ApiService } from '../api-service';

jest.mock('axios');

jest.mock('@ibm-vibe/outbound-guard', () => {
const actual = jest.requireActual('@ibm-vibe/outbound-guard');
return {
...actual,
assertSafeOutboundUrl: jest.fn(actual.assertSafeOutboundUrl),
guardedAxiosOptions: jest.fn(() => ({ lookup: jest.fn(), maxRedirects: 0, proxy: false }))
};
});

const guard = jest.requireMock('@ibm-vibe/outbound-guard') as {
assertSafeOutboundUrl: jest.Mock;
guardedAxiosOptions: jest.Mock;
};
const mockedAxios = axios as jest.Mocked<typeof axios>;

describe('ApiService.makeApiRequest outbound guard', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('refuses a blocked literal before making any request', async () => {
const service = new ApiService() as any;

await expect(service.makeApiRequest('http://169.254.169.254/latest/', 'GET', {})).rejects.toMatchObject({
code: 'OUTBOUND_BLOCKED'
});
await expect(service.makeApiRequest('http://169.254.169.254/', 'POST', {})).rejects.toMatchObject({
code: 'OUTBOUND_BLOCKED'
});

expect(mockedAxios.get).not.toHaveBeenCalled();
expect(mockedAxios).not.toHaveBeenCalled();
});

it('applies guarded axios options to GET requests', async () => {
const service = new ApiService() as any;
mockedAxios.get.mockResolvedValue({ data: {} } as any);

await service.makeApiRequest('http://8.8.8.8/', 'GET', { q: 'x' });

expect(guard.assertSafeOutboundUrl).toHaveBeenCalledWith('http://8.8.8.8/', expect.any(Object));
expect(mockedAxios.get).toHaveBeenCalledWith(
expect.stringContaining('q=x'),
expect.objectContaining({ maxRedirects: 0, proxy: false, lookup: expect.any(Function) })
);
});

it('applies guarded axios options to non-GET requests', async () => {
const service = new ApiService() as any;
(mockedAxios as any).mockResolvedValue({ data: {} });

await service.makeApiRequest('http://8.8.8.8/', 'POST', { input: 'hi' });

expect(mockedAxios).toHaveBeenCalledWith(
expect.objectContaining({ maxRedirects: 0, proxy: false, lookup: expect.any(Function) })
);
});
});
8 changes: 6 additions & 2 deletions agent-service-api/src/services/api-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
ConversationExecutionResponse,
IntermediateStep
} from '@ibm-vibe/types';
import { DEFAULT_TIMEOUT } from '../config';
import { assertSafeOutboundUrl, guardedAxiosOptions } from '@ibm-vibe/outbound-guard';
import { DEFAULT_TIMEOUT, OUTBOUND_CONFIG } from '../config';
import { extractTokenUsage } from './token-extractor';
import {
escapeForJsonTemplate as escapeTemplateValue,
Expand Down Expand Up @@ -275,6 +276,8 @@ export class ApiService {
headers?: Record<string, string>,
apiKey?: string
): Promise<any> {
assertSafeOutboundUrl(endpoint, OUTBOUND_CONFIG);

const requestHeaders = {
'Content-Type': 'application/json',
...headers,
Expand All @@ -283,7 +286,8 @@ export class ApiService {

const config: AxiosRequestConfig = {
headers: requestHeaders,
timeout: DEFAULT_TIMEOUT
timeout: DEFAULT_TIMEOUT,
...guardedAxiosOptions(OUTBOUND_CONFIG)
};

const httpMethod = method || 'POST';
Expand Down
1 change: 1 addition & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"type": "commonjs",
"dependencies": {
"@ibm-vibe/config": "*",
"@ibm-vibe/outbound-guard": "*",
"@ibm-vibe/types": "*",
"@ibm-vibe/utils": "*",
"@types/better-sqlite3": "^7.6.12",
Expand Down
123 changes: 123 additions & 0 deletions backend/src/routes/__tests__/llm-configs.save-guard.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import type { Request, Response } from 'express';

jest.mock('../../db/queries');
jest.mock('../../services/llm-config-service');
jest.mock('../../utils/pagination');

import llmConfigsRouter from '../llm-configs';
import * as queries from '../../db/queries';

const mockCreateLLMConfig = queries.createLLMConfig as jest.MockedFunction<typeof queries.createLLMConfig>;
const mockUpdateLLMConfig = queries.updateLLMConfig as jest.MockedFunction<typeof queries.updateLLMConfig>;

const findHandler = (method: string, path: string) => {
const layer = (llmConfigsRouter as any).stack.find(
(l: any) => l.route && l.route.path === path && l.route.methods[method]
);
return layer.route.stack[0].handle;
};

const invoke = async (handler: any, body: any, params: Record<string, string> = {}) => {
const json = jest.fn();
const status = jest.fn().mockReturnThis();
const res = { json, status, send: jest.fn() } as unknown as Response;
await handler({ body, params, query: {} } as unknown as Request, res, jest.fn());
return { json, status };
};

describe('llm-configs save-time outbound checks', () => {
beforeEach(() => {
jest.clearAllMocks();
mockCreateLLMConfig.mockImplementation((config: any) => ({ id: 1, ...config }) as any);
mockUpdateLLMConfig.mockImplementation((id: number, updates: any) => ({ id, ...updates }) as any);
});

describe('POST /', () => {
it('rejects a malformed base_url with 400 and does not save', async () => {
const post = findHandler('post', '/');
const { status, json } = await invoke(post, {
name: 'x',
provider: 'ollama',
config: { base_url: 'not a url' }
});

expect(status).toHaveBeenCalledWith(400);
expect(json).toHaveBeenCalledWith({ error: expect.stringContaining('base_url') });
expect(mockCreateLLMConfig).not.toHaveBeenCalled();
});

it('rejects a non-http scheme with 400 when config is a JSON string', async () => {
const post = findHandler('post', '/');
const { status } = await invoke(post, {
name: 'x',
provider: 'ollama',
config: JSON.stringify({ base_url: 'file:///etc/passwd' })
});

expect(status).toHaveBeenCalledWith(400);
expect(mockCreateLLMConfig).not.toHaveBeenCalled();
});

it('saves but warns when base_url is a policy-blocked literal', async () => {
const post = findHandler('post', '/');
const { status, json } = await invoke(post, {
name: 'x',
provider: 'ollama',
config: { base_url: 'http://169.254.169.254' }
});

expect(status).toHaveBeenCalledWith(201);
expect(mockCreateLLMConfig).toHaveBeenCalled();
expect(json).toHaveBeenCalledWith(
expect.objectContaining({
warnings: [expect.stringContaining('base_url')]
})
);
});

it('saves without warnings when base_url is allowed', async () => {
const post = findHandler('post', '/');
const { status, json } = await invoke(post, {
name: 'x',
provider: 'ollama',
config: { base_url: 'https://8.8.8.8' }
});

expect(status).toHaveBeenCalledWith(201);
expect(json.mock.calls[0][0].warnings).toBeUndefined();
});

it('saves a config without base_url unchanged', async () => {
const post = findHandler('post', '/');
const { status } = await invoke(post, { name: 'x', provider: 'openai', config: { api_key: 'k' } });

expect(status).toHaveBeenCalledWith(201);
});
});

describe('PUT /:id', () => {
it('rejects a malformed base_url with 400 and does not update', async () => {
const put = findHandler('put', '/:id');
const { status } = await invoke(put, { config: { base_url: 'not a url' } }, { id: '3' });

expect(status).toHaveBeenCalledWith(400);
expect(mockUpdateLLMConfig).not.toHaveBeenCalled();
});

it('updates without validation when config is not part of the request', async () => {
const put = findHandler('put', '/:id');
const { status } = await invoke(put, { name: 'renamed' }, { id: '3' });

expect(mockUpdateLLMConfig).toHaveBeenCalledWith(3, expect.objectContaining({ name: 'renamed' }));
expect(status).not.toHaveBeenCalledWith(400);
});

it('warns on a policy-blocked base_url but still updates', async () => {
const put = findHandler('put', '/:id');
const { json } = await invoke(put, { config: { base_url: 'http://10.0.0.5' } }, { id: '3' });

expect(mockUpdateLLMConfig).toHaveBeenCalled();
expect(json).toHaveBeenCalledWith(expect.objectContaining({ warnings: [expect.any(String)] }));
});
});
});
Loading
Loading