Skip to content

Commit 8023f4c

Browse files
authored
fix(telegram): thread media transport policy into SSRF (#44639)
* fix(telegram): preserve media download transport policy * refactor(telegram): thread media transport policy * fix(telegram): sync fallback media policy * fix: note telegram media transport fix (#44639)
1 parent c38e7b0 commit 8023f4c

13 files changed

Lines changed: 469 additions & 85 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ Docs: https://docs.openclaw.ai
7474
- Memory/session sync: add mode-aware post-compaction session reindexing with `agents.defaults.compaction.postIndexSync` plus `agents.defaults.memorySearch.sync.sessions.postCompactionForce`, so compacted session memory can refresh immediately without forcing every deployment into synchronous reindexing. (#25561) thanks @rodrigouroz.
7575
- Telegram/model picker: make inline model button selections persist the chosen session model correctly, clear overrides when selecting the configured default, and include effective fallback models in `/models` button validation. (#40105) Thanks @avirweb.
7676
- Telegram/native command sync: suppress expected `BOT_COMMANDS_TOO_MUCH` retry error noise, add a final fallback summary log, and document the difference between command-menu overflow and real Telegram network failures.
77+
- Telegram/media downloads: thread the same direct or proxy transport policy into SSRF-guarded file fetches so inbound attachments keep working when Telegram falls back between env-proxy and direct networking. (#44639) Thanks @obviyus.
7778
- Mattermost/reply media delivery: pass agent-scoped `mediaLocalRoots` through shared reply delivery so allowed local files upload correctly from button, slash-command, and model-picker replies. (#44021) Thanks @LyleLiu666.
7879
- Plugins/env-scoped roots: fix plugin discovery/load caches and provenance tracking so same-process `HOME`/`OPENCLAW_HOME` changes no longer reuse stale plugin state or misreport `~/...` plugins as untracked. (#44046) thanks @gumadeiras.
7980
- Gateway/session discovery: discover disk-only and retired ACP session stores under custom templated `session.store` roots so ACP reconciliation, session-id/session-label targeting, and run-id fallback keep working after restart. (#44176) thanks @gumadeiras.

‎src/infra/net/fetch-guard.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
createPinnedDispatcher,
88
resolvePinnedHostnameWithPolicy,
99
type LookupFn,
10+
type PinnedDispatcherPolicy,
1011
SsrFBlockedError,
1112
type SsrFPolicy,
1213
} from "./ssrf.js";
@@ -29,6 +30,7 @@ export type GuardedFetchOptions = {
2930
signal?: AbortSignal;
3031
policy?: SsrFPolicy;
3132
lookupFn?: LookupFn;
33+
dispatcherPolicy?: PinnedDispatcherPolicy;
3234
mode?: GuardedFetchMode;
3335
pinDns?: boolean;
3436
/** @deprecated use `mode: "trusted_env_proxy"` for trusted/operator-controlled URLs. */
@@ -196,7 +198,7 @@ export async function fetchWithSsrFGuard(params: GuardedFetchOptions): Promise<G
196198
if (canUseTrustedEnvProxy) {
197199
dispatcher = new EnvHttpProxyAgent();
198200
} else if (params.pinDns !== false) {
199-
dispatcher = createPinnedDispatcher(pinned);
201+
dispatcher = createPinnedDispatcher(pinned, params.dispatcherPolicy);
200202
}
201203

202204
const init: RequestInit & { dispatcher?: Dispatcher } = {

‎src/infra/net/ssrf.dispatcher.test.ts‎

Lines changed: 92 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,24 @@
11
import { describe, expect, it, vi } from "vitest";
22

3-
const { agentCtor } = vi.hoisted(() => ({
3+
const { agentCtor, envHttpProxyAgentCtor, proxyAgentCtor } = vi.hoisted(() => ({
44
agentCtor: vi.fn(function MockAgent(this: { options: unknown }, options: unknown) {
55
this.options = options;
66
}),
7+
envHttpProxyAgentCtor: vi.fn(function MockEnvHttpProxyAgent(
8+
this: { options: unknown },
9+
options: unknown,
10+
) {
11+
this.options = options;
12+
}),
13+
proxyAgentCtor: vi.fn(function MockProxyAgent(this: { options: unknown }, options: unknown) {
14+
this.options = options;
15+
}),
716
}));
817

918
vi.mock("undici", () => ({
1019
Agent: agentCtor,
20+
EnvHttpProxyAgent: envHttpProxyAgentCtor,
21+
ProxyAgent: proxyAgentCtor,
1122
}));
1223

1324
import { createPinnedDispatcher, type PinnedHostname } from "./ssrf.js";
@@ -34,4 +45,84 @@ describe("createPinnedDispatcher", () => {
3445
| undefined;
3546
expect(firstCallArg?.connect?.autoSelectFamily).toBeUndefined();
3647
});
48+
49+
it("preserves caller transport hints while overriding lookup", () => {
50+
const lookup = vi.fn() as unknown as PinnedHostname["lookup"];
51+
const previousLookup = vi.fn();
52+
const pinned: PinnedHostname = {
53+
hostname: "api.telegram.org",
54+
addresses: ["149.154.167.220"],
55+
lookup,
56+
};
57+
58+
createPinnedDispatcher(pinned, {
59+
mode: "direct",
60+
connect: {
61+
autoSelectFamily: true,
62+
autoSelectFamilyAttemptTimeout: 300,
63+
lookup: previousLookup,
64+
},
65+
});
66+
67+
expect(agentCtor).toHaveBeenCalledWith({
68+
connect: {
69+
autoSelectFamily: true,
70+
autoSelectFamilyAttemptTimeout: 300,
71+
lookup,
72+
},
73+
});
74+
});
75+
76+
it("keeps env proxy route while pinning the direct no-proxy path", () => {
77+
const lookup = vi.fn() as unknown as PinnedHostname["lookup"];
78+
const pinned: PinnedHostname = {
79+
hostname: "api.telegram.org",
80+
addresses: ["149.154.167.220"],
81+
lookup,
82+
};
83+
84+
createPinnedDispatcher(pinned, {
85+
mode: "env-proxy",
86+
connect: {
87+
autoSelectFamily: true,
88+
},
89+
proxyTls: {
90+
autoSelectFamily: true,
91+
},
92+
});
93+
94+
expect(envHttpProxyAgentCtor).toHaveBeenCalledWith({
95+
connect: {
96+
autoSelectFamily: true,
97+
lookup,
98+
},
99+
proxyTls: {
100+
autoSelectFamily: true,
101+
},
102+
});
103+
});
104+
105+
it("keeps explicit proxy routing intact", () => {
106+
const lookup = vi.fn() as unknown as PinnedHostname["lookup"];
107+
const pinned: PinnedHostname = {
108+
hostname: "api.telegram.org",
109+
addresses: ["149.154.167.220"],
110+
lookup,
111+
};
112+
113+
createPinnedDispatcher(pinned, {
114+
mode: "explicit-proxy",
115+
proxyUrl: "http://127.0.0.1:7890",
116+
proxyTls: {
117+
autoSelectFamily: false,
118+
},
119+
});
120+
121+
expect(proxyAgentCtor).toHaveBeenCalledWith({
122+
uri: "http://127.0.0.1:7890",
123+
proxyTls: {
124+
autoSelectFamily: false,
125+
},
126+
});
127+
});
37128
});

‎src/infra/net/ssrf.ts‎

Lines changed: 48 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { lookup as dnsLookupCb, type LookupAddress } from "node:dns";
22
import { lookup as dnsLookup } from "node:dns/promises";
3-
import { Agent, type Dispatcher } from "undici";
3+
import { Agent, EnvHttpProxyAgent, ProxyAgent, type Dispatcher } from "undici";
44
import {
55
extractEmbeddedIpv4FromIpv6,
66
isBlockedSpecialUseIpv4Address,
@@ -255,6 +255,22 @@ export type PinnedHostname = {
255255
lookup: typeof dnsLookupCb;
256256
};
257257

258+
export type PinnedDispatcherPolicy =
259+
| {
260+
mode: "direct";
261+
connect?: Record<string, unknown>;
262+
}
263+
| {
264+
mode: "env-proxy";
265+
connect?: Record<string, unknown>;
266+
proxyTls?: Record<string, unknown>;
267+
}
268+
| {
269+
mode: "explicit-proxy";
270+
proxyUrl: string;
271+
proxyTls?: Record<string, unknown>;
272+
};
273+
258274
function dedupeAndPreferIpv4(results: readonly LookupAddress[]): string[] {
259275
const seen = new Set<string>();
260276
const ipv4: string[] = [];
@@ -329,11 +345,37 @@ export async function resolvePinnedHostname(
329345
return await resolvePinnedHostnameWithPolicy(hostname, { lookupFn });
330346
}
331347

332-
export function createPinnedDispatcher(pinned: PinnedHostname): Dispatcher {
333-
return new Agent({
334-
connect: {
335-
lookup: pinned.lookup,
336-
},
348+
function withPinnedLookup(
349+
lookup: PinnedHostname["lookup"],
350+
connect?: Record<string, unknown>,
351+
): Record<string, unknown> {
352+
return connect ? { ...connect, lookup } : { lookup };
353+
}
354+
355+
export function createPinnedDispatcher(
356+
pinned: PinnedHostname,
357+
policy?: PinnedDispatcherPolicy,
358+
): Dispatcher {
359+
if (!policy || policy.mode === "direct") {
360+
return new Agent({
361+
connect: withPinnedLookup(pinned.lookup, policy?.connect),
362+
});
363+
}
364+
365+
if (policy.mode === "env-proxy") {
366+
return new EnvHttpProxyAgent({
367+
connect: withPinnedLookup(pinned.lookup, policy.connect),
368+
...(policy.proxyTls ? { proxyTls: { ...policy.proxyTls } } : {}),
369+
});
370+
}
371+
372+
const proxyUrl = policy.proxyUrl.trim();
373+
if (!policy.proxyTls) {
374+
return new ProxyAgent(proxyUrl);
375+
}
376+
return new ProxyAgent({
377+
uri: proxyUrl,
378+
proxyTls: { ...policy.proxyTls },
337379
});
338380
}
339381

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import { resolveTelegramTransport } from "../telegram/fetch.js";
3+
import { fetchRemoteMedia } from "./fetch.js";
4+
5+
const undiciFetch = vi.hoisted(() => vi.fn());
6+
const AgentCtor = vi.hoisted(() =>
7+
vi.fn(function MockAgent(
8+
this: { options?: Record<string, unknown> },
9+
options?: Record<string, unknown>,
10+
) {
11+
this.options = options;
12+
}),
13+
);
14+
const EnvHttpProxyAgentCtor = vi.hoisted(() =>
15+
vi.fn(function MockEnvHttpProxyAgent(
16+
this: { options?: Record<string, unknown> },
17+
options?: Record<string, unknown>,
18+
) {
19+
this.options = options;
20+
}),
21+
);
22+
const ProxyAgentCtor = vi.hoisted(() =>
23+
vi.fn(function MockProxyAgent(
24+
this: { options?: Record<string, unknown> | string },
25+
options?: Record<string, unknown> | string,
26+
) {
27+
this.options = options;
28+
}),
29+
);
30+
31+
vi.mock("undici", () => ({
32+
Agent: AgentCtor,
33+
EnvHttpProxyAgent: EnvHttpProxyAgentCtor,
34+
ProxyAgent: ProxyAgentCtor,
35+
fetch: undiciFetch,
36+
}));
37+
38+
describe("fetchRemoteMedia telegram network policy", () => {
39+
type LookupFn = NonNullable<Parameters<typeof fetchRemoteMedia>[0]["lookupFn"]>;
40+
41+
afterEach(() => {
42+
undiciFetch.mockReset();
43+
AgentCtor.mockClear();
44+
EnvHttpProxyAgentCtor.mockClear();
45+
ProxyAgentCtor.mockClear();
46+
vi.unstubAllEnvs();
47+
});
48+
49+
it("preserves Telegram resolver transport policy for file downloads", async () => {
50+
const lookupFn = vi.fn(async () => [
51+
{ address: "149.154.167.220", family: 4 },
52+
]) as unknown as LookupFn;
53+
undiciFetch.mockResolvedValueOnce(
54+
new Response(new Uint8Array([0xff, 0xd8, 0xff, 0x00]), {
55+
status: 200,
56+
headers: { "content-type": "image/jpeg" },
57+
}),
58+
);
59+
60+
const telegramTransport = resolveTelegramTransport(undefined, {
61+
network: {
62+
autoSelectFamily: true,
63+
dnsResultOrder: "verbatim",
64+
},
65+
});
66+
67+
await fetchRemoteMedia({
68+
url: "https://api.telegram.org/file/bottok/photos/1.jpg",
69+
fetchImpl: telegramTransport.sourceFetch,
70+
dispatcherPolicy: telegramTransport.pinnedDispatcherPolicy,
71+
lookupFn,
72+
maxBytes: 1024,
73+
ssrfPolicy: {
74+
allowedHostnames: ["api.telegram.org"],
75+
allowRfc2544BenchmarkRange: true,
76+
},
77+
});
78+
79+
const init = undiciFetch.mock.calls[0]?.[1] as
80+
| (RequestInit & {
81+
dispatcher?: {
82+
options?: {
83+
connect?: Record<string, unknown>;
84+
};
85+
};
86+
})
87+
| undefined;
88+
89+
expect(init?.dispatcher?.options?.connect).toEqual(
90+
expect.objectContaining({
91+
autoSelectFamily: true,
92+
autoSelectFamilyAttemptTimeout: 300,
93+
lookup: expect.any(Function),
94+
}),
95+
);
96+
});
97+
98+
it("keeps explicit proxy routing for file downloads", async () => {
99+
const { makeProxyFetch } = await import("../telegram/proxy.js");
100+
const lookupFn = vi.fn(async () => [
101+
{ address: "149.154.167.220", family: 4 },
102+
]) as unknown as LookupFn;
103+
undiciFetch.mockResolvedValueOnce(
104+
new Response(new Uint8Array([0x25, 0x50, 0x44, 0x46]), {
105+
status: 200,
106+
headers: { "content-type": "application/pdf" },
107+
}),
108+
);
109+
110+
const telegramTransport = resolveTelegramTransport(makeProxyFetch("http://127.0.0.1:7890"), {
111+
network: {
112+
autoSelectFamily: false,
113+
dnsResultOrder: "ipv4first",
114+
},
115+
});
116+
117+
await fetchRemoteMedia({
118+
url: "https://api.telegram.org/file/bottok/files/1.pdf",
119+
fetchImpl: telegramTransport.sourceFetch,
120+
dispatcherPolicy: telegramTransport.pinnedDispatcherPolicy,
121+
lookupFn,
122+
maxBytes: 1024,
123+
ssrfPolicy: {
124+
allowedHostnames: ["api.telegram.org"],
125+
allowRfc2544BenchmarkRange: true,
126+
},
127+
});
128+
129+
const init = undiciFetch.mock.calls[0]?.[1] as
130+
| (RequestInit & {
131+
dispatcher?: {
132+
options?: {
133+
uri?: string;
134+
};
135+
};
136+
})
137+
| undefined;
138+
139+
expect(init?.dispatcher?.options?.uri).toBe("http://127.0.0.1:7890");
140+
expect(ProxyAgentCtor).toHaveBeenCalled();
141+
});
142+
});

‎src/media/fetch.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import path from "node:path";
22
import { fetchWithSsrFGuard, withStrictGuardedFetchMode } from "../infra/net/fetch-guard.js";
3-
import type { LookupFn, SsrFPolicy } from "../infra/net/ssrf.js";
3+
import type { LookupFn, PinnedDispatcherPolicy, SsrFPolicy } from "../infra/net/ssrf.js";
44
import { detectMime, extensionForMime } from "./mime.js";
55
import { readResponseWithLimit } from "./read-response-with-limit.js";
66

@@ -35,6 +35,7 @@ type FetchMediaOptions = {
3535
readIdleTimeoutMs?: number;
3636
ssrfPolicy?: SsrFPolicy;
3737
lookupFn?: LookupFn;
38+
dispatcherPolicy?: PinnedDispatcherPolicy;
3839
};
3940

4041
function stripQuotes(value: string): string {
@@ -92,6 +93,7 @@ export async function fetchRemoteMedia(options: FetchMediaOptions): Promise<Fetc
9293
readIdleTimeoutMs,
9394
ssrfPolicy,
9495
lookupFn,
96+
dispatcherPolicy,
9597
} = options;
9698

9799
let res: Response;
@@ -106,6 +108,7 @@ export async function fetchRemoteMedia(options: FetchMediaOptions): Promise<Fetc
106108
maxRedirects,
107109
policy: ssrfPolicy,
108110
lookupFn,
111+
dispatcherPolicy,
109112
}),
110113
);
111114
res = result.response;

0 commit comments

Comments
 (0)