🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
docs(agents): add security-review skill for SSRF and recurring findings (#14087)
Steffen Schmitz352adf99939b
diff --git a/.agents/skills/backend-dev-guidelines/SKILL.md b/.agents/skills/backend-dev-guidelines/SKILL.mdindex 74861ec589..87af98729f 100644--- a/.agents/skills/backend-dev-guidelines/SKILL.md+++ b/.agents/skills/backend-dev-guidelines/SKILL.md@@ -24,6 +24,10 @@ Use this skill for backend and API work across `web/`, `worker/`, andend-to-end reference map.- Read only the specific reference file that matches the work when the scope isnarrower.+- If the task introduces a user-supplied URL, an outbound HTTP request, a new+ integration, or touches secrets, RBAC, or redirect handling, also load the+ shared [`security-review`](../security-review/SKILL.md) skill before+ designing or implementing the change.## Quick Start Checklistsdiff --git a/.agents/skills/code-review/SKILL.md b/.agents/skills/code-review/SKILL.mdindex 7ee24fa37d..e3e4a7bad4 100644--- a/.agents/skills/code-review/SKILL.md+++ b/.agents/skills/code-review/SKILL.md@@ -23,6 +23,11 @@ feature.`clickhouse-best-practices` skill.- If the review touches backend code, also use the shared`backend-dev-guidelines` skill where relevant.+- If the change accepts a user-supplied URL, adds outbound HTTP, introduces a+ new integration, or touches secrets, RBAC, or redirect handling, also use+ the shared [`security-review`](../security-review/SKILL.md) skill. Run its+ [`references/checklist.md`](../security-review/references/checklist.md)+ before signoff.## Review Prioritiesdiff --git a/.agents/skills/code-review/references/review-checklist.md b/.agents/skills/code-review/references/review-checklist.mdindex 55be1e91b3..be56603406 100644--- a/.agents/skills/code-review/references/review-checklist.md+++ b/.agents/skills/code-review/references/review-checklist.md@@ -41,6 +41,22 @@ This is the canonical shared review checklist for Langfuse.- `top-banner-offset` / `pt-banner-offset` - For sticky/fixed/absolute positioning and padding- `h-screen-with-banner` / `min-h-screen-with-banner` - For full-height containers accounting for banners+## Security++- For changes that accept a user-supplied URL, host, `endpoint`, `baseURL`,+ or webhook target, or that issue a new outbound HTTP request, run the+ shared [`security-review`](../../security-review/SKILL.md) skill and treat+ its [`outbound-url-validation.md`](../../security-review/references/outbound-url-validation.md)+ defenses (save-time validation + use-time / connection-time validation ++ redirect-time validation) as required. Plain `fetch(<userUrl>)` or SDK+ init with `endpoint: <userUrl>` without one of the canonical validators+ (`validateLlmConnectionBaseURL`, `validateWebhookURL`,+ `validateBlobStorageEndpoint`, or a new wrapper around+ `validateOutboundUrlHost`) is a finding.+- For changes that add a new integration, secret-bearing field, redirect+ follower, or RBAC scope, run the rest of the+ [`security-review/references/checklist.md`](../../security-review/references/checklist.md).+## JavaScript / TypeScript Style- use concat instead of spread to avoid stack overflow with large arraysdiff --git a/.agents/skills/security-review/SKILL.md b/.agents/skills/security-review/SKILL.mdnew file mode 100644index 0000000000..46f85398c0--- /dev/null+++ b/.agents/skills/security-review/SKILL.md@@ -0,0 +1,101 @@+---+name: security-review+description: Security review patterns for Langfuse. Use during code review, design, or planning whenever a change accepts user-supplied URLs, host/endpoint/baseURL fields, secrets, cross-tenant data, new outbound HTTP requests, new integrations (webhooks, blob storage, LLM connections, image proxies), redirect-following behavior, or new auth/permission scopes. Covers SSRF/outbound URL validation today and is intentionally extensible to other recurring security findings (tenant isolation, secret handling, redirect mishandling, file upload, RBAC scope drift).+---++# Security Review++Use this skill when reviewing or planning code that touches a security-sensitive+surface in Langfuse. It collects the recurring findings the team has seen in+external security reports so that future agents catch them at design and review+time rather than after the fact.++## When to Apply++Apply this skill when the change touches any of:++- a user-supplied URL, host, endpoint, `baseURL`, or webhook target+- a new outbound HTTP request (`fetch`, `axios`, AWS SDK client init with a+ custom `endpoint`, OpenAI/Anthropic/Bedrock client init with a custom+ `baseURL`, etc.)+- a new integration form under Settings -> Integrations or any+ admin-configurable network destination+- a new tRPC procedure or public API route that mutates project-scoped data or+ changes who can access it+- secrets, API keys, signing secrets, or encryption-at-rest fields+- redirect-following or cross-origin header handling+- file uploads, image proxies, or other binary data flowing in or out++Apply this skill during **plan mode** when designing a new integration so the+correct validation surfaces land in the plan, not in a follow-up CVE.++## How to Read This Skill++1. Open [references/checklist.md](references/checklist.md) and run the mental+ sweep against the change.+2. For each bullet that fires, open the matching topic reference.++| Topic | Open when | File |+| --- | --- | --- |+| SSRF and outbound URL validation | The change accepts or fetches a user-supplied URL, host, or endpoint | [references/outbound-url-validation.md](references/outbound-url-validation.md) |++The catalog is intentionally short today. New topic files are added as new+finding classes recur (see "Extending This Skill").++## Output Expectations (Review Mode)++When this skill is used during code review:++- List findings first, ordered by severity, with file and line references.+- For each finding, name the canonical helper or known-good call site the+ author should copy.+- For SSRF-class findings, point at [references/outbound-url-validation.md](references/outbound-url-validation.md)+ rather than re-deriving the fix.+- Call out missing **negative tests** (private-IP, cross-tenant, missing-scope)+ as findings, not as nice-to-haves.++## Output Expectations (Design / Plan Mode)++When this skill is used while planning:++- Restate which surfaces the new feature exposes (forms, public API routes,+ worker entrypoints).+- For each surface that matches a checklist trigger, name the validator or+ helper that must be invoked and at which layer (save-time, use-time,+ connection-time, redirect-time).+- Treat "we will validate later" as a design defect: validation belongs in the+ same change that introduces the surface.++## Extending This Skill++Add a new `references/<topic>.md` whenever a security finding recurs across+features or PR reviews. Keep each reference narrow and concrete:++1. Threat in plain language (one paragraph).+2. Canonical helpers in this repo, with paths.+3. Known-good call sites that can be copied.+4. Required defenses (save-time, use-time, transport-time, etc.).+5. Anti-patterns to flag in review.++Then add a one-line trigger to [references/checklist.md](references/checklist.md)+pointing at the new topic file, and add a row to the table above.++Candidates for future references (do not add until a real finding recurs):++- Tenant isolation (`projectId` filters across Prisma and ClickHouse)+- Secret handling and encryption-at-rest read paths+- Redirect mishandling and sensitive-header propagation+- File upload validation and content-type sniffing+- RBAC scope drift on new tRPC/public API endpoints+- Signed URL scoping (expiry, path, method)+- Public API rate limiting and auth boundary checks++## Integration With Other Skills++- The shared `code-review` skill should defer here for any change that matches+ the triggers above; see [code-review/SKILL.md](../code-review/SKILL.md).+- The shared `backend-dev-guidelines` skill should defer here when adding+ outbound HTTP, integration config, or URL-accepting procedures; see+ [backend-dev-guidelines/SKILL.md](../backend-dev-guidelines/SKILL.md).+- Confirmed issues with reproduction evidence go through `linear-bug-triage`+ for Linear handoff.diff --git a/.agents/skills/security-review/references/checklist.md b/.agents/skills/security-review/references/checklist.mdnew file mode 100644index 0000000000..cf1a76c8fa--- /dev/null+++ b/.agents/skills/security-review/references/checklist.md@@ -0,0 +1,74 @@+# Security Review Checklist++Run this list mentally on every relevant change. For each bullet, either find+that it does not apply, or confirm the listed mitigation is present in the+diff. Each bullet links to the topic reference that owns the detail.++## User-Supplied URLs and Outbound Requests++- Does the change accept a URL, host, `endpoint`, `baseURL`, webhook target,+ or any field that becomes the destination of an outbound HTTP request?+ - If yes, see [outbound-url-validation.md](outbound-url-validation.md).+ - Required: a save-time validator on the mutation/API route **and** use-time+ or connection-time validation when the request is issued, including+ redirects. Raw `fetch(userUrl)` or SDK init with `endpoint: userUrl`+ without that wiring is a finding.++- Does the change add a new "integration" (Settings -> Integrations, new+ webhook destination, new storage backend, new LLM provider, new image+ proxy) that lets an admin configure a host?+ - If yes, see [outbound-url-validation.md](outbound-url-validation.md).+ - Required: new env-driven allowlist trio (host / IPs / IP segments) for+ self-hosted, plus strict Cloud enforcement.++- Does the change follow redirects on a user-controlled URL with plain+ `fetch()`?+ - If yes, see [outbound-url-validation.md](outbound-url-validation.md)+ (Redirect Handling). Required: `fetchWithSecureRedirects` with the+ matching validator.++## Tenant Isolation++- Does every new Prisma query on a project-scoped table include `projectId`+ in the `where` clause?+- Does every new ClickHouse query on a project-scoped table include+ `project_id = {projectId: String}`?+- Does every new tRPC procedure use `protectedProjectProcedure` (or+ equivalent) and call `throwIfNoProjectAccess` with the right scope?+- Does every new public API route go through `withMiddlewares` ++ `createAuthedProjectAPIRoute` (or the equivalent organization variant) with+ the right scope?++These are enforced today by the repo-wide review checklist in+[../../code-review/references/review-checklist.md](../../code-review/references/review-checklist.md);+restate them here so the security sweep stays self-contained.++## Secrets and Credentials++- Are new secrets stored encrypted at rest (e.g. via `encrypt` / `decrypt`+ from `@langfuse/shared/encryption`) and never returned through `get`/list+ endpoints?+- Are secrets omitted from API responses (`select` / `omit` in Prisma) and+ from logs?+- Are new env vars added to `.env*.example` files and validated via the+ package `env.mjs/ts`, not read from `process.env` directly?++## Audit Logging++- Do sensitive mutations (integration config changes, role or scope changes,+ exports, deletions) emit `auditLog` with the right `action` and+ `resourceType`? Match existing wiring in+ `web/src/features/blobstorage-integration/blobstorage-integration-router.ts`+ and similar routers.++## Negative Tests++- Does the change include tests that prove **blocked** inputs are rejected+ (private IPs, cross-tenant IDs, missing scope, http: on Cloud)? Missing+ negative coverage on a security-sensitive surface is a finding.++## Extending++When a new finding class starts to recur in PR reviews or security reports,+add a one-line bullet here pointing at a new `references/<topic>.md`. Do not+restate the detail in this checklist; keep it as the trigger surface.diff --git a/.agents/skills/security-review/references/outbound-url-validation.md b/.agents/skills/security-review/references/outbound-url-validation.mdnew file mode 100644index 0000000000..3b3617fc68--- /dev/null+++ b/.agents/skills/security-review/references/outbound-url-validation.md@@ -0,0 +1,165 @@+# Outbound URL Validation (SSRF)++## Threat++Any Langfuse code path that issues an outbound HTTP request to a URL derived+from user input (mutation form, public API field, integration config, image+proxy) can be coerced into Server-Side Request Forgery. The high-value+internal targets in Langfuse's deployment topology include:++- Cloud instance metadata services (`169.254.169.254`, IMDSv2 endpoints)+- Internal Postgres, ClickHouse, Redis, S3/MinIO, queue admin UIs+- Loopback admin interfaces (`127.0.0.1`, `localhost`, Docker API on+ `2375/2376`)+- Kubernetes API server and other in-cluster control planes+- Any RFC1918 / RFC6598 / IPv6 ULA range routable from the pod or container++Even when the surface requires `integrations:CRUD` or admin scope, the+attacker model assumes the credentialed user is malicious or compromised;+SSRF lets them pivot from app-level admin to network-level access that the+deployment topology otherwise denies.++## Canonical Helpers++All under `packages/shared/src/server/outbound-url/`:++- [`parseOutboundUrl(urlString)`](../../../../packages/shared/src/server/outbound-url/validation.ts)+ — safe parse. Rejects embedded credentials, invalid encoding, and bad URL+ syntax. **Use this instead of `new URL(...)` for any user-supplied URL.**+- [`validateOutboundUrlHost({ url, whitelist, logContext, shouldSkipDnsCheckForLiteralIps })`](../../../../packages/shared/src/server/outbound-url/validation.ts)+ — checks hostname blocklist, IP literal blocklist, and forward DNS+ resolution against blocked CIDRs (defends DNS rebinding by resolving every+ A/AAAA plus the local `getaddrinfo` view).+- [`addSecureOutboundConnectionValidation(options, ...)`](../../../../packages/shared/src/server/outbound-url/connection.ts)+ — attaches connect-time IP validation to a `fetch` request so the TCP peer+ is re-validated after DNS resolution, not just at save time.+- [`fetchWithSecureRedirects(...)`](../../../../packages/shared/src/server/outbound-url/fetch.ts)+ — manual redirect handling. Validates each `Location` hop with the+ caller-supplied validator and strips sensitive headers (`Authorization`,+ `Cookie`, signing headers) on cross-origin redirects.++Surface-specific wrappers (reuse these rather than rolling your own):++- LLM base URL:+ [`validateLlmConnectionBaseURL`](../../../../packages/shared/src/server/llm/baseUrlValidation.ts)+- Webhook URL:+ [`validateWebhookURL`](../../../../packages/shared/src/server/webhooks/validation.ts)+- Blob storage endpoint:+ [`validateBlobStorageEndpoint`](../../../../packages/shared/src/server/services/blobStorageEndpointValidation.ts)+ and the companion+ [`blobStorageEndpointConnectionValidationOptions`](../../../../packages/shared/src/server/services/blobStorageEndpointValidation.ts)+ for connect-time enforcement through `StorageServiceFactory`.++## Required Defenses++Every outbound-URL surface MUST apply **all three** of:++1. **Save-time validation** in the mutation, tRPC procedure, or public API+ route that persists the URL. Reject the write if validation fails.+2. **Use-time / connection-time validation** when the request is actually+ issued (worker job, lazy validation endpoint, processor). DNS can change+ between save and use; the SDK that ultimately makes the call may resolve a+ different IP than the save-time check did. Plumb+ `addSecureOutboundConnectionValidation` (or the SDK's equivalent hook)+ through the request.+3. **Redirect-time validation** if the request can be redirected. Plain+ `fetch()` defaults to `redirect: 'follow'` and will silently chase a+ redirect into the loopback range. Use `fetchWithSecureRedirects` with the+ matching validator instead.++## Known-Good Call Sites (Copy These)++- LLM base URL save:+ `web/src/features/llm-api-key/server/router.ts` (`update` mutation calls+ `validateLlmConnectionBaseURL` before persisting).+- LLM base URL through public API:+ `web/src/pages/api/public/llm-connections/index.ts`.+- Webhook URL save + use:+ `packages/shared/src/server/webhooks/validation.ts` is wired into both the+ automation form and the worker-side webhook sender.+- Blob storage endpoint:+ `web/src/features/blobstorage-integration/blobstorage-integration-router.ts`+ (`validate` mutation calls `validateBlobStorageEndpoint`); connection-time+ enforcement flows through `StorageServiceFactory.getInstance({+ connectionValidation: blobStorageEndpointConnectionValidationOptions() })`.++## When Adding a New Outbound URL Surface++1. Identify the user-input layers: form mutation, public API route, env import,+ anywhere the URL can be supplied by a tenant.+2. Decide whether an existing wrapper fits. If yes, reuse it. If not, add a+ new wrapper under `packages/shared/src/server/...` that delegates to+ `validateOutboundUrlHost` so blocklist behavior, DNS rebinding handling,+ and credential checks stay centralized.+3. Define the env allowlist trio for self-hosted users who legitimately point+ at private network targets (mirroring+ `LANGFUSE_WEBHOOK_WHITELISTED_HOST/IPS/IP_SEGMENTS`,+ `LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST/IPS/IP_SEGMENTS`, and+ `LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_HOST/IPS/IP_SEGMENTS`). Do+ not share another surface's allowlist; each surface keeps its own.+4. Add the env vars to `.env*.example` and the package `env.mjs/ts`.+5. Call the wrapper from:+ - every tRPC mutation that writes the URL,+ - every public API route that accepts the URL,+ - the worker/processor that issues the request (use connect-time+ validation if the underlying SDK does not expose a host-validation hook).+6. If the request can redirect, use `fetchWithSecureRedirects` with the same+ wrapper as the validator.+7. Add server-side tests that prove blocked targets fail validation:+ `127.0.0.1`, `169.254.169.254`, an RFC1918 literal, an RFC1918 hostname+ (DNS rebinding), `http://` on Cloud, and a URL containing+ `user:pass@host`.++## Anti-Patterns to Flag in Review++- `fetch(<user-supplied-url>)` (or `axios`, `got`, etc.) without an upstream+ call to a `validate*URL` helper, or without+ `addSecureOutboundConnectionValidation` on the request options.+- A tRPC mutation that persists a `host` / `endpoint` / `baseURL` / `webhookUrl`+ field without invoking the matching validator before the write.+- `StorageServiceFactory.getInstance({ endpoint })` (or any SDK client init+ that takes a user-controlled URL) without `connectionValidation` plumbed+ through.+- Custom URL parsing via `new URL(userInput)` instead of+ `parseOutboundUrl(userInput)`. The latter rejects embedded credentials and+ bad encoding, both of which are recurring SSRF/credential-leak vectors.+- Following redirects with `fetch(url)` (default `redirect: 'follow'`) on a+ user-controlled URL. Switch to `fetchWithSecureRedirects`.+- A new integration UI that validates only on the client side. Save-time+ validation must run server-side.+- Save-time validation present, use-time validation missing (or vice versa).+ Both layers are required; the worker may issue the request hours after the+ save and DNS will have moved.++## Env Allowlist Behavior++- Cloud (`NEXT_PUBLIC_LANGFUSE_CLOUD_REGION` set) forces strict mode.+ Allowlist env vars are ignored on Cloud, and HTTPS is enforced for surfaces+ that require it (LLM base URL, blob storage endpoint).+- Self-hosted reads the per-surface env trio:+ - `LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST/IPS/IP_SEGMENTS`+ - `LANGFUSE_WEBHOOK_WHITELISTED_HOST/IPS/IP_SEGMENTS`+ - `LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_HOST/IPS/IP_SEGMENTS`+- Blob storage endpoint validation is **opt-in** today on self-hosted (the+ helper is a no-op until the operator configures one of the allowlist env+ vars). There is a `TODO(next major)` in+ `blobStorageEndpointValidation.ts` to flip the default; until then, do not+ rely on blob storage validation for new surfaces — wire your own wrapper+ that defaults to strict.++## Negative Tests (Required)++A change that adds a new outbound URL surface MUST include server-side tests+that assert each of the following fails validation:++- Loopback literal (`http://127.0.0.1`, `http://[::1]`)+- Cloud metadata literal (`http://169.254.169.254`)+- RFC1918 literal (`http://10.0.0.1`)+- Hostname that resolves to a private IP (DNS rebinding sanity check)+- URL with embedded credentials (`http://user:pass@host`)+- `http://` on Cloud (where HTTPS is required)+- An empty allowlist permits no internal targets on self-hosted++Pattern reference:+`worker/src/__tests__/llm-base-url-validation.test.ts` and the test files+adjacent to the wrappers above.