From 8632813c168bf46d50735c7d976b2bfb4f861380 Mon Sep 17 00:00:00 2001 From: Zvonimir Fras Date: Thu, 26 Nov 2026 19:21:51 -0500 Subject: [PATCH] fix(security): guard caller-controlled outbound URLs Agent api_endpoint and LLM config base_url are caller-controlled, and the services previously sent requests to any address they were given. That allowed SSRF to cloud metadata and internal hosts, and the /execute-test response returned the body to the caller. Add @ibm-vibe/outbound-guard, a Node-only package that: - refuses non-http(s) schemes and malformed URLs before any request - classifies IP literals (including IPv4-mapped, NAT64, 6to4, and alternate IPv4 spellings) and refuses always-blocked ranges - refuses private and loopback ranges per policy - resolves hostnames through a lookup guard that rejects any blocked address, closing DNS rebinding for the connected address - disables redirects and proxy handling for guarded requests Policy is set by OUTBOUND_ALLOW_LOOPBACK (default true) and OUTBOUND_ALLOW_PRIVATE_NETWORKS (default false). The agent service always refuses its own port and the backend port, so /execute-test cannot read back the backend's unauthenticated endpoints. Save-time: POST/PUT /api/llm-configs reject malformed base_url with 400 and warn on policy-blocked addresses. The call-time guard remains authoritative. Behaviour changes: outbound requests no longer follow redirects, and ignore HTTP_PROXY/HTTPS_PROXY. Stored rows written before this change are validated at call time only. Signed-off-by: Zvonimir Fras --- agent-service-api/package.json | 1 + .../src/config/__tests__/index.test.ts | 40 ++- agent-service-api/src/config/index.ts | 14 + .../__tests__/api-service.guard.test.ts | 63 ++++ agent-service-api/src/services/api-service.ts | 8 +- backend/package.json | 1 + .../__tests__/llm-configs.save-guard.test.ts | 123 ++++++++ backend/src/routes/llm-configs.ts | 63 +++- .../llm-config-service.guard.test.ts | 56 ++++ .../__tests__/llm-config-service.test.ts | 18 +- backend/src/services/llm-config-service.ts | 42 ++- package-lock.json | 16 + package.json | 6 +- packages/config/src/index.ts | 27 +- packages/outbound-guard/jest.config.js | 15 + packages/outbound-guard/package.json | 17 ++ .../src/__tests__/outbound-guard.test.ts | 287 ++++++++++++++++++ packages/outbound-guard/src/index.ts | 206 +++++++++++++ packages/outbound-guard/tsconfig.json | 16 + 19 files changed, 987 insertions(+), 32 deletions(-) create mode 100644 agent-service-api/src/services/__tests__/api-service.guard.test.ts create mode 100644 backend/src/routes/__tests__/llm-configs.save-guard.test.ts create mode 100644 backend/src/services/__tests__/llm-config-service.guard.test.ts create mode 100644 packages/outbound-guard/jest.config.js create mode 100644 packages/outbound-guard/package.json create mode 100644 packages/outbound-guard/src/__tests__/outbound-guard.test.ts create mode 100644 packages/outbound-guard/src/index.ts create mode 100644 packages/outbound-guard/tsconfig.json diff --git a/agent-service-api/package.json b/agent-service-api/package.json index 2d53ff7..b4c03d1 100644 --- a/agent-service-api/package.json +++ b/agent-service-api/package.json @@ -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", diff --git a/agent-service-api/src/config/__tests__/index.test.ts b/agent-service-api/src/config/__tests__/index.test.ts index f1dbb4b..6afeee0 100644 --- a/agent-service-api/src/config/__tests__/index.test.ts +++ b/agent-service-api/src/config/__tests__/index.test.ts @@ -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 } }) })); @@ -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); + }); }); diff --git a/agent-service-api/src/config/index.ts b/agent-service-api/src/config/index.ts index f2f5f68..d814709 100644 --- a/agent-service-api/src/config/index.ts +++ b/agent-service-api/src/config/index.ts @@ -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] +}; diff --git a/agent-service-api/src/services/__tests__/api-service.guard.test.ts b/agent-service-api/src/services/__tests__/api-service.guard.test.ts new file mode 100644 index 0000000..45e6db8 --- /dev/null +++ b/agent-service-api/src/services/__tests__/api-service.guard.test.ts @@ -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; + +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) }) + ); + }); +}); diff --git a/agent-service-api/src/services/api-service.ts b/agent-service-api/src/services/api-service.ts index c31144f..a5cf118 100644 --- a/agent-service-api/src/services/api-service.ts +++ b/agent-service-api/src/services/api-service.ts @@ -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, @@ -275,6 +276,8 @@ export class ApiService { headers?: Record, apiKey?: string ): Promise { + assertSafeOutboundUrl(endpoint, OUTBOUND_CONFIG); + const requestHeaders = { 'Content-Type': 'application/json', ...headers, @@ -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'; diff --git a/backend/package.json b/backend/package.json index 7323bc1..795c812 100644 --- a/backend/package.json +++ b/backend/package.json @@ -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", diff --git a/backend/src/routes/__tests__/llm-configs.save-guard.test.ts b/backend/src/routes/__tests__/llm-configs.save-guard.test.ts new file mode 100644 index 0000000..50cecce --- /dev/null +++ b/backend/src/routes/__tests__/llm-configs.save-guard.test.ts @@ -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; +const mockUpdateLLMConfig = queries.updateLLMConfig as jest.MockedFunction; + +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 = {}) => { + 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)] })); + }); + }); +}); diff --git a/backend/src/routes/llm-configs.ts b/backend/src/routes/llm-configs.ts index 40dd8be..f899c50 100644 --- a/backend/src/routes/llm-configs.ts +++ b/backend/src/routes/llm-configs.ts @@ -7,6 +7,54 @@ import { hasPaginationParams, validatePaginationOrError } from '../utils/paginat import { asyncHandler } from '../lib/asyncHandler'; import { logError } from '../lib/logger'; import { parseIdParam } from '../lib/routeHelpers'; +import { assertSafeOutboundUrl, OutboundBlockedError } from '@ibm-vibe/outbound-guard'; + +const parseHttpUrl = (value: string): URL | null => { + try { + const url = new URL(value); + return url.protocol === 'http:' || url.protocol === 'https:' ? url : null; + } catch { + return null; + } +}; + +const readBaseUrl = (config: unknown): unknown => { + let parsed = config; + if (typeof config === 'string') { + try { + parsed = JSON.parse(config); + } catch { + return undefined; + } + } + return parsed && typeof parsed === 'object' ? (parsed as { base_url?: unknown }).base_url : undefined; +}; + +/** + * Validates a config's base_url at save time. Malformed URLs and non-http(s) schemes are + * rejected. A policy-blocked address is saved with a warning, because the call-time guard + * is authoritative. DNS is never resolved here. + */ +const checkBaseUrlForSave = (config: unknown): { error?: string; warnings: string[] } => { + const baseUrl = readBaseUrl(config); + if (baseUrl === undefined || baseUrl === '') { + return { warnings: [] }; + } + if (typeof baseUrl !== 'string' || !parseHttpUrl(baseUrl)) { + return { error: 'base_url must be a valid http or https URL', warnings: [] }; + } + try { + assertSafeOutboundUrl(baseUrl); + return { warnings: [] }; + } catch (error) { + if (error instanceof OutboundBlockedError) { + return { + warnings: ['base_url points to an address that outbound calls will refuse under the current policy'] + }; + } + throw error; + } +}; const router = express.Router(); @@ -82,6 +130,12 @@ router.post( .json({ error: 'Missing required fields: name, provider, and config are required' }); } + const outboundCheck = checkBaseUrlForSave(config); + if (outboundCheck.error) { + return res.status(400).json({ error: outboundCheck.error }); + } + const warnings = outboundCheck.warnings; + // Convert config to string if it's an object const configStr = typeof config === 'string' ? config : JSON.stringify(config); @@ -94,7 +148,7 @@ router.post( }; const createdConfig = createLLMConfig(newConfig); - return res.status(201).json(createdConfig); + return res.status(201).json(warnings.length > 0 ? { ...createdConfig, warnings } : createdConfig); } catch (error: any) { logError('Error creating LLM config:', error); return res.status(500).json({ error: error.message }); @@ -115,6 +169,11 @@ router.put( } const { name, provider, config, priority } = req.body; + const outboundCheck = checkBaseUrlForSave(config); + if (outboundCheck.error) { + return res.status(400).json({ error: outboundCheck.error }); + } + const warnings = outboundCheck.warnings; // Convert config to string if it's an object let configStr = config; @@ -135,7 +194,7 @@ router.put( return res.status(404).json({ error: 'LLM config not found' }); } - return res.json(updatedConfig); + return res.json(warnings.length > 0 ? { ...updatedConfig, warnings } : updatedConfig); } catch (error: any) { logError('Error updating LLM config:', error); return res.status(500).json({ error: error.message }); diff --git a/backend/src/services/__tests__/llm-config-service.guard.test.ts b/backend/src/services/__tests__/llm-config-service.guard.test.ts new file mode 100644 index 0000000..e9e5010 --- /dev/null +++ b/backend/src/services/__tests__/llm-config-service.guard.test.ts @@ -0,0 +1,56 @@ +import { LLMConfigService } from '../llm-config-service'; +import * as dbQueries from '../../db/queries'; +import axios from 'axios'; + +jest.mock('../../db/queries'); +jest.mock('axios'); + +describe('LLMConfigService outbound guard', () => { + let service: LLMConfigService; + const mockedAxios = axios as jest.Mocked; + + const ollamaConfig = (baseUrl: string) => ({ + id: 7, + provider: 'ollama', + config: JSON.stringify({ model: 'llama2', base_url: baseUrl }), + priority: 1 + }); + + beforeEach(() => { + jest.clearAllMocks(); + service = new LLMConfigService(); + }); + + it('refuses a blocked base_url before making any request', async () => { + (dbQueries.getLLMConfigById as jest.Mock).mockReturnValue(ollamaConfig('http://169.254.169.254')); + + const result = await service.callLLM(7, { prompt: 'hi' }); + + expect(mockedAxios.post).not.toHaveBeenCalled(); + expect(result.error).toContain('Outbound request to this address is not allowed'); + expect(result.error).not.toContain('169.254'); + }); + + it('refuses a mapped IPv6 metadata base_url before making any request', async () => { + (dbQueries.getLLMConfigById as jest.Mock).mockReturnValue(ollamaConfig('http://[::ffff:a9fe:a9fe]')); + + const result = await service.callLLM(7, { prompt: 'hi' }); + + expect(mockedAxios.post).not.toHaveBeenCalled(); + expect(result.error).toContain('Outbound request to this address is not allowed'); + }); + + it('applies guarded axios options to a permitted loopback base_url', async () => { + (dbQueries.getLLMConfigById as jest.Mock).mockReturnValue(ollamaConfig('http://127.0.0.1:11434')); + mockedAxios.post.mockResolvedValue({ data: { response: 'ok' } } as any); + + const result = await service.callLLM(7, { prompt: 'hi' }); + + expect(result.text).toBe('ok'); + expect(mockedAxios.post).toHaveBeenCalledWith( + 'http://127.0.0.1:11434/api/generate', + expect.any(Object), + expect.objectContaining({ maxRedirects: 0, proxy: false, lookup: expect.any(Function) }) + ); + }); +}); diff --git a/backend/src/services/__tests__/llm-config-service.test.ts b/backend/src/services/__tests__/llm-config-service.test.ts index f3e1462..239e322 100644 --- a/backend/src/services/__tests__/llm-config-service.test.ts +++ b/backend/src/services/__tests__/llm-config-service.test.ts @@ -152,7 +152,8 @@ describe('LLMConfigService', () => { num_predict: 500, stop: ['END'] } - }) + }), + expect.objectContaining({ maxRedirects: 0, proxy: false }) ); }); @@ -178,7 +179,8 @@ describe('LLMConfigService', () => { temperature: 0.7, num_predict: 1000 }) - }) + }), + expect.objectContaining({ maxRedirects: 0, proxy: false }) ); }); }); @@ -215,12 +217,12 @@ describe('LLMConfigService', () => { temperature: 0.5, stop: undefined }, - { + expect.objectContaining({ headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test-key' } - } + }) ); }); @@ -283,13 +285,13 @@ describe('LLMConfigService', () => { temperature: 0.7, stop_sequences: [] }, - { + expect.objectContaining({ headers: { 'Content-Type': 'application/json', 'x-api-key': 'test-key', 'anthropic-version': '2023-06-01' } - } + }) ); }); @@ -465,7 +467,7 @@ describe('LLMConfigService', () => { temperature: 0.5, stop: undefined }, - { + expect.objectContaining({ headers: { 'Content-Type': 'application/json', 'x-api-key': 'test-key', @@ -473,7 +475,7 @@ describe('LLMConfigService', () => { 'x-team-id': 'test-team-id', 'User-Agent': 'bob-ide/2.0.1' } - } + }) ); }); diff --git a/backend/src/services/llm-config-service.ts b/backend/src/services/llm-config-service.ts index 5bd2032..be1d517 100644 --- a/backend/src/services/llm-config-service.ts +++ b/backend/src/services/llm-config-service.ts @@ -1,5 +1,6 @@ import axios from 'axios'; import { LLMConfig } from '@ibm-vibe/types'; +import { assertSafeOutboundUrl, guardedAxiosOptions } from '@ibm-vibe/outbound-guard'; export interface LLMRequestOptions { prompt: string; @@ -117,16 +118,21 @@ export class LLMConfigService { const model = configData.model || 'llama2'; try { - const response = await axios.post(`${baseUrl}/api/generate`, { - model, - prompt: options.prompt, - stream: false, - options: { - temperature: options.temperature || 0.7, - num_predict: options.max_tokens || 1000, - stop: options.stop || [] - } - }); + assertSafeOutboundUrl(baseUrl); + const response = await axios.post( + `${baseUrl}/api/generate`, + { + model, + prompt: options.prompt, + stream: false, + options: { + temperature: options.temperature || 0.7, + num_predict: options.max_tokens || 1000, + stop: options.stop || [] + } + }, + guardedAxiosOptions() + ); return { text: response.data.response, @@ -153,6 +159,7 @@ export class LLMConfigService { const baseUrl = configData.base_url || 'https://api.openai.com/v1'; try { + assertSafeOutboundUrl(baseUrl); const response = await axios.post( `${baseUrl}/chat/completions`, { @@ -166,7 +173,8 @@ export class LLMConfigService { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` - } + }, + ...guardedAxiosOptions() } ); @@ -195,6 +203,7 @@ export class LLMConfigService { const baseUrl = configData.base_url || 'https://api.anthropic.com/v1'; try { + assertSafeOutboundUrl(baseUrl); const response = await axios.post( `${baseUrl}/messages`, { @@ -209,7 +218,8 @@ export class LLMConfigService { 'Content-Type': 'application/json', 'x-api-key': apiKey, 'anthropic-version': '2023-06-01' - } + }, + ...guardedAxiosOptions() } ); @@ -243,6 +253,7 @@ export class LLMConfigService { const baseUrl = configData.base_url || 'https://us-south.ml.cloud.ibm.com'; try { + assertSafeOutboundUrl(baseUrl); const tokenParams = new URLSearchParams(); tokenParams.append('grant_type', 'urn:ibm:params:oauth:grant-type:apikey'); tokenParams.append('apikey', apiKey); @@ -274,7 +285,8 @@ export class LLMConfigService { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}`, Accept: 'application/json' - } + }, + ...guardedAxiosOptions() } ); @@ -312,6 +324,7 @@ export class LLMConfigService { const baseUrl = configData.base_url || 'https://api.us-east.bob.ibm.com'; try { + assertSafeOutboundUrl(baseUrl); const response = await axios.post( `${baseUrl}/inference/v1/chat/completions`, { @@ -328,7 +341,8 @@ export class LLMConfigService { 'x-instance-id': instanceId, 'x-team-id': teamId, 'User-Agent': 'bob-ide/2.0.1' - } + }, + ...guardedAxiosOptions() } ); diff --git a/package-lock.json b/package-lock.json index 507e2d5..5473edf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -29,6 +29,7 @@ "license": "Apache-2.0", "dependencies": { "@ibm-vibe/config": "*", + "@ibm-vibe/outbound-guard": "*", "@ibm-vibe/types": "*", "@ibm-vibe/utils": "*", "axios": "^1.20.0", @@ -84,6 +85,7 @@ "license": "Apache-2.0", "dependencies": { "@ibm-vibe/config": "*", + "@ibm-vibe/outbound-guard": "*", "@ibm-vibe/types": "*", "@ibm-vibe/utils": "*", "@types/better-sqlite3": "^7.6.12", @@ -1461,6 +1463,10 @@ "resolved": "packages/config", "link": true }, + "node_modules/@ibm-vibe/outbound-guard": { + "resolved": "packages/outbound-guard", + "link": true + }, "node_modules/@ibm-vibe/types": { "resolved": "packages/types", "link": true @@ -13965,6 +13971,16 @@ "typescript": "^5.7.3" } }, + "packages/outbound-guard": { + "name": "@ibm-vibe/outbound-guard", + "version": "1.0.0", + "dependencies": { + "axios": "^1.20.0" + }, + "devDependencies": { + "typescript": "^5.7.3" + } + }, "packages/types": { "name": "@ibm-vibe/types", "version": "1.0.0", diff --git a/package.json b/package.json index 8bb4ddb..16a0a14 100644 --- a/package.json +++ b/package.json @@ -14,13 +14,13 @@ "scripts": { "install:all": "npm install", "build:types": "npm run build -w @ibm-vibe/types", - "build:packages": "npm run build -w @ibm-vibe/types && npm run build -w @ibm-vibe/utils && npm run build -w @ibm-vibe/config && npm run build -w @ibm-vibe/cli", + "build:packages": "npm run build -w @ibm-vibe/types && npm run build -w @ibm-vibe/utils && npm run build -w @ibm-vibe/config && npm run build -w @ibm-vibe/outbound-guard && npm run build -w @ibm-vibe/cli", "postinstall": "npm run build:packages", "format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,md,yml,yaml,css,scss}\"", "format:check": "prettier --check \"**/*.{js,jsx,ts,tsx,json,md,yml,yaml,css,scss}\"", "lint": "npm run lint -w backend && npm run lint -w frontend && npm run lint -w agent-service-api && npm run lint -w @ibm-vibe/cli", - "typecheck": "npm run typecheck -w backend && npm run typecheck -w frontend && npm run typecheck -w agent-service-api", - "test:ts": "npm run test -w backend && npm run test -w frontend && npm run test -w agent-service-api", + "typecheck": "npm run typecheck -w backend && npm run typecheck -w frontend && npm run typecheck -w agent-service-api && npm run typecheck -w @ibm-vibe/outbound-guard", + "test:ts": "npm run test -w backend && npm run test -w frontend && npm run test -w agent-service-api && npm run test -w @ibm-vibe/outbound-guard", "test:cli-e2e": "npm run build -w backend && npm run test:e2e -w @ibm-vibe/cli", "test": "npm run test:ts", "dev:backend": "npm run dev -w backend", diff --git a/packages/config/src/index.ts b/packages/config/src/index.ts index a66b5d4..9734889 100644 --- a/packages/config/src/index.ts +++ b/packages/config/src/index.ts @@ -1,11 +1,23 @@ import { z } from 'zod'; +const booleanFlag = (defaultValue: boolean) => + z + .enum(['true', 'false']) + .default(defaultValue ? 'true' : 'false') + .transform((value) => value === 'true'); + +const outboundEnvSchema = { + OUTBOUND_ALLOW_LOOPBACK: booleanFlag(true), + OUTBOUND_ALLOW_PRIVATE_NETWORKS: booleanFlag(false) +}; + const backendEnvSchema = z.object({ PORT: z.coerce.number().default(5100), HOST: z.string().default('localhost'), AGENT_SERVICE_URL: z.string().default('http://localhost:5002'), AGENT_SERVICE_TIMEOUT: z.coerce.number().nonnegative().default(0), - DB_PATH: z.string().default('./data/agent-testing.db') + DB_PATH: z.string().default('./data/agent-testing.db'), + ...outboundEnvSchema }); const agentServiceApiSchema = z.object({ @@ -18,7 +30,8 @@ const agentServiceApiSchema = z.object({ POLLER_BASE_INTERVAL_MS: z.coerce.number().positive().default(5000), POLLER_MAX_INTERVAL_MS: z.coerce.number().positive().default(60000), POLLER_BACKOFF_MULTIPLIER: z.coerce.number().positive().default(1.5), - POLLER_MAX_CONCURRENT_JOBS: z.coerce.number().int().positive().default(3) + POLLER_MAX_CONCURRENT_JOBS: z.coerce.number().int().positive().default(3), + ...outboundEnvSchema }); const frontendEnvSchema = z.object({ @@ -34,6 +47,7 @@ export const loadBackendConfig = ( server: { port: number; host: string }; agentService: { url: string; timeout: number }; database: { path: string }; + outbound: { allowLoopback: boolean; allowPrivateNetworks: boolean }; } => { const parsed = backendEnvSchema.parse(env); return { @@ -47,6 +61,10 @@ export const loadBackendConfig = ( }, database: { path: parsed.DB_PATH + }, + outbound: { + allowLoopback: parsed.OUTBOUND_ALLOW_LOOPBACK, + allowPrivateNetworks: parsed.OUTBOUND_ALLOW_PRIVATE_NETWORKS } }; }; @@ -63,6 +81,7 @@ export const loadAgentServiceApiConfig = ( backoffMultiplier: number; maxConcurrentJobs: number; }; + outbound: { allowLoopback: boolean; allowPrivateNetworks: boolean }; } => { const parsed = agentServiceApiSchema.parse(env); return { @@ -83,6 +102,10 @@ export const loadAgentServiceApiConfig = ( maxIntervalMs: parsed.POLLER_MAX_INTERVAL_MS, backoffMultiplier: parsed.POLLER_BACKOFF_MULTIPLIER, maxConcurrentJobs: parsed.POLLER_MAX_CONCURRENT_JOBS + }, + outbound: { + allowLoopback: parsed.OUTBOUND_ALLOW_LOOPBACK, + allowPrivateNetworks: parsed.OUTBOUND_ALLOW_PRIVATE_NETWORKS } }; }; diff --git a/packages/outbound-guard/jest.config.js b/packages/outbound-guard/jest.config.js new file mode 100644 index 0000000..adcad86 --- /dev/null +++ b/packages/outbound-guard/jest.config.js @@ -0,0 +1,15 @@ +/** @type {import('ts-jest').JestConfigWithTsJest} */ +module.exports = { + preset: 'ts-jest', + testEnvironment: 'node', + testMatch: ['**/__tests__/**/*.test.ts'], + collectCoverageFrom: ['src/**/*.ts', '!src/**/*.d.ts', '!src/**/__tests__/**'], + coverageThreshold: { + global: { + branches: 90, + functions: 90, + lines: 90, + statements: 90 + } + } +}; diff --git a/packages/outbound-guard/package.json b/packages/outbound-guard/package.json new file mode 100644 index 0000000..e1c4ece --- /dev/null +++ b/packages/outbound-guard/package.json @@ -0,0 +1,17 @@ +{ + "name": "@ibm-vibe/outbound-guard", + "version": "1.0.0", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "scripts": { + "build": "tsc -p tsconfig.json", + "typecheck": "tsc --noEmit", + "test": "jest --runInBand" + }, + "dependencies": { + "axios": "^1.20.0" + }, + "devDependencies": { + "typescript": "^5.7.3" + } +} diff --git a/packages/outbound-guard/src/__tests__/outbound-guard.test.ts b/packages/outbound-guard/src/__tests__/outbound-guard.test.ts new file mode 100644 index 0000000..f45970a --- /dev/null +++ b/packages/outbound-guard/src/__tests__/outbound-guard.test.ts @@ -0,0 +1,287 @@ +import dns from 'dns'; +import { + assertSafeOutboundUrl, + guardedAxiosOptions, + OutboundBlockedError, + classifyAddress, + DEFAULT_POLICY, + AddressClass +} from '../index'; + +jest.mock('dns', () => { + const actual = jest.requireActual('dns'); + return { ...actual, lookup: jest.fn() }; +}); + +const lookupMock = dns.lookup as unknown as jest.Mock; + +/** Make dns.lookup(name, {all:true}) resolve to the given addresses. */ +const resolveTo = (...addresses: string[]) => { + lookupMock.mockImplementation((_host: string, opts: any, cb: any) => { + cb( + null, + addresses.map((address) => ({ address, family: address.includes(':') ? 6 : 4 })) + ); + }); +}; + +beforeEach(() => { + lookupMock.mockReset(); +}); + +describe('classifyAddress', () => { + const cases: Array<[string, 'public' | 'loopback' | 'private' | 'always']> = [ + ['169.254.169.254', 'always'], + ['127.0.0.1', 'loopback'], + ['10.1.2.3', 'private'], + ['172.16.0.5', 'private'], + ['192.168.1.1', 'private'], + ['100.64.0.1', 'private'], + ['8.8.8.8', 'public'], + ['0.0.0.0', 'always'], + ['224.0.0.1', 'always'], + ['255.255.255.255', 'always'], + ['::1', 'loopback'], + ['::', 'always'], + ['fe80::1', 'always'], + ['fd00::1', 'private'], + ['ff02::1', 'always'], + ['::ffff:169.254.169.254', 'always'], + ['::ffff:a9fe:a9fe', 'always'], + ['::ffff:127.0.0.1', 'loopback'], + ['::ffff:10.0.0.1', 'private'], + ['::127.0.0.1', 'always'], + ['64:ff9b::a9fe:a9fe', 'always'], + ['64:ff9b:1::a9fe:a9fe', 'always'], + ['2002:a9fe:a9fe::1', 'always'], + ['2606:4700:4700::1111', 'public'] + ]; + + it.each(cases)('classifies %s as %s', (address, expected) => { + expect(classifyAddress(address)).toBe(expected); + }); + + it.each([ + ['::ffff:0:a9fe:a9fe', 'always'], // SIIT + ['64:ff9b::8.8.8.8', 'always'], // NAT64 with dotted tail, parsed as 64:ff9b::808:808 + ['64:ff9b:1:0:0:0:0:1', 'always'], // local-use NAT64 + ['64:ff9b:2::1', 'public'], // outside every blocked NAT64 range + ['2001:db8::1', 'public'], + ['1:2:3:4:5:6:7:8', 'public'], // full form, no compression + ['::ffff:300.1.1.1', 'always'], // invalid embedded IPv4 fails closed + ['1:2:3:4:5:6:7:8:9', 'always'], // too many groups + ['1::2::3', 'always'], // two compressions + ['1:2:3:4:5:6:7:8::', 'always'], // trailing compression with eight groups is not valid + ['1:2:3:4:5:6:7:zz', 'always'], // non-hex group + ['1::2:3:4:5:6:7:8:9', 'always'], // compression with too many groups + ['not-an-ip:host', 'always'] // contains a colon but is not an address + ] as Array<[string, AddressClass]>)('classifies malformed or edge IPv6 %s as %s', (address, expected) => { + expect(classifyAddress(address)).toBe(expected); + }); + + it.each([ + ['192.0.0.5', 'private'], // IETF protocol assignments + ['192.0.2.7', 'private'], // TEST-NET-1 + ['192.0.1.1', 'public'], + ['198.18.0.9', 'private'], // benchmarking + ['198.19.255.1', 'private'], + ['198.20.0.1', 'public'], + ['198.51.100.4', 'private'], // TEST-NET-2 + ['203.0.113.9', 'private'], // TEST-NET-3 + ['203.0.114.1', 'public'], + ['172.32.0.1', 'public'], // just outside 172.16/12 + ['100.128.0.1', 'public'], // just outside CGNAT + ['223.255.255.255', 'public'] + ] as Array<[string, AddressClass]>)('classifies reserved IPv4 %s as %s', (address, expected) => { + expect(classifyAddress(address)).toBe(expected); + }); + + it.each([ + ['::1:2:3:4:5:6:7', 'public'], // compression in the middle, no dotted tail + ['1:2:3:4::5:6:7', 'public'], + ['::ffff:1.2.3.4', 'public'], // mapped with dotted tail, public + ['2001:db8::', 'public'], // trailing compression + ['::ffff:1.2.3', 'always'], // dotted tail with three parts + ['::ffff:1.2.3.256', 'always'], // dotted tail with an octet over 255 + ['::ffff:1.2.3.x', 'always'], // dotted tail with a non-numeric octet + ['1:2:3:4:5:6:7::8', 'always'] // compression with too many groups + ] as Array<[string, AddressClass]>)('classifies compressed or dotted-tail IPv6 %s as %s', (address, expected) => { + expect(classifyAddress(address)).toBe(expected); + }); + + it('fails closed for a non-address string', () => { + expect(classifyAddress('example.com')).toBe('always'); + }); + + it('strips a zone identifier before classifying', () => { + expect(classifyAddress('fe80::1%eth0')).toBe('always'); + }); + + it('defaults allow loopback and block private networks', () => { + expect(DEFAULT_POLICY).toEqual({ allowLoopback: true, allowPrivateNetworks: false }); + }); +}); + +describe('assertSafeOutboundUrl (literals and schemes)', () => { + it('refuses the cloud metadata address', () => { + expect(() => assertSafeOutboundUrl('http://169.254.169.254/latest/meta-data/')).toThrow(OutboundBlockedError); + }); + + it('refuses mapped IPv6 forms of the metadata address (hex form, as URL normalises it)', () => { + expect(() => assertSafeOutboundUrl('http://[::ffff:169.254.169.254]/')).toThrow(OutboundBlockedError); + expect(() => assertSafeOutboundUrl('http://[::ffff:a9fe:a9fe]/')).toThrow(OutboundBlockedError); + }); + + it.each(['http://2852039166/', 'http://0/'])( + 'refuses alternate IPv4 spellings that normalise to a blocked address: %s', + (url) => { + // 2852039166 normalises to 169.254.169.254; 0 normalises to 0.0.0.0 + expect(() => assertSafeOutboundUrl(url)).toThrow(OutboundBlockedError); + } + ); + + it('allows an alternate loopback spelling by default (0x7f.1 normalises to 127.0.0.1)', () => { + expect(() => assertSafeOutboundUrl('http://0x7f.1/')).not.toThrow(); + }); + + it('refuses a private address when private networks are disabled', () => { + expect(() => assertSafeOutboundUrl('http://10.0.0.5/')).toThrow(OutboundBlockedError); + expect(() => assertSafeOutboundUrl('http://192.168.1.10:8080/')).toThrow(OutboundBlockedError); + }); + + it('allows a private address when private networks are enabled', () => { + expect(() => assertSafeOutboundUrl('http://10.0.0.5/', { allowPrivateNetworks: true })).not.toThrow(); + }); + + it('allows loopback by default', () => { + expect(() => assertSafeOutboundUrl('http://127.0.0.1:11434/')).not.toThrow(); + expect(() => assertSafeOutboundUrl('http://[::1]:11434/')).not.toThrow(); + }); + + it('refuses loopback when loopback is disabled', () => { + expect(() => assertSafeOutboundUrl('http://127.0.0.1:11434/', { allowLoopback: false })).toThrow( + OutboundBlockedError + ); + }); + + it('does not refuse a public literal', () => { + expect(() => assertSafeOutboundUrl('https://8.8.8.8/')).not.toThrow(); + }); + + it.each(['file:///etc/passwd', 'gopher://127.0.0.1:70/', 'ftp://8.8.8.8/', 'javascript:alert(1)'])( + 'refuses non-http(s) scheme: %s', + (url) => { + expect(() => assertSafeOutboundUrl(url)).toThrow(OutboundBlockedError); + } + ); + + it('refuses a string that is not a URL', () => { + expect(() => assertSafeOutboundUrl('not a url')).toThrow(OutboundBlockedError); + }); + + it('does not resolve DNS for an IP literal', () => { + assertSafeOutboundUrl('http://8.8.8.8/'); + expect(lookupMock).not.toHaveBeenCalled(); + }); + + it('does not include the resolved address in the error message', () => { + try { + assertSafeOutboundUrl('http://169.254.169.254/'); + throw new Error('expected throw'); + } catch (error: any) { + expect(error).toBeInstanceOf(OutboundBlockedError); + expect(error.code).toBe('OUTBOUND_BLOCKED'); + expect(error.message).toBe('Outbound request to this address is not allowed'); + expect(error.message).not.toContain('169.254'); + } + }); + + it('refuses a configured denied port on loopback, even when loopback is allowed', () => { + expect(() => assertSafeOutboundUrl('http://127.0.0.1:5100/api/llm-configs', { denyPorts: [5100] })).toThrow( + OutboundBlockedError + ); + }); + + it('refuses a denied port when the URL uses the scheme default port', () => { + expect(() => assertSafeOutboundUrl('http://127.0.0.1/', { denyPorts: [80] })).toThrow(OutboundBlockedError); + }); + + it('allows loopback on a non-denied port', () => { + expect(() => assertSafeOutboundUrl('http://127.0.0.1:9999/', { denyPorts: [5100] })).not.toThrow(); + }); + + it('denies a configured port on a hostname before any DNS lookup', () => { + expect(() => assertSafeOutboundUrl('http://localhost:5100/', { denyPorts: [5100] })).toThrow( + OutboundBlockedError + ); + expect(lookupMock).not.toHaveBeenCalled(); + }); +}); + +describe('guardedAxiosOptions', () => { + it('disables redirects and proxy handling', () => { + const opts = guardedAxiosOptions(); + expect(opts.maxRedirects).toBe(0); + expect(opts.proxy).toBe(false); + expect(typeof opts.lookup).toBe('function'); + }); + + it('lookup resolves a public hostname and returns the validated address', (done) => { + resolveTo('8.8.8.8'); + const { lookup } = guardedAxiosOptions(); + lookup!('example.com', {} as any, (err: any, address: any, family: any) => { + expect(err).toBeNull(); + expect(address).toBe('8.8.8.8'); + expect(family).toBe(4); + done(); + }); + }); + + it('lookup refuses a hostname that resolves to the metadata address', (done) => { + resolveTo('169.254.169.254'); + const { lookup } = guardedAxiosOptions(); + lookup!('metadata.example', {} as any, (err: any) => { + expect(err).toBeInstanceOf(OutboundBlockedError); + done(); + }); + }); + + it('lookup refuses a hostname with one blocked address among public ones (rebinding-style mix)', (done) => { + resolveTo('8.8.8.8', '10.0.0.7'); + const { lookup } = guardedAxiosOptions(); + lookup!('mixed.example', {} as any, (err: any) => { + expect(err).toBeInstanceOf(OutboundBlockedError); + done(); + }); + }); + + it('lookup honours all:true and returns an array of validated addresses', (done) => { + resolveTo('8.8.8.8', '1.1.1.1'); + const { lookup } = guardedAxiosOptions(); + lookup!('example.com', { all: true } as any, (err: any, addresses: any) => { + expect(err).toBeNull(); + expect(addresses.map((a: any) => a.address)).toEqual(['8.8.8.8', '1.1.1.1']); + done(); + }); + }); + + it('lookup propagates DNS errors unchanged', (done) => { + lookupMock.mockImplementation((_h: string, _o: any, cb: any) => + cb(Object.assign(new Error('nx'), { code: 'ENOTFOUND' })) + ); + const { lookup } = guardedAxiosOptions(); + lookup!('missing.example', {} as any, (err: any) => { + expect(err.code).toBe('ENOTFOUND'); + done(); + }); + }); + + it('lookup refuses a zoned link-local address returned by DNS', (done) => { + resolveTo('fe80::1%eth0'); + const { lookup } = guardedAxiosOptions(); + lookup!('zoned.example', {} as any, (err: any) => { + expect(err).toBeInstanceOf(OutboundBlockedError); + done(); + }); + }); +}); diff --git a/packages/outbound-guard/src/index.ts b/packages/outbound-guard/src/index.ts new file mode 100644 index 0000000..a6e9b01 --- /dev/null +++ b/packages/outbound-guard/src/index.ts @@ -0,0 +1,206 @@ +import dns from 'dns'; +import net from 'net'; +import type { AddressFamily, AxiosRequestConfig } from 'axios'; + +export interface OutboundPolicy { + allowLoopback: boolean; + allowPrivateNetworks: boolean; +} + +export const DEFAULT_POLICY: OutboundPolicy = { + allowLoopback: true, + allowPrivateNetworks: false +}; + +export type AddressClass = 'public' | 'loopback' | 'private' | 'always'; + +export class OutboundBlockedError extends Error { + readonly code = 'OUTBOUND_BLOCKED'; + + constructor() { + super('Outbound request to this address is not allowed'); + this.name = 'OutboundBlockedError'; + } +} + +const ipv4Class = (a: number, b: number, c: number): AddressClass => { + if (a === 0 || a >= 224) return 'always'; + if (a === 169 && b === 254) return 'always'; + if (a === 127) return 'loopback'; + if (a === 10) return 'private'; + if (a === 172 && b >= 16 && b <= 31) return 'private'; + if (a === 192 && b === 168) return 'private'; + if (a === 100 && b >= 64 && b <= 127) return 'private'; + if (a === 192 && b === 0 && (c === 0 || c === 2)) return 'private'; + if (a === 198 && (b === 18 || b === 19)) return 'private'; + if (a === 198 && b === 51 && c === 100) return 'private'; + if (a === 203 && b === 0 && c === 113) return 'private'; + return 'public'; +}; + +/** Parses an IPv6 literal (optionally with embedded dotted IPv4) into 16 bytes. */ +const parseIPv6 = (input: string): number[] | null => { + let text = input; + if (text.includes('.')) { + const idx = text.lastIndexOf(':'); + const parts = text + .slice(idx + 1) + .split('.') + .map(Number); + if (parts.length !== 4 || parts.some((p) => !Number.isInteger(p) || p < 0 || p > 255)) return null; + text = + text.slice(0, idx + 1) + + ((parts[0] << 8) | parts[1]).toString(16) + + ':' + + ((parts[2] << 8) | parts[3]).toString(16); + } + + const halves = text.split('::'); + if (halves.length > 2) return null; + const head = halves[0] ? halves[0].split(':') : []; + const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : []; + + let groups: string[]; + if (halves.length === 2) { + const missing = 8 - head.length - tail.length; + if (missing < 0) return null; + groups = [...head, ...new Array(missing).fill('0'), ...tail]; + } else { + groups = head; + } + if (groups.length !== 8) return null; + + const bytes: number[] = []; + for (const group of groups) { + if (!/^[0-9a-f]{1,4}$/i.test(group)) return null; + const value = parseInt(group, 16); + bytes.push(value >> 8, value & 0xff); + } + return bytes; +}; + +const isZeroFrom = (bytes: number[], from: number, to: number): boolean => bytes.slice(from, to).every((b) => b === 0); + +const ipv6Class = (bytes: number[]): AddressClass => { + if (isZeroFrom(bytes, 0, 16)) return 'always'; // :: + if (isZeroFrom(bytes, 0, 15) && bytes[15] === 1) return 'loopback'; // ::1 + + // IPv4-mapped (::ffff:a.b.c.d): classify the embedded IPv4 address. + if (isZeroFrom(bytes, 0, 10) && bytes[10] === 0xff && bytes[11] === 0xff) { + return ipv4Class(bytes[12], bytes[13], bytes[14]); + } + + // Embedded-IPv4 transition ranges that can reach IPv4 hosts: always blocked. + if (isZeroFrom(bytes, 0, 12)) return 'always'; // ::/96 IPv4-compatible (deprecated) + if (isZeroFrom(bytes, 0, 8) && bytes[8] === 0xff && bytes[9] === 0xff && isZeroFrom(bytes, 10, 12)) { + return 'always'; // ::ffff:0:0:0/96 SIIT + } + if (bytes[0] === 0x00 && bytes[1] === 0x64 && bytes[2] === 0xff && bytes[3] === 0x9b) { + if (isZeroFrom(bytes, 4, 12) || (bytes[4] === 0x00 && bytes[5] === 0x01)) return 'always'; // 64:ff9b::/96, 64:ff9b:1::/48 + } + if (bytes[0] === 0x20 && bytes[1] === 0x02) return 'always'; // 2002::/16 (6to4) + + if (bytes[0] === 0xfe && (bytes[1] & 0xc0) === 0x80) return 'always'; // fe80::/10 link-local + if (bytes[0] === 0xff) return 'always'; // ff00::/8 multicast + if ((bytes[0] & 0xfe) === 0xfc) return 'private'; // fc00::/7 ULA + + return 'public'; +}; + +/** + * Classifies an IP address literal. Accepts IPv4, IPv6, and IPv6 with a zone identifier. + * Anything that cannot be parsed is treated as 'always' (fail closed). + */ +export const classifyAddress = (address: string): AddressClass => { + const withoutZone = address.split('%')[0]; + if (net.isIPv4(withoutZone)) { + const [a, b, c] = withoutZone.split('.').map(Number); + return ipv4Class(a, b, c); + } + if (net.isIPv6(withoutZone)) { + const bytes = parseIPv6(withoutZone); + return bytes ? ipv6Class(bytes) : 'always'; + } + return 'always'; +}; + +const isBlocked = (addressClass: AddressClass, policy: OutboundPolicy): boolean => { + if (addressClass === 'always') return true; + if (addressClass === 'loopback') return !policy.allowLoopback; + if (addressClass === 'private') return !policy.allowPrivateNetworks; + return false; +}; + +export interface OutboundUrlOptions extends Partial { + /** Ports that are refused for any destination, e.g. this service's own port. */ + denyPorts?: number[]; +} + +/** + * Pre-flight check for a caller-supplied URL. Validates the scheme, the denied ports, + * and IP literals. Hostnames are not resolved here; the lookup guard from + * guardedAxiosOptions() checks the resolved addresses at connect time. + * + * IP literals never reach dns.lookup, so they must be checked here. + */ +export const assertSafeOutboundUrl = (url: string, options: OutboundUrlOptions = {}): URL => { + const policy: OutboundPolicy = { ...DEFAULT_POLICY, ...options }; + + let parsed: URL; + try { + parsed = new URL(url); + } catch { + throw new OutboundBlockedError(); + } + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + throw new OutboundBlockedError(); + } + + const port = parsed.port ? Number(parsed.port) : parsed.protocol === 'https:' ? 443 : 80; + if (options.denyPorts?.includes(port)) { + throw new OutboundBlockedError(); + } + + const host = parsed.hostname.replace(/^\[|\]$/g, ''); + if (net.isIP(host.split('%')[0]) && isBlocked(classifyAddress(host), policy)) { + throw new OutboundBlockedError(); + } + return parsed; +}; + +/** + * Axios options that enforce the policy at connect time: + * - lookup: rejects any hostname that resolves to a blocked address (closes DNS rebinding, + * because the validated address is the one connected to). + * - maxRedirects 0: a redirect is an error, so a validated host cannot send us elsewhere. + * - proxy false: HTTP_PROXY/HTTPS_PROXY would otherwise send the request without a lookup. + */ +export const guardedAxiosOptions = ( + policy: Partial = {} +): Pick => { + const resolved: OutboundPolicy = { ...DEFAULT_POLICY, ...policy }; + + const lookup: NonNullable = (hostname, options, callback) => { + dns.lookup(hostname, { all: true }, (err, addresses) => { + if (err) { + callback(err, ''); + return; + } + const entries = addresses.map((entry) => ({ + address: entry.address, + family: entry.family as AddressFamily + })); + if (entries.some((entry) => isBlocked(classifyAddress(entry.address), resolved))) { + callback(new OutboundBlockedError(), ''); + return; + } + if (typeof options === 'object' && options !== null && 'all' in options && options.all) { + callback(null, entries); + return; + } + callback(null, entries[0].address, entries[0].family); + }); + }; + + return { lookup, maxRedirects: 0, proxy: false }; +}; diff --git a/packages/outbound-guard/tsconfig.json b/packages/outbound-guard/tsconfig.json new file mode 100644 index 0000000..4ce7cf9 --- /dev/null +++ b/packages/outbound-guard/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2019", + "module": "commonjs", + "declaration": true, + "declarationMap": true, + "outDir": "dist", + "rootDir": "src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "composite": true + }, + "include": ["src/**/*.ts"], + "exclude": ["dist", "node_modules"] +}