Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(translate): pin the LibreTranslate client connection to the vetted address (#377)

Yudhi Armyndharis60a45c0eaa67
diff --git a/src/plugins/extensions/translation/libretranslate.client.spec.ts b/src/plugins/extensions/translation/libretranslate.client.spec.ts
index 6430dcdc7..f537a8302 100644
--- a/src/plugins/extensions/translation/libretranslate.client.spec.ts
+++ b/src/plugins/extensions/translation/libretranslate.client.spec.ts
@@ -1,91 +1,105 @@
-// src/modules/translation/adapters/libretranslate.client.spec.ts
import { LibreTranslateClient } from './libretranslate.client';
+import { SsrfBlockedError, withSafeFetch } from '../../../common/security/ssrf-guard';
-describe('LibreTranslateClient', () => {
- const makeFetch = (impl: jest.Mock) => {
- global.fetch = impl;
- };
+// The client delegates the actual request to withSafeFetch (the IP-pinned, redirect-refusing primitive
+// that the SSRF guard owns and ssrf-guard.spec.ts covers). Stub only that helper; keep SsrfBlockedError
+// and isSsrfProtectionEnabled real so the client's circuit-exemption and guard-flag logic run for real.
+jest.mock('../../../common/security/ssrf-guard', () => {
+ const actual = jest.requireActual<typeof import('../../../common/security/ssrf-guard')>(
+ '../../../common/security/ssrf-guard',
+ );
+ return { ...actual, withSafeFetch: jest.fn() };
+});
- const origAllow = process.env.SSRF_ALLOWED_HOSTS;
- beforeEach(() => {
- // The logic tests target host `lt`; allowlist it so the new SSRF guard lets them through.
- process.env.SSRF_ALLOWED_HOSTS = 'lt';
- });
- afterEach(() => {
- if (origAllow === undefined) delete process.env.SSRF_ALLOWED_HOSTS;
- else process.env.SSRF_ALLOWED_HOSTS = origAllow;
- jest.restoreAllMocks();
- });
+const mockedWithSafeFetch = withSafeFetch as unknown as jest.Mock;
- describe('SSRF guard', () => {
- it('blocks a request to an internal address when SSRF protection is on (no fetch)', async () => {
- delete process.env.SSRF_ALLOWED_HOSTS; // 169.254.169.254 not allowlisted
- const fetchMock = jest.fn();
- global.fetch = fetchMock;
- const client = new LibreTranslateClient({ url: 'http://169.254.169.254:7001', timeoutMs: 1000 });
- await expect(client.translate('a', 'en', 'es')).rejects.toThrow();
- expect(fetchMock).not.toHaveBeenCalled();
- });
+type CannedResponse = { ok: boolean; status?: number; json?: () => Promise<unknown> };
+type WsfCall = [string, { method?: string; body?: string }, (r: unknown) => unknown, { guard: boolean }];
- it('does not trip the circuit breaker on a deterministic SSRF block', async () => {
- delete process.env.SSRF_ALLOWED_HOSTS;
- global.fetch = jest.fn();
- const client = new LibreTranslateClient({
- url: 'http://169.254.169.254:7001',
- timeoutMs: 1000,
- failureThreshold: 2,
- });
- await expect(client.translate('a', 'en', 'es')).rejects.toThrow();
- await expect(client.translate('a', 'en', 'es')).rejects.toThrow();
- await expect(client.translate('a', 'en', 'es')).rejects.toThrow();
- expect(client.isHealthy()).toBe(true);
- });
+// Feed the client a canned response into its `use` callback, mirroring withSafeFetch's real contract
+// (`return await use(response)`), so success/non-ok handling exercises the real client code.
+const respondWith = (res: CannedResponse): void => {
+ mockedWithSafeFetch.mockImplementation((_url: string, _init: unknown, use: (r: unknown) => unknown) =>
+ Promise.resolve(use(res)),
+ );
+};
- it('refuses to follow redirects (redirect: error) on a guarded request', async () => {
- const fetchMock = jest.fn().mockResolvedValue({ ok: true, json: () => Promise.resolve({ translatedText: 'x' }) });
- global.fetch = fetchMock;
- const client = new LibreTranslateClient({ url: 'http://lt:7001', timeoutMs: 1000 });
- await client.translate('a', 'en', 'es');
- const init = (fetchMock.mock.calls[0] as [string, RequestInit])[1];
- expect(init.redirect).toBe('error');
- });
+describe('LibreTranslateClient', () => {
+ const ORIG_PROTECT = process.env.WEBHOOK_SSRF_PROTECT;
+ beforeEach(() => mockedWithSafeFetch.mockReset());
+ afterEach(() => {
+ if (ORIG_PROTECT === undefined) delete process.env.WEBHOOK_SSRF_PROTECT;
+ else process.env.WEBHOOK_SSRF_PROTECT = ORIG_PROTECT;
});
- it('translate() posts q/source/target and returns translatedText', async () => {
- const fetchMock = jest.fn<Promise<unknown>, [string, RequestInit?]>().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve({ translatedText: 'Hola' }),
- });
- makeFetch(fetchMock);
+ it('routes the request through the IP-pinned withSafeFetch helper (guard on by default)', async () => {
+ respondWith({ ok: true, json: () => Promise.resolve({ translatedText: 'Hola' }) });
const client = new LibreTranslateClient({ url: 'http://lt:7001', timeoutMs: 1000 });
+ await client.translate('Hello', 'en', 'es');
+ expect(mockedWithSafeFetch).toHaveBeenCalledTimes(1);
+ const [url, , , opts] = mockedWithSafeFetch.mock.calls[0] as WsfCall;
+ expect(url).toBe('http://lt:7001/translate');
+ expect(opts).toEqual({ guard: true });
+ });
+
+ it('translate() sends q/source/target plus the api_key in the POST body and returns translatedText', async () => {
+ respondWith({ ok: true, json: () => Promise.resolve({ translatedText: 'Hola' }) });
+ const client = new LibreTranslateClient({ url: 'http://lt:7001', apiKey: 'secret', timeoutMs: 1000 });
const out = await client.translate('Hello', 'en', 'es');
expect(out).toBe('Hola');
- const init = fetchMock.mock.calls[0][1] as RequestInit;
- const body = JSON.parse(init.body as string) as Record<string, unknown>;
- expect(body).toMatchObject({ q: 'Hello', source: 'en', target: 'es' });
+ const [, init] = mockedWithSafeFetch.mock.calls[0] as WsfCall;
+ expect(init.method).toBe('POST');
+ expect(JSON.parse(init.body as string) as Record<string, unknown>).toMatchObject({
+ q: 'Hello',
+ source: 'en',
+ target: 'es',
+ api_key: 'secret',
+ });
});
it('detect() returns the top language', async () => {
- makeFetch(
- jest.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve([{ language: 'fr', confidence: 0.97 }]),
- }),
- );
+ respondWith({ ok: true, json: () => Promise.resolve([{ language: 'fr', confidence: 0.97 }]) });
const client = new LibreTranslateClient({ url: 'http://lt:7001', timeoutMs: 1000 });
expect(await client.detect('Bonjour')).toEqual({ lang: 'fr', confidence: 0.97 });
});
- it('opens the circuit after N consecutive failures and reports unhealthy', async () => {
- makeFetch(jest.fn().mockResolvedValue({ ok: false, status: 500, text: () => Promise.resolve('err') }));
+ it('languages() uses GET with no body', async () => {
+ respondWith({ ok: true, json: () => Promise.resolve([{ code: 'en' }, { code: 'es' }]) });
+ const client = new LibreTranslateClient({ url: 'http://lt:7001', timeoutMs: 1000 });
+ expect(await client.languages()).toEqual(['en', 'es']);
+ const [, init] = mockedWithSafeFetch.mock.calls[0] as WsfCall;
+ expect(init.method).toBe('GET');
+ expect(init.body).toBeUndefined();
+ });
+
+ it('passes guard:false to withSafeFetch when SSRF protection is disabled', async () => {
+ process.env.WEBHOOK_SSRF_PROTECT = 'false';
+ respondWith({ ok: true, json: () => Promise.resolve({ translatedText: 'x' }) });
+ const client = new LibreTranslateClient({ url: 'http://lt:7001', timeoutMs: 1000 });
+ await client.translate('a', 'en', 'es');
+ const [, , , opts] = mockedWithSafeFetch.mock.calls[0] as WsfCall;
+ expect(opts).toEqual({ guard: false });
+ });
+
+ it('propagates an SsrfBlockedError without tripping the circuit breaker', async () => {
+ mockedWithSafeFetch.mockRejectedValue(new SsrfBlockedError('blocked internal address'));
+ const client = new LibreTranslateClient({ url: 'http://lt:7001', timeoutMs: 1000, failureThreshold: 2 });
+ await expect(client.translate('a', 'en', 'es')).rejects.toThrow(SsrfBlockedError);
+ await expect(client.translate('a', 'en', 'es')).rejects.toThrow(SsrfBlockedError);
+ await expect(client.translate('a', 'en', 'es')).rejects.toThrow(SsrfBlockedError);
+ expect(client.isHealthy()).toBe(true);
+ });
+
+ it('a non-ok response rejects and counts toward the circuit breaker', async () => {
+ respondWith({ ok: false, status: 500 });
const client = new LibreTranslateClient({
url: 'http://lt:7001',
timeoutMs: 1000,
failureThreshold: 2,
cooldownMs: 60000,
});
- await expect(client.translate('a', 'en', 'es')).rejects.toThrow();
- await expect(client.translate('a', 'en', 'es')).rejects.toThrow();
+ await expect(client.translate('a', 'en', 'es')).rejects.toThrow(/HTTP 500/);
+ await expect(client.translate('a', 'en', 'es')).rejects.toThrow(/HTTP 500/);
expect(client.isHealthy()).toBe(false);
await expect(client.translate('a', 'en', 'es')).rejects.toThrow(/circuit open/i);
});
diff --git a/src/plugins/extensions/translation/libretranslate.client.ts b/src/plugins/extensions/translation/libretranslate.client.ts
index b7f771dc5..126704ebb 100644
--- a/src/plugins/extensions/translation/libretranslate.client.ts
+++ b/src/plugins/extensions/translation/libretranslate.client.ts
@@ -1,7 +1,7 @@
// src/modules/translation/adapters/libretranslate.client.ts
import { Translator, DetectResult } from './core/ports';
import { createLogger } from '../../../common/services/logger.service';
-import { assertSafeFetchUrl, isSsrfProtectionEnabled, SsrfBlockedError } from '../../../common/security/ssrf-guard';
+import { isSsrfProtectionEnabled, SsrfBlockedError, withSafeFetch } from '../../../common/security/ssrf-guard';
export interface LibreTranslateOptions {
url: string;
@@ -59,30 +59,28 @@ export class LibreTranslateClient implements Translator {
}
const url = `${this.base}${path}`;
- const ssrfProtected = isSsrfProtectionEnabled();
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.opts.timeoutMs);
try {
- // Validate the target host before sending the api_key-bearing body. Honors SSRF_ALLOWED_HOSTS,
- // so the documented localhost LibreTranslate sidecar still works once it's allowlisted.
- if (ssrfProtected) {
- await assertSafeFetchUrl(url);
- }
const body = method === 'POST' ? JSON.stringify({ ...payload, api_key: this.opts.apiKey }) : undefined;
- const res = await fetch(url, {
- method,
- headers: { 'Content-Type': 'application/json' },
- body,
- signal: controller.signal,
- // Refuse redirects: the guard only validated the original host; a 3xx would re-send the
- // api_key to a redirect-controlled (possibly internal) target.
- redirect: ssrfProtected ? 'error' : 'follow',
- });
- if (!res.ok) {
- throw new Error(`LibreTranslate ${path} -> HTTP ${res.status}`);
- }
+ // Route through the IP-pinned fetch: the host is validated once and the connection is pinned to the
+ // vetted address(es), closing the DNS-rebinding window between check and connect (the api_key
+ // travels in the body, so a rebind to an internal listener would otherwise exfiltrate it). Honors
+ // SSRF_ALLOWED_HOSTS for the documented localhost sidecar, and refuses redirects. When SSRF
+ // protection is disabled this degrades to a plain redirect-following fetch.
+ const data = await withSafeFetch(
+ url,
+ { method, headers: { 'Content-Type': 'application/json' }, body, signal: controller.signal },
+ async res => {
+ if (!res.ok) {
+ throw new Error(`LibreTranslate ${path} -> HTTP ${res.status}`);
+ }
+ return res.json();
+ },
+ { guard: isSsrfProtectionEnabled() },
+ );
this.consecutiveFailures = 0;
- return await res.json();
+ return data;
} catch (err) {
// A blocked-host SSRF error is a deterministic configuration problem, not a transient upstream
// failure — don't let it trip the circuit breaker (which exists to back off a flaky server).