Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(tracing): sanitize external urls wholistically (#13791)

Nimar3d7315250268
diff --git a/web/src/components/ui/MarkdownViewer.tsx b/web/src/components/ui/MarkdownViewer.tsx
index bbabd8d19a..79def010c4 100644
--- a/web/src/components/ui/MarkdownViewer.tsx
+++ b/web/src/components/ui/MarkdownViewer.tsx
@@ -35,10 +35,10 @@ import { type MediaReturnType } from "@/src/features/media/validation";
import { JSONView } from "@/src/components/ui/CodeJsonViewer";
import { MarkdownJsonViewHeader } from "@/src/components/ui/MarkdownJsonView";
import { copyTextToClipboard } from "@/src/utils/clipboard";
-import DOMPurify from "dompurify";
import { MENTION_USER_PREFIX } from "@/src/features/comments/lib/mentionParser";
import { useCollapsibleSystemPrompt } from "@/src/hooks/useCollapsibleSystemPrompt";
import { Button } from "@/src/components/ui/button";
+import { getSafeImageUrl, getSafeLinkUrl } from "@/src/components/ui/safe-url";
import {
getPromptReferenceMarkdownHref,
getPromptReferenceMarkdownLabel,
@@ -63,33 +63,6 @@ type ReactMarkdownNodeChildren = Exclude<
// html is rendered as plain text by default.
const MemoizedReactMarkdown: FC<Options> = memo(ReactMarkdown);
-const getSafeUrl = (href: string | undefined | null): string | null => {
- if (!href || typeof href !== "string") return null;
-
- // DOMPurify's default sanitization is quite permissive but safe
- // It blocks javascript:, data: with scripts, vbscript:, etc.
- // But allows http:, https:, ftp:, mailto:, tel:, and many others
- try {
- const sanitized = DOMPurify.sanitize(href, {
- // ALLOWED_TAGS: An array of HTML tags that are explicitly permitted in the output.
- // Setting this to an empty array means that no HTML tags are allowed.
- // Any HTML tag found within the 'href' string would be stripped out.
- ALLOWED_TAGS: [],
-
- // ALLOWED_ATTR: An array of HTML attributes that are explicitly permitted on allowed tags.
- // Setting this to an empty array means that no HTML attributes are allowed.
- // Similar to ALLOWED_TAGS, this ensures that if any attributes are somehow
- // embedded within the URL string (e.g., malformed or attempting injection),
- // they will be removed by DOMPurify. We only expect a pure URL string.
- ALLOWED_ATTR: [],
- });
-
- return sanitized || null;
- } catch {
- return null;
- }
-};
-
const isTextElement = (
child: ReactNode,
): child is ReactElement<{ className?: string }> =>
@@ -285,7 +258,7 @@ function MarkdownRenderer({
}
// Handle regular links
- const safeHref = getSafeUrl(href);
+ const safeHref = getSafeLinkUrl(href);
if (safeHref) {
return (
<Link
@@ -371,8 +344,10 @@ function MarkdownRenderer({
);
},
img({ src, alt }) {
- return src && typeof src === "string" ? (
- <ResizableImage src={src} alt={alt} />
+ const safeSrc =
+ typeof src === "string" ? getSafeImageUrl(src) : null;
+ return safeSrc ? (
+ <ResizableImage src={safeSrc} alt={alt} />
) : null;
},
hr() {
@@ -566,40 +541,50 @@ export function MarkdownView({
)
) : (
// content parts (multi-modal)
- (markdown ?? []).map((content, index) =>
- isOpenAITextContentPart(content) ? (
- <MarkdownRenderer
- key={index}
- markdown={content.text}
- theme={theme}
- customCodeHeaderClassName={customCodeHeaderClassName}
- />
- ) : isOpenAIImageContentPart(content) ? (
- OpenAIUrlImageUrl.safeParse(content.image_url.url).success ? (
+ (markdown ?? []).map((content, index) => {
+ if (isOpenAITextContentPart(content)) {
+ return (
+ <MarkdownRenderer
+ key={index}
+ markdown={content.text}
+ theme={theme}
+ customCodeHeaderClassName={customCodeHeaderClassName}
+ />
+ );
+ }
+
+ if (isOpenAIImageContentPart(content)) {
+ const imageUrl = content.image_url.url;
+ const safeImageUrl =
+ typeof imageUrl === "string" &&
+ OpenAIUrlImageUrl.safeParse(imageUrl).success
+ ? getSafeImageUrl(imageUrl)
+ : null;
+
+ return safeImageUrl ? (
<div key={index}>
- <ResizableImage src={content.image_url.url.toString()} />
+ <ResizableImage src={safeImageUrl} />
</div>
- ) : MediaReferenceStringSchema.safeParse(content.image_url.url)
- .success ? (
- <LangfuseMediaView
- mediaReferenceString={content.image_url.url}
- />
+ ) : MediaReferenceStringSchema.safeParse(imageUrl).success ? (
+ <LangfuseMediaView mediaReferenceString={imageUrl} />
) : (
<div className="grid grid-cols-[auto_1fr] items-center gap-2">
<span title="<Base64 data URI>" className="h-4 w-4">
<ImageOff className="h-4 w-4" />
</span>
<span className="truncate text-sm">
- {content.image_url.url.toString()}
+ {imageUrl.toString()}
</span>
</div>
- )
- ) : content.type === "input_audio" ? (
+ );
+ }
+
+ return content.type === "input_audio" ? (
<LangfuseMediaView
mediaReferenceString={content.input_audio.data}
/>
- ) : null,
- )
+ ) : null;
+ })
)}
{audio ? (
<>
diff --git a/web/src/components/ui/resizable-image.tsx b/web/src/components/ui/resizable-image.tsx
index 13c714d581..7f13e16fab 100644
--- a/web/src/components/ui/resizable-image.tsx
+++ b/web/src/components/ui/resizable-image.tsx
@@ -9,6 +9,7 @@ import { Skeleton } from "@/src/components/ui/skeleton";
import { captureException } from "@sentry/nextjs";
import { useSession } from "next-auth/react";
import { buildResizableImageSrc } from "./resizable-image.utils";
+import { getSafeImageUrl } from "@/src/components/ui/safe-url";
/**
* Implemented customLoader as we cannot whitelist user provided image domains
@@ -31,16 +32,29 @@ const ImageErrorDisplay = ({
}: {
src: string;
displayError: string;
-}) => (
- <div className="grid grid-cols-[auto_1fr] items-center gap-2">
- <span title={displayError} className="h-4 w-4">
- <ImageOff className="h-4 w-4" />
- </span>
- <Link href={src} className="truncate text-sm underline" target="_blank">
- {src}
- </Link>
- </div>
-);
+}) => {
+ const safeSrc = getSafeImageUrl(src);
+
+ return (
+ <div className="grid grid-cols-[auto_1fr] items-center gap-2">
+ <span title={displayError} className="h-4 w-4">
+ <ImageOff className="h-4 w-4" />
+ </span>
+ {safeSrc ? (
+ <Link
+ href={safeSrc}
+ className="truncate text-sm underline"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {src}
+ </Link>
+ ) : (
+ <span className="truncate text-sm">{src}</span>
+ )}
+ </div>
+ );
+};
export const ResizableImage = ({
src,
@@ -53,13 +67,15 @@ export const ResizableImage = ({
isDefaultVisible?: boolean;
shouldValidateImageSource?: boolean;
}) => {
+ const safeSrc = getSafeImageUrl(src);
const [isZoomedIn, setIsZoomedIn] = useState(true);
const [hasFetchError, setHasFetchError] = useState(false);
const [isImageVisible, setIsImageVisible] = useState(isDefaultVisible);
const session = useSession();
- const isValidImage = api.utilities.validateImgUrl.useQuery(src, {
+ const isValidImage = api.utilities.validateImgUrl.useQuery(safeSrc ?? "", {
enabled:
session.status === "authenticated" &&
+ Boolean(safeSrc) &&
isImageVisible &&
shouldValidateImageSource,
initialData: shouldValidateImageSource ? undefined : { isValid: true },
@@ -95,16 +111,16 @@ export const ResizableImage = ({
isZoomedIn ? "h-1/2 w-1/2" : "h-full w-full",
)}
>
- {isImageVisible && isValidImage.data?.isValid ? (
+ {isImageVisible && safeSrc && isValidImage.data?.isValid ? (
<>
<Image
loader={customLoader}
- src={src}
+ src={safeSrc}
alt={alt ?? `Markdown Image-${Math.random()}`}
loading="lazy"
width={0}
height={0}
- title={src}
+ title={safeSrc ?? src}
className="h-full w-full rounded border object-contain"
onError={(error) => {
setHasFetchError(true);
@@ -133,18 +149,26 @@ export const ResizableImage = ({
size="sm"
variant="secondary"
onClick={() => setIsImageVisible(!isImageVisible)}
+ disabled={!safeSrc}
>
Load Image
</Button>
<div className="flex min-w-0 flex-1 items-center overflow-hidden">
- <Link
- href={src}
- title={src}
- className="truncate underline"
- target="_blank"
- >
- {src}
- </Link>
+ {safeSrc ? (
+ <Link
+ href={safeSrc}
+ title={src}
+ className="truncate underline"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {src}
+ </Link>
+ ) : (
+ <span title={src} className="truncate">
+ {src}
+ </span>
+ )}
</div>
</div>
)}
diff --git a/web/src/components/ui/safe-url.clienttest.ts b/web/src/components/ui/safe-url.clienttest.ts
new file mode 100644
index 0000000000..ebeb315fc0
--- /dev/null
+++ b/web/src/components/ui/safe-url.clienttest.ts
@@ -0,0 +1,67 @@
+import { getSafeImageUrl, getSafeLinkUrl } from "@/src/components/ui/safe-url";
+
+describe("safe URL helpers", () => {
+ it.each([
+ "javascript:alert(1)",
+ "JaVaScRiPt:alert(1)",
+ "jav\nascript:alert(1)",
+ "vbscript:msgbox(1)",
+ "data:text/html,<svg/onload=alert(1)>",
+ "data:image/png;base64,iVBORw0KGgo=",
+ "ftp://example.com/file.txt",
+ "//attacker.example.com/path",
+ "/\\attacker.example.com/path",
+ "/\\\\attacker.example.com/path",
+ "\\attacker.example.com/path",
+ "relative\\path",
+ ])("blocks unsafe link URL %s", (url) => {
+ expect(getSafeLinkUrl(url)).toBeNull();
+ });
+
+ it.each([
+ ["https://example.com/path?q=1", "https://example.com/path?q=1"],
+ ["HTTPS://EXAMPLE.COM/path", "https://example.com/path"],
+ ["https://example.com/foo\tbar", "https://example.com/foobar"],
+ ["https://example.com/foo bar", "https://example.com/foo%20bar"],
+ ["http://example.com/image.png", "http://example.com/image.png"],
+ ["irc://irc.example.com/langfuse", "irc://irc.example.com/langfuse"],
+ ["ircs://irc.example.com/langfuse", "ircs://irc.example.com/langfuse"],
+ ["mailto:[email protected]", "mailto:[email protected]"],
+ ["tel:+49123456789", "tel:+49123456789"],
+ ["/project/abc/traces/def", "/project/abc/traces/def"],
+ ["relative/path", "relative/path"],
+ ["./relative/path", "./relative/path"],
+ ["../relative/path", "../relative/path"],
+ ["?tab=foo", "?tab=foo"],
+ ["#section", "#section"],
+ ])("allows safe link URL %s", (url, expected) => {
+ expect(getSafeLinkUrl(url)).toBe(expected);
+ });
+
+ it.each([
+ "mailto:[email protected]",
+ "tel:+49123456789",
+ "#section",
+ "data:image/png;base64,iVBORw0KGgo=",
+ "//attacker.example.com/path",
+ "/\\attacker.example.com/path",
+ "/\\\\attacker.example.com/path",
+ "\\attacker.example.com/path",
+ "relative\\path",
+ ])("blocks non-image URL %s for image sources", (url) => {
+ expect(getSafeImageUrl(url)).toBeNull();
+ });
+
+ it.each([
+ ["https://example.com/image.png", "https://example.com/image.png"],
+ ["HTTPS://EXAMPLE.COM/image.png", "https://example.com/image.png"],
+ ["http://example.com/image.png", "http://example.com/image.png"],
+ ["/api/media/image.png", "/api/media/image.png"],
+ ["relative/image.png", "relative/image.png"],
+ ["./relative/image.png", "./relative/image.png"],
+ ["../relative/image.png", "../relative/image.png"],
+ ])("allows safe image URL %s", (url, expected) => {
+ expect(getSafeImageUrl(url)).toBe(expected);
+ });
+});
diff --git a/web/src/components/ui/safe-url.ts b/web/src/components/ui/safe-url.ts
new file mode 100644
index 0000000000..cee2a4a1b8
--- /dev/null
+++ b/web/src/components/ui/safe-url.ts
@@ -0,0 +1,94 @@
+const SAFE_LINK_PROTOCOLS = new Set([
+ "http:",
+ "https:",
+ "irc:",
+ "ircs:",
+ "mailto:",
+ "tel:",
+ "xmpp:",
+]);
+const SAFE_IMAGE_PROTOCOLS = new Set(["http:", "https:"]);
+const SAME_ORIGIN_URL_BASE = "https://langfuse.local";
+
+// Markdown image URLs intentionally stay limited to fetchable http(s) URLs and
+// same-origin paths. Do not add data: here; inline base64 media needs separate
+// handling from clickable/fetchable markdown URLs.
+
+// The old DOMPurify helper used ALLOWED_TAGS: [] and ALLOWED_ATTR: [], which is
+// correct for stripping HTML tags/attributes from a string. It does not validate
+// URL protocols when the input is already plain text: "javascript:alert(1)" has
+// no markup to remove, so URL safety has to be protocol allowlist based here.
+const getSafeUrl = (
+ value: string | undefined | null,
+ {
+ allowedProtocols,
+ allowHash = false,
+ allowSearch = false,
+ allowRelativePath = true,
+ }: {
+ allowedProtocols: Set<string>;
+ allowHash?: boolean;
+ allowSearch?: boolean;
+ allowRelativePath?: boolean;
+ },
+): string | null => {
+ if (!value || typeof value !== "string") return null;
+
+ const trimmed = value.trim();
+ if (!trimmed) return null;
+
+ try {
+ const parsed = new URL(trimmed);
+ return allowedProtocols.has(parsed.protocol) ? parsed.href : null;
+ } catch {
+ // Markdown links may point to anchors inside the rendered content.
+ if (allowHash && trimmed.startsWith("#")) {
+ return trimmed;
+ }
+
+ if (allowSearch && trimmed.startsWith("?")) {
+ return isSafeSameOriginReference(trimmed) ? trimmed : null;
+ }
+
+ if (allowRelativePath && isRelativePathReference(trimmed)) {
+ return isSafeSameOriginReference(trimmed) ? trimmed : null;
+ }
+
+ return null;
+ }
+};
+
+const isRelativePathReference = (value: string): boolean =>
+ value.startsWith("/") ||
+ value.startsWith("./") ||
+ value.startsWith("../") ||
+ /^[^/?#]/.test(value);
+
+const isSafeSameOriginReference = (value: string): boolean => {
+ // Block protocol-relative and backslash-normalized URLs. Browsers can resolve
+ // values like "/\\attacker.example/x" to another host for http(s) documents.
+ if (value.startsWith("//") || value.includes("\\")) return false;
+
+ try {
+ const parsed = new URL(value, SAME_ORIGIN_URL_BASE);
+ return parsed.origin === SAME_ORIGIN_URL_BASE;
+ } catch {
+ return false;
+ }
+};
+
+export const getSafeLinkUrl = (
+ value: string | undefined | null,
+): string | null =>
+ getSafeUrl(value, {
+ allowedProtocols: SAFE_LINK_PROTOCOLS,
+ allowHash: true,
+ allowSearch: true,
+ });
+
+export const getSafeImageUrl = (
+ value: string | undefined | null,
+): string | null =>
+ getSafeUrl(value, {
+ allowedProtocols: SAFE_IMAGE_PROTOCOLS,
+ });