🪢 Langfuse 图解教程Langfuse Visual Guide 第九部分 · 自动化与集成Part 9 · Automation & Integrations 44 / 55
第九部分 · 自动化与集成Part 9 · Automation & Integrations

自动化与 webhookAutomations & webhooks

🧭 读前Before you start
先读 第30课 的执行流水线与 第14课 的队列,本课讲自动化与 webhook(含 SSRF 防护)。
Read Lesson 30 (the execution pipeline) and Lesson 14 (the queue); this lesson covers automations and webhooks (incl. SSRF defense).

第 33 课的监控告警要送到人手里、prompt 改了要通知外部系统、新 trace 来了要触发下游流程——这些「当 X 发生,就做 Y」的联动,由 Langfuse 的自动化(Automation)驱动:一个 Trigger(触发器,何时)绑一个 Action(动作,做什么)。这一课讲它的数据模型,但真正的重头戏,是一个绕不开的安全话题:当 Action 是 webhook(让 Langfuse 的服务器去访问用户填的任意 URL)时,怎么防住 SSRF——别让用户把你的服务器当跳板,去打内网、偷云凭证。 你会看到一套教科书级的纵深防御:协议白名单、端口白名单、内网 IP 黑名单、云元数据地址黑名单、解析失败即拦截,再加上超时、重试、签名、自动停用。「用户给我们一个 URL、我们去请求它」——这是所有 Web 系统里最危险的功能之一,这一课讲清楚它该怎么做才安全。

📋 生活类比
自动化像家里的「智能联动」:当门铃响(Trigger),就开走廊灯(Action)。简单、好用。但 webhook 这种 Action 藏着一个危险:它让 Langfuse 的服务器,去访问用户填写的任意地址。 这就好比你雇了个跑腿小哥,他会忠实地去你写的任何地址送信。平时没问题——可要是有人写的地址是「去公司机房,把保险柜钥匙拍张照带回来」(指向内网服务或云厂商的元数据接口),小哥照办,机密就泄了。这就是 SSRF(服务端请求伪造):攻击者借你的服务器之手,去够它自己够不到的内部资源。防住它的办法,是给小哥一张「禁止前往」清单:本机地址、内网地址、那个专门存着云凭证的 169.254.169.254……一律不去,地址看不懂的也一律不去(宁可错拦,不可放过)。

自动化 = 触发器 → 动作

数据模型是经典的「IFTTT」三件套。Trigger 定义「何时」:eventSource(什么对象,如 trace、prompt)+ eventActions(什么变化,如 created/updated/deleted)+ filter(额外条件)。Action 定义「做什么」:type(WEBHOOK / SLACK / GITHUB_DISPATCH)+ config(如 webhook 的 url/method/headers/secretId)。Automation 把一个 Trigger 绑到一个 Action。每次触发,留一条 AutomationExecution 记录(状态、输入、输出、报错)。

当 X 发生(Trigger)→ 就做 Y(Action) 一个事件监控告警/prompt改/新trace Trigger(何时)eventSource: trace/prompteventActions: created/updatedfilter: 额外条件 · status ACTIVE Action(做什么)WEBHOOK / SLACK / GITHUB_DISPATCH config: { url, method, headers, secretId }每种 type 的结构化配置 AutomationExecutionstatus: PENDING→COMPLETED/ERRORinput/output/error 留痕 匹配则 Automation 把一个 Trigger 绑一个 Action;这正是第33课监控告警「发布到 WebhookQueue 后」的去处——由某个 webhook Action 投递出去 AutomationExecution 像第30课 JobExecution、第32课标注 item——又一个「落库的执行记录」状态机
Trigger → Action 的 IFTTT 模型:schema.prisma:1635 Trigger(eventSource/eventActions/filter/status)、:1613 Action(type WEBHOOK/SLACK/GITHUB_DISPATCH + config Json)、:1659 Automation(绑定二者)、:1690 AutomationExecution(PENDING/COMPLETED/ERROR/CANCELLED + input/output/error)。第 33 课监控告警就经此投递。
示例:一次 webhook 投递(载荷 + 签名) POST https://your-app.com/hooks/langfuse 请求头 headers content-type: application/json user-agent: Langfuse/1.0 x-langfuse-signature: t=1719500000,v1=3a7bf2c8… 请求体 body (JSON) { id: "evt_9f3a…", timestamp: "2026-06-27T10:00Z", type: "prompt-version", apiVersion: "v1", action: "created", prompt: { name: "support-reply", version: 3, type: "text" } } 🔐 验签 (HMAC-SHA256) signed = "{t}.{body}" hmac = HMAC(secret, signed) compare == v1 ? ✓ 一致才信任,否则丢弃
每次投递都自带「这是我发的」证明(字段取自 domain/webhooks.ts 与 encryption/signature.ts;值为示例):Langfuse 把事件 POST 到你的 URL,体是 prompt-version 事件 JSON(type/apiVersion/action=created|updated|deleted/prompt)。关键在 x-langfuse-signature: t=…,v1=…——createSignatureHeader 对 "{timestamp}.{body}" 算 HMAC-SHA256。你的接收端用同一个密钥重算、比对 v1,一致才信任。于是别人即使知道你的 URL 也伪造不出合法请求(配合第 44 课的 SSRF 出站防护,一进一出都设防)。
何时Trigger
守着事件流:eventSource(盯哪类对象)+ eventActions(哪种变化)+ filter(更细的条件,和第 23 课同款过滤)。status=ACTIVE 才生效——可随时停用而不删除。
做什么Action
三种动作类型:WEBHOOK(调用户给的 URL,本课重点)、SLACK(发到频道,第 45 课)、GITHUB_DISPATCH(触发 GitHub workflow)。config 用结构化 JSON 存各自参数,secretId 指向加密保管的密钥(第 39 课)。
留痕AutomationExecution
每次触发都落一行:状态机 PENDING→COMPLETED/ERROR/CANCELLED,连 input/output/error 一并存——和第 30 课 JobExecution、第 32 课标注 item 是同一种「有状态、可追溯的执行记录」。

webhook 的命门:纵深防御挡住 SSRF

WEBHOOK 这个 Action,本质是「让 Langfuse 的服务器去请求一个用户填的 URL」。这是 SSRF(Server-Side Request Forgery,服务端请求伪造)的经典温床:攻击者把 URL 填成 http://169.254.169.254/...(云元数据接口,能拿到你的临时 AK/SK)或 http://localhost:6379(你的内部 Redis),借你服务器之手够到它本不该够到的东西。Langfuse 的防御不是一道墙,而是层层叠叠的多道闸——任何一道漏了,还有下一道。

用户填的 URL 要闯过五道闸,全过才放行 用户填的 URL合法:https://hooks.x.com/…恶意:http://169.254.169.254http://localhost:6379file:///etc/passwd 闸1 协议仅 http/https 闸2 端口仅 80 / 443 闸3 主机名黑 localhost/metadata 闸4 IP 段黑 内网/loopback/link-local 闸5 fail-closed解析不了?直接拦 全过 → 放行请求带超时/重试/签名 任一不过 → 拒绝恶意 URL 全被挡在外 外部接收方验签确认来自 Langfuse 关键:IP 校验在「请求时」对解析出的真实 IP 做,防 DNS-rebinding(域名先解析成合法 IP、临门一脚切到内网 IP)
纵深防御,层层设防:validateWebhookURL(validation.ts:35)只放 http/https、只放端口 80/443;ipBlocking.ts 的 isHostnameBlocked 黑掉 localhost / metadata.google.internal / 169.254.169.254,isIPBlocked 黑掉 RFC1918 内网、loopback、link-local 等 CIDR,且 IP 解析失败就默认拦截(fail-closed)。校验在请求时对真实 IP 做,防 DNS-rebinding。
⚠️ 「让服务器去请求用户填的 URL」是 Web 系统最危险的功能之一
webhook 会让 Langfuse 去请求用户填的任意 URL——SSRF 的经典温床(http://169.254.169.254 偷云临时凭证、http://localhost:6379 打内部 Redis)。关键防线:IP 校验必须在「请求时」对真正解析出的 IP 做、解析失败即拦截(fail-closed)。否则 DNS-rebinding 会用「创建时解析到合法公网 IP、请求那一刻切到内网 IP」绕过你创建时的白名单。安全检查要贴着危险动作发生的那一刻做。
packages/shared/src/server/webhooks/ipBlocking.ts · validation.tsSSRF 防御
// 闸4:黑名单 CIDR——内网、本机、云元数据所在的链路本地段全拦
const BLOCKED_CIDRS = ["10.0.0.0/8", "127.0.0.0/8", "169.254.0.0/16"/* AWS/GCP 元数据 */,
                       "172.16.0.0/12", "192.168.0.0/16", "::1/128", …];
export function isIPBlocked(ip) { /* 命中任一段 → true;解析失败 → 也 true(宁可错拦)*/ }

// 闸3:主机名黑名单——连域名都直接禁
const blockedPatterns = ["localhost", "*.localhost",
  "metadata.google.internal", "169.254.169.254", …];   // 云元数据端点

// 闸1+2:协议与端口白名单(validation.ts)
if (!["http:", "https:"].includes(protocol)) throw "Only HTTP and HTTPS allowed";
if (![80, 443].includes(port))            throw "Only ports 80 and 443 allowed";

☁️ 云元数据接口

169.254.169.254 / metadata.google.internal——AWS/GCP 实例元数据。最致命:能拿到机器的临时云凭证(AK/SK),进而接管整个云账号。被主机名黑名单 + link-local CIDR(169.254.0.0/16)双重拦截。

🔌 内网服务

localhost:6379 的 Redis、内部管理后台、数据库……往往因为「反正在内网」而不设防。被 loopback(127.0.0.0/8) + RFC1918(10/8,172.16/12,192.168/16) CIDR 黑名单拦截。

📄 非 HTTP 协议

file:///etc/passwd 读本地文件、gopher:// 打其它 TCP 服务……被协议白名单(仅 http/https)从源头掐死,连解析 IP 都轮不到。

不止 SSRF:投递还要稳、要可信

挡住 SSRF 只是「不出事」。要让 webhook 真正可靠又可信,投递环节还有几道操作性的硬化——它们共同构成「请求外部世界」这件事的完整工程姿态:

向外部世界发请求:6 道硬化,各防一种「外部世界怎么坑你」 Langfuse worker SSRF 防御 防借你打内网/偷云凭证 签名 HMAC 防伪造/篡改 · x-langfuse-signature 状态校验 2xx 防悄悄失败被当成功 超时 AbortController 防对方挂起拖死 worker 重试(指数退避) 防临时抖动 → 最终送达 自动停用 防对死端点无限锤 外部 endpoint 用户填的 URL 凡向外部世界发请求,一律当不可信、不可靠对待
硬化怎么做防什么
SSRF 防御协议/端口白名单 + IP/主机名黑名单 + fail-closed(上一节)借你服务器打内网、偷云凭证
签名用密钥对 payload 算 HMAC,放进 x-langfuse-signature 头接收方可验签——确认确实来自 Langfuse、未被篡改
超时AbortController + LANGFUSE_WEBHOOK_TIMEOUT_MS对方慢/挂起时不拖死 worker
重试backOff 指数退避对方临时抖动时最终送达
状态校验要求返回 2xx,否则记 ERROR悄悄失败被当成功
自动停用反复失败的 trigger 自动禁用对着一个已死的端点无限锤

把这张表读完,你会发现一条清晰的工程信条:凡是「向外部世界发起请求」,都要当成不可信、不可靠来对待。外部 URL 可能是恶意的(→ SSRF 防御)、可能很慢(→ 超时)、可能临时挂(→ 重试)、可能永久挂(→ 自动停用);而你发出去的东西,对方也需要确认是不是真的来自你(→ 签名)。每一道防护都对应一种「外部世界会怎么坑你」的具体设想——安全与健壮,从来不是一个开关,而是一摞针对具体威胁的具体防护。

🎯 设计取舍
为什么 SSRF 值得动用这么多道防御?它到底有多危险? 因为它能把一个看似无害的功能(「我们帮你回调一个 URL」)变成直通你内网核心的隧道。最致命的目标是 169.254.169.254——AWS/GCP 的实例元数据接口:任何能让你服务器去请求它的人,都可能拿到这台机器的临时云凭证(AK/SK),进而接管你的整个云账号。其次是内网服务:你的 Redis、内部管理后台、数据库,往往因为「反正在内网」而不设防——可一旦攻击者能借你的 webhook 之手去请求它们,这层「内网即安全」的假设就崩了。SSRF 的可怕,正在于它绕过了所有边界:防火墙挡的是外面进来的,而 SSRF 是从你内部往外打,畅通无阻。所以它配得上纵深防御——而且每道闸都要fail-closed:拿不准的、解析不了的,一律当危险处理。安全代码的默认答案是「拒绝」,不是「放行」。

为什么校验要放在「请求时」对解析出的真实 IP 做,而不是创建 webhook 时检查一下 URL 就完事? 因为有个阴险的攻击叫 DNS-rebinding(DNS 重绑定):攻击者控制一个域名,创建 webhook 时把它解析到一个合法的公网 IP(顺利过审),等到 Langfuse 真正发请求时,再把这个域名临门一脚切换解析到 169.254.169.254 或内网 IP。如果你只在创建时校验,就被这一手骗过去了。Langfuse 的做法是把 IP 校验下沉到实际发起请求的那一刻,对当时真正解析出的 IP 判定——攻击者再怎么切换 DNS,临门那一刻的真实 IP 也逃不过这道闸。安全检查必须贴着「真正危险动作发生的那一刻」做,而不是提前在一个可能已经过期的快照上做。
🎯 本课要点
  • 自动化 = Trigger → Action:经典 IFTTT 模型。Trigger(eventSource/eventActions/filter 定「何时」)绑 Action(WEBHOOK/SLACK/GITHUB_DISPATCH 定「做什么」),AutomationExecution 留每次执行的状态记录。第 33 课监控告警经此投递。
  • webhook 的命门是 SSRF:让服务器请求用户填的 URL,攻击者可借此打内网、偷 169.254.169.254 的云凭证——「用户给 URL 我们去请求」是 Web 系统最危险的功能之一。
  • 纵深防御挡 SSRF:协议白名单(http/https)+ 端口白名单(80/443)+ 主机名黑名单(localhost/metadata)+ IP CIDR 黑名单(内网/loopback/link-local)+ fail-closed(解析不了就拦)。任一道都可能救命。
  • 校验在请求时做:对实际解析出的真实 IP 判定,防 DNS-rebinding(创建时解析到合法 IP、请求时切到内网)。安全检查要贴着危险动作发生的那一刻。
  • 投递还要稳要可信:HMAC 签名(x-langfuse-signature,让接收方验真)+ 超时 + 指数退避重试 + 2xx 校验 + 反复失败自动停用——向外部世界发请求,一律当不可信、不可靠对待。

🧪 自测 · 想一想为什么这么设计

1. webhook 这个 Action 让 Langfuse 的服务器去请求「用户填写的任意 URL」。这为什么是个危险的安全面,攻击者会怎么利用?
  1. SSRF(服务端请求伪造):攻击者把 URL 填成内网地址或 169.254.169.254(云元数据接口),借你服务器之手够到它本不该够到的内部资源——尤其能偷到这台机器的临时云凭证(AK/SK),进而接管整个云账号
  2. webhook 消耗的带宽太大
  3. 用户填的 URL 可能拼错,导致 404
  4. webhook 会拖慢页面加载速度
看答案与解析 点击展开
答案:A。「用户给一个 URL、我们去请求它」是所有 Web 系统里最危险的功能之一。攻击者不在乎对方返回什么页面,而是借你的服务器当跳板:请求 169.254.169.254(AWS/GCP 实例元数据接口)拿临时云凭证、请求 localhost:6379 打你的内部 Redis、请求内部管理后台……这些资源往往因为「反正在内网」而不设防。SSRF 的可怕在于它绕过了所有边界:防火墙挡外面进来的,SSRF 是从你内部往外打。
2. Langfuse 的 IP 黑名单校验有两个值得注意的设计:解析失败时默认「拦截」,而且校验放在「真正发请求那一刻」对解析出的真实 IP 做。这两点各防住了什么?
  1. 都是为了节省内存
  2. 都是为了兼容 IPv6
  3. 都是为了让校验跑得更快
  4. fail-closed(拿不准就拦)防的是「校验代码本身出错或遇到怪输入时悄悄放行」;请求时校验真实 IP 防的是 DNS-rebinding——攻击者创建时把域名解析到合法 IP 过审、请求时再切换解析到内网 IP
看答案与解析 点击展开
答案:D。fail-closed 是安全代码的默认信条:拿不准的、解析不了的,一律当危险处理——默认答案是「拒绝」不是「放行」(ipBlocking.ts:88 注释 'block it to be safe')。DNS-rebinding 则是个阴险攻击:只在创建时校验就会被骗,因为域名解析结果可以临门一脚切换。Langfuse 把 IP 校验下沉到实际发请求那一刻、对当时真正解析出的 IP 判定,攻击者再切 DNS 也逃不过。安全检查必须贴着「危险动作真正发生的那一刻」做。
3. 自动化的数据模型是 Trigger → Action,每次执行还落一条 AutomationExecution 记录。这个 AutomationExecution 和前面哪些课的设计是「同一种东西」?
  1. 和第30课 eval 的 JobExecution、第32课人工标注的 queue item 是同一种「落库的、有状态的、可追溯的执行记录」——状态机 PENDING→COMPLETED/ERROR,连 input/output/error 一并存,便于排查与重试
  2. 和 ClickHouse 的 trace 表是同一种东西
  3. 和 Redis 缓存是同一种东西
  4. 和 Prompt 的版本号是同一种东西
看答案与解析 点击展开
答案:A。Langfuse 反复用同一个模式:凡是「异步执行、可能失败、要能排查」的动作,就给它一张表、一个状态机、一份 input/output/error 留痕。eval 的 JobExecution(第30课)、标注 item(第32课)、这里的 AutomationExecution,本质都是「有状态、可追溯的执行记录」。认出这个反复出现的骨架,新功能就不再陌生:先问『它的执行记录长什么样、状态机怎么流转』。
💭 发散思考(没有标准答案,动手或动脑想想)
  • 这一课的 webhook SSRF 防御是「纵深防御」的范本:协议白名单、端口白名单、主机名黑名单、IP CIDR 黑名单、fail-closed、请求时校验……一道接一道,而不是一道大墙。请结合你自己的经验谈谈:为什么安全设计偏爱「多道独立的闸」而不是「一道完美的墙」?这种思路除了 SSRF,还能迁移到哪些场景(鉴权、输入校验、限流)?多道防护各自独立又有什么维护成本?

Lesson 33's monitor alerts need to reach a human, a changed prompt needs to notify an external system, a new trace needs to kick off a downstream flow — all these "when X happens, do Y" linkages are driven by Langfuse Automations: a Trigger (when) bound to an Action (what to do). This lesson covers the data model, but the real headline act is an unavoidable security topic: when the Action is a webhook (Langfuse's server fetches a user-supplied arbitrary URL), how do you stop SSRF — keeping users from turning your server into a springboard to hit the internal network and steal cloud credentials. You'll see textbook-grade defense in depth: a protocol allowlist, a port allowlist, an internal-IP blocklist, a cloud-metadata-address blocklist, fail-closed on unparseable hosts, plus timeouts, retries, signing, and auto-disable. "A user gives us a URL and we fetch it" is one of the most dangerous features in any web system — this lesson spells out how to do it safely.

📋 Analogy
An automation is like a "smart home linkage": when the doorbell rings (Trigger), turn on the hallway light (Action). Simple, handy. But a webhook Action hides a danger: it makes Langfuse's server fetch any address the user types in. It's like hiring an errand runner who faithfully delivers a letter to any address you write down. Usually fine — but if someone writes "go to the company server room and snap a photo of the safe key" (pointing at an internal service or the cloud provider's metadata endpoint), the runner complies and the secret leaks. That's SSRF (Server-Side Request Forgery): the attacker borrows your server's hands to reach internal resources it could never reach on its own. The defense is to hand the runner a "do-not-go" list: localhost, internal addresses, that 169.254.169.254 that holds cloud credentials… all off-limits — and anything whose address can't be understood is off-limits too (better to wrongly block than to let through).

Automation = trigger → action

The data model is the classic "IFTTT" trio. A Trigger defines "when": eventSource (which object, e.g. trace, prompt) + eventActions (which change, e.g. created/updated/deleted) + filter (extra conditions). An Action defines "what to do": type (WEBHOOK / SLACK / GITHUB_DISPATCH) + config (e.g. a webhook's url/method/headers/secretId). An Automation binds one Trigger to one Action. Every firing leaves an AutomationExecution record (status, input, output, error).

When X happens (Trigger) → do Y (Action) an eventalert / prompt change / new trace Trigger (when)eventSource: trace/prompteventActions: created/updatedfilter: extra cond · status ACTIVE Action (what)WEBHOOK / SLACK / GITHUB_DISPATCH config: { url, method, headers, secretId }structured config per type AutomationExecutionstatus: PENDING→COMPLETED/ERRORinput/output/error kept on match An Automation binds one Trigger to one Action; this is exactly where Lesson 33's alert goes "after publishing to WebhookQueue" — delivered by some webhook Action AutomationExecution is like Lesson 30's JobExecution and Lesson 32's annotation item — yet another "persisted execution record" state machine
The IFTTT Trigger → Action model: schema.prisma:1635 Trigger (eventSource/eventActions/filter/status), :1613 Action (type WEBHOOK/SLACK/GITHUB_DISPATCH + config Json), :1659 Automation (binds the two), :1690 AutomationExecution (PENDING/COMPLETED/ERROR/CANCELLED + input/output/error). Lesson 33's monitor alerts are delivered through exactly this path.
Example: one webhook delivery (payload + signature) POST https://your-app.com/hooks/langfuse headers content-type: application/json user-agent: Langfuse/1.0 x-langfuse-signature: t=1719500000,v1=3a7bf2c8… body (JSON) { id: "evt_9f3a…", timestamp: "2026-06-27T10:00Z", type: "prompt-version", apiVersion: "v1", action: "created", prompt: { name: "support-reply", version: 3, type: "text" } } 🔐 verify (HMAC-SHA256) signed = "{t}.{body}" hmac = HMAC(secret, signed) compare == v1 ? ✓ trust only if equal, else drop
Every delivery carries proof of "I really sent this" (fields from domain/webhooks.ts and encryption/signature.ts; values illustrative): Langfuse POSTs the event to your URL with a prompt-version JSON body (type/apiVersion/action=created|updated|deleted/prompt). The key is x-langfuse-signature: t=…,v1=… — createSignatureHeader computes HMAC-SHA256 over "{timestamp}.{body}". Your receiver recomputes it with the same secret and compares v1, trusting only on a match. So even someone who knows your URL cannot forge a valid request (paired with Lesson 44's SSRF outbound guard, both directions are defended).
whenTrigger
Watches the event stream: eventSource (which object class) + eventActions (which change) + filter (finer conditions, same filtering as Lesson 23). Only fires when status=ACTIVE — you can pause it anytime without deleting.
whatAction
Three action types: WEBHOOK (call the user's URL, this lesson's focus), SLACK (post to a channel, Lesson 45), GITHUB_DISPATCH (trigger a GitHub workflow). config stores each one's params as structured JSON; secretId points to an encrypted-at-rest secret (Lesson 39).
auditAutomationExecution
Every firing writes a row: a state machine PENDING→COMPLETED/ERROR/CANCELLED, storing input/output/error too — the same kind of "stateful, traceable execution record" as Lesson 30's JobExecution and Lesson 32's annotation item.

The webhook's Achilles heel: defense in depth stops SSRF

The WEBHOOK Action is, in essence, "make Langfuse's server fetch a user-supplied URL." That's the classic breeding ground for SSRF (Server-Side Request Forgery): an attacker sets the URL to http://169.254.169.254/... (the cloud metadata endpoint, which yields your temporary AK/SK) or http://localhost:6379 (your internal Redis), reaching — through your server's hands — things it should never reach. Langfuse's defense isn't one wall but layer upon layer of gates — if any one leaks, the next still holds.

The user URL must clear five gates; only all-pass is let through user-supplied URLlegit:https://hooks.x.com/…malicious:http://169.254.169.254http://localhost:6379file:///etc/passwd gate1 protocolhttp/https only gate2 port80 / 443 only gate3 hostnameblock localhost/metadata gate4 IP rangeblock private/loopback/link-local gate5 fail-closedcan't resolve? block it all pass → sendwith timeout/retry/signature any fail → rejectmalicious URLs all blocked external receiververifies it's from Langfuse Key: the IP check runs "at request time" on the actually-resolved IP, defeating DNS-rebinding (resolve to a legit IP first, switch to an internal IP at the last second)
Defense in depth, gate after gate: validateWebhookURL (validation.ts:35) allows only http/https and only ports 80/443; ipBlocking.ts's isHostnameBlocked blocks localhost / metadata.google.internal / 169.254.169.254, and isIPBlocked blocks RFC1918 private ranges, loopback, link-local and other CIDRs, and defaults to blocking when IP resolution fails (fail-closed). The check runs at request time on the real IP, defeating DNS-rebinding.
⚠️ "Make the server fetch a user-supplied URL" is one of the web's most dangerous features
A webhook makes Langfuse request any URL the user typed — a classic SSRF vector (http://169.254.169.254 to steal temporary cloud creds, http://localhost:6379 to hit internal Redis). The key defense: the IP check must run "at request time" on the actually-resolved IP, and fail closed when resolution fails. Otherwise DNS-rebinding ("resolve to a legit public IP at creation, switch to an internal IP the moment we fetch") slips past the creation-time allowlist. Run the security check right at the moment the dangerous action happens.
packages/shared/src/server/webhooks/ipBlocking.ts · validation.tsSSRF defense
// gate4: blocklisted CIDRs — private, loopback, and the link-local cloud metadata range
const BLOCKED_CIDRS = ["10.0.0.0/8", "127.0.0.0/8", "169.254.0.0/16"/* AWS/GCP metadata */,
                       "172.16.0.0/12", "192.168.0.0/16", "::1/128", …];
export function isIPBlocked(ip) { /* in any range → true; resolution fails → also true (rather block) */ }

// gate3: hostname blocklist — even the domain name is forbidden
const blockedPatterns = ["localhost", "*.localhost",
  "metadata.google.internal", "169.254.169.254", …];   // cloud metadata endpoints

// gate1+2: protocol and port allowlists (validation.ts)
if (!["http:", "https:"].includes(protocol)) throw "Only HTTP and HTTPS allowed";
if (![80, 443].includes(port))            throw "Only ports 80 and 443 allowed";

☁️ cloud metadata endpoint

169.254.169.254 / metadata.google.internal — AWS/GCP instance metadata. The deadliest: yields the machine's temporary cloud credentials (AK/SK) and from there takeover of the whole cloud account. Blocked twice: hostname blocklist + link-local CIDR (169.254.0.0/16).

🔌 internal services

localhost:6379 Redis, internal admin panels, databases… often undefended on the assumption "it's internal anyway." Blocked by loopback (127.0.0.0/8) + RFC1918 (10/8, 172.16/12, 192.168/16) CIDR blocklist.

📄 non-HTTP protocols

file:///etc/passwd to read local files, gopher:// to hit other TCP services… killed at the source by the protocol allowlist (http/https only) — it never even reaches IP resolution.

Beyond SSRF: delivery must be reliable and trustworthy

Blocking SSRF only gets you "no disaster." To make webhooks truly reliable and trustworthy, the delivery path needs several more operational hardenings — together they form the complete engineering posture for "calling the outside world":

calling the outside world: 6 hardenings, each guarding a specific threat Langfuse worker SSRF defense vs internal-net / credential theft HMAC signature vs forgery/tamper · x-langfuse-signature 2xx status check vs silent failure timeout (AbortController) vs a hung peer dragging worker retry (backoff) vs transient blips → eventual delivery auto-disable vs hammering a dead endpoint external endpoint user-supplied URL treat every outbound request as untrusted and unreliable
HardeningHowGuards against
SSRF defenseprotocol/port allowlist + IP/hostname blocklist + fail-closed (previous section)using your server to hit the internal net, steal cloud creds
SigningHMAC the payload with a secret, put it in x-langfuse-signaturereceiver can verify — confirm it really came from Langfuse, untampered
TimeoutAbortController + LANGFUSE_WEBHOOK_TIMEOUT_MSa slow/hung peer dragging down the worker
RetrybackOff exponential backoffeventual delivery through a peer's transient blip
Status checkrequire a 2xx, else record ERRORsilent failures counted as success
Auto-disablea repeatedly-failing trigger gets disabledhammering a dead endpoint forever

Read that table and a clear engineering creed emerges: anything that "issues a request to the outside world" must be treated as untrusted and unreliable. An external URL may be malicious (→ SSRF defense), may be slow (→ timeout), may blip (→ retry), may be permanently down (→ auto-disable); and what you send out, the peer in turn needs to confirm actually came from you (→ signing). Each guard corresponds to a concrete hypothesis about "how the outside world will hurt you" — security and robustness are never one switch, but a stack of specific defenses against specific threats.

🎯 Design trade-off
Why does SSRF warrant so many layers of defense? How dangerous is it, really? Because it can turn a seemingly harmless feature ("we'll call a URL back for you") into a tunnel straight into your network's core. The deadliest target is 169.254.169.254 — AWS/GCP's instance metadata endpoint: anyone who can make your server fetch it may obtain the machine's temporary cloud credentials (AK/SK) and from there take over your entire cloud account. Next come internal services: your Redis, internal admin panels, databases — often undefended on the assumption "it's internal anyway." Once an attacker can use your webhook's hands to reach them, that "internal = safe" assumption collapses. SSRF is terrifying precisely because it bypasses every boundary: a firewall blocks what comes in from outside, but SSRF attacks outward from inside you, unimpeded. So it earns defense in depth — and every gate must be fail-closed: anything uncertain or unparseable is treated as dangerous. The default answer of secure code is "deny," not "allow."

Why run the check "at request time" on the resolved real IP, instead of validating the URL once at webhook-creation time? Because of an insidious attack called DNS-rebinding: the attacker controls a domain, resolves it to a legitimate public IP at creation time (passing review smoothly), then at the last second when Langfuse actually sends the request flips that domain to resolve to 169.254.169.254 or an internal IP. If you only validate at creation, this sleight of hand fools you. Langfuse pushes the IP check down to the very moment the request is issued, judging the IP actually resolved then — no matter how the attacker swaps DNS, the real IP at that instant can't slip past this gate. Security checks must hug "the moment the truly dangerous action happens," not be done early on a possibly-stale snapshot.
🎯 Key points
  • Automation = Trigger → Action: the classic IFTTT model. A Trigger (eventSource/eventActions/filter defines "when") binds an Action (WEBHOOK/SLACK/GITHUB_DISPATCH defines "what"); AutomationExecution keeps a status record of each run. Lesson 33's monitor alerts are delivered through this.
  • The webhook's Achilles heel is SSRF: making the server fetch a user-supplied URL lets an attacker hit the internal net and steal 169.254.169.254's cloud credentials — "user gives a URL, we fetch it" is one of the most dangerous web features.
  • Defense in depth stops SSRF: protocol allowlist (http/https) + port allowlist (80/443) + hostname blocklist (localhost/metadata) + IP CIDR blocklist (private/loopback/link-local) + fail-closed (can't resolve → block). Any one gate may be the lifesaver.
  • Check at request time: judge the actually-resolved real IP to defeat DNS-rebinding (resolve to a legit IP at creation, switch to internal at request). Security checks hug the moment the danger happens.
  • Delivery must be reliable and trustworthy too: HMAC signing (x-langfuse-signature, lets the receiver verify) + timeout + exponential-backoff retry + 2xx check + auto-disable on repeated failure — treat every outbound request as untrusted and unreliable.

🧪 Self-test - think about the design

1. The webhook Action makes Langfuse's server fetch 'any user-supplied URL'. Why is this a dangerous attack surface, and how would an attacker exploit it?
  1. SSRF (Server-Side Request Forgery): the attacker sets the URL to an internal address or 169.254.169.254 (the cloud metadata endpoint), reaching—through your server's hands—internal resources it should never reach, especially stealing this machine's temporary cloud credentials (AK/SK) and from there taking over the whole cloud account
  2. webhooks consume too much bandwidth
  3. the user's URL may be mistyped, causing 404
  4. webhooks slow down page load
Show answer & explanation click to expand
Answer: A. 'A user gives a URL and we fetch it' is one of the most dangerous features in any web system. The attacker doesn't care what page comes back; they use your server as a springboard: fetch 169.254.169.254 (the AWS/GCP instance metadata endpoint) for temporary cloud credentials, fetch localhost:6379 to hit your internal Redis, fetch internal admin panels… these are often undefended on the assumption 'it's internal anyway'. SSRF is terrifying because it bypasses every boundary: a firewall blocks what comes in, SSRF attacks outward from inside you.
2. Langfuse's IP-blocklist check has two notable designs: it defaults to 'block' when resolution fails, and it runs 'at the moment the request is actually sent' on the resolved real IP. What does each guard against?
  1. both are to save memory
  2. both are for IPv6 compatibility
  3. both are to make the check run faster
  4. fail-closed (block when uncertain) guards against 'silently letting through when the check code errors or hits weird input'; checking the real IP at request time guards against DNS-rebinding—the attacker resolves the domain to a legit IP at creation to pass review, then flips it to an internal IP at request time
Show answer & explanation click to expand
Answer: D. fail-closed is the default creed of secure code: anything uncertain or unparseable is treated as dangerous—the default answer is 'deny', not 'allow' (ipBlocking.ts:88 comment 'block it to be safe'). DNS-rebinding is insidious: validating only at creation is fooled because DNS resolution can flip at the last second. Langfuse pushes the IP check down to the moment the request is sent, judging the IP actually resolved then, so swapping DNS can't slip past. Security checks must hug 'the moment the dangerous action actually happens'.
3. The automation data model is Trigger → Action, and each run writes an AutomationExecution record. AutomationExecution is 'the same kind of thing' as designs from which earlier lessons?
  1. the same 'persisted, stateful, traceable execution record' as Lesson 30's eval JobExecution and Lesson 32's annotation queue item—a state machine PENDING→COMPLETED/ERROR, storing input/output/error too, for debugging and retry
  2. the same as the ClickHouse trace table
  3. the same as the Redis cache
  4. the same as a Prompt's version number
Show answer & explanation click to expand
Answer: A. Langfuse reuses the same pattern: any 'async, possibly-failing, must-be-debuggable' action gets a table, a state machine, and an input/output/error trail. eval's JobExecution (Lesson 30), the annotation item (Lesson 32), and AutomationExecution here are all 'stateful, traceable execution records'. Recognizing this recurring skeleton makes new features unsurprising: first ask 'what does its execution record look like, how does the state machine flow'.
💭 Open questions (no single right answer - just think or try)
  • This lesson's webhook SSRF defense is a model of 'defense in depth': protocol allowlist, port allowlist, hostname blocklist, IP CIDR blocklist, fail-closed, request-time check… gate after gate, not one big wall. Drawing on your own experience: why does security design favor 'many independent gates' over 'one perfect wall'? Beyond SSRF, where else does this idea transfer (auth, input validation, rate limiting)? What maintenance cost do independent layered defenses carry?