Skip to content

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

chore: enhance security measures in image verification (#2701)

marliessophiefffa14d0e967
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 13a9a0650d..24a9b092f8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -40,7 +40,7 @@ importers:
next-auth:
specifier: ^4.24.7
zod:
specifier: ^3.23.8
version: 3.23.8
@@ -447,6 +447,9 @@ importers:
graphql:
specifier: ^16.9.0
version: 16.9.0
+ ip-address:
+ specifier: ^9.0.5
+ version: 9.0.5
js-tiktoken:
specifier: ^1.0.12
version: 1.0.12
@@ -467,7 +470,7 @@ importers:
next-auth:
specifier: ^4.24.7
next-query-params:
specifier: ^5.0.0
@@ -1761,6 +1764,7 @@ packages:
'@humanwhocodes/[email protected]':
resolution: {integrity: sha512-3T8LkOmg45BV5FICb15QQMsyUSWrQ8AygVfC7ZG32zOalnqrilm018ZVCw0eapXux8FtA33q8PSRSstjee3jSg==}
engines: {node: '>=10.10.0'}
+ deprecated: Use @eslint/config-array instead
'@humanwhocodes/[email protected]':
resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==}
@@ -1768,6 +1772,7 @@ packages:
'@humanwhocodes/[email protected]':
resolution: {integrity: sha512-6EwiSjwWYP7pTckG6I5eyFANjPhmPjUX9JRLUSfNPC7FX7zK9gyZAfUEaECL6ALTpGX5AjnBq3C9XmVWPitNpw==}
+ deprecated: Use @eslint/object-schema instead
resolution: {integrity: sha512-trnsAYxU3xnS1gPHPyU961coFyLkh4gAD/0zQ5mymY4yOZ+CYvsPqUbOFSw0aDM4y0tV7tiFxL/1XfXPNC6IPg==}
@@ -8721,6 +8726,7 @@ packages:
resolution: {integrity: sha512-+8R2/nLaWyI5Jp2Ly7L52qcgDFU3xryyoNG52DPJ8dlGnagphxIc0mLNGurgyKeeTGycsOsuOIP4dtofv3ZoBA==}
+ deprecated: This version of posthog-js is deprecated, please update posthog-js, and do not use this version! Check out our JS docs at https://posthog.com/docs/libraries/js
resolution: {integrity: sha512-JB+ei0LkwE+rKHyW5z79Nd1jUaGxU6TvkfjFqY9vQaHxU5aU8dRl0UUaEmZdZbHwjp3WmXCBQQRNyimwbNQfCw==}
@@ -8942,7 +8948,7 @@ packages:
resolution: {integrity: sha512-39olGaX2djYUdhaQQHDZ0T0GwEp+5f9UB9HmEP0qHfdQHIq0xGQZuAZ5TLnJIc/88SrPLpEflPC+xUqOTv3c5g==}
- deprecated: < 21.5.0 is no longer supported
+ deprecated: < 22.6.4 is no longer supported
resolution: {integrity: sha512-LA0Y9kxMYv47GIPJy6MI84fqTd2HmYZI83W/kM/SkKfDlajnZYfmXFTxkbY+xSBPkLJxltMa9hIkmdc29eguMA==}
@@ -9273,6 +9279,7 @@ packages:
resolution: {integrity: sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==}
+ deprecated: Rimraf versions prior to v4 are no longer supported
hasBin: true
@@ -15283,7 +15290,7 @@ snapshots:
'@typescript-eslint/eslint-plugin': 7.3.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])
'@typescript-eslint/parser': 7.12.0([email protected])([email protected])
eslint-config-prettier: 9.1.0([email protected])
+ eslint-import-resolver-alias: 1.1.2([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected]))
eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])
eslint-plugin-eslint-comments: 3.2.0([email protected])
@@ -16992,7 +16999,7 @@ snapshots:
eslint: 8.57.0
eslint-plugin-turbo: 1.13.4([email protected])
dependencies:
@@ -19801,6 +19808,23 @@ snapshots:
optionalDependencies:
nodemailer: 6.9.13
+ dependencies:
+ '@babel/runtime': 7.24.5
+ '@panva/hkdf': 1.1.1
+ cookie: 0.5.0
+ jose: 4.15.5
+ oauth: 0.9.15
+ openid-client: 5.6.5
+ preact: 10.19.7
+ preact-render-to-string: 5.2.6([email protected])
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
+ uuid: 8.3.2
+ optionalDependencies:
+ nodemailer: 6.9.13
+
dependencies:
'@babel/runtime': 7.24.5
diff --git a/web/package.json b/web/package.json
index a61caf3236..65ca479632 100644
--- a/web/package.json
+++ b/web/package.json
@@ -88,6 +88,7 @@
"dompurify": "^3.1.5",
"exponential-backoff": "^3.1.1",
"graphql": "^16.9.0",
+ "ip-address": "^9.0.5",
"js-tiktoken": "^1.0.12",
"kysely": "^0.27.3",
"langchain": "^0.2.6",
diff --git a/web/src/components/ui/MarkdownViewer.tsx b/web/src/components/ui/MarkdownViewer.tsx
index 768ae5df68..33545312e6 100644
--- a/web/src/components/ui/MarkdownViewer.tsx
+++ b/web/src/components/ui/MarkdownViewer.tsx
@@ -17,13 +17,14 @@ import remarkMath from "remark-math";
import { CodeBlock } from "@/src/components/ui/Codeblock";
import { useTheme } from "next-themes";
import { Button } from "@/src/components/ui/button";
-import { Check, Copy, Maximize2, Minimize2 } from "lucide-react";
+import { Check, Copy, ImageOff, Maximize2, Minimize2 } from "lucide-react";
import { api } from "@/src/utils/api";
import { isPresent } from "@/src/utils/typeChecks";
import { BsMarkdown } from "react-icons/bs";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { Skeleton } from "@/src/components/ui/skeleton";
import { useMarkdownContext } from "@/src/features/theming/useMarkdownContext";
+import { captureException } from "@sentry/nextjs";
// ReactMarkdown does not render raw HTML by default for security reasons, to prevent XSS (Cross-Site Scripting) attacks.
// html is rendered as plain text by default.
@@ -38,15 +39,35 @@ const isChecklist = (children: ReactNode) =>
Array.isArray(children) &&
children.some((child: any) => child?.props?.className === "task-list-item");
-// Implemented customLoader as we cannot whitelist user provided image domains.
-// Security risks are taken care of by a validation in api.public.validateImgUrl.
-// Do not use this customLoader in production if you are not using the above mentioned security measures.
+/**
+ * Implemented customLoader as we cannot whitelist user provided image domains
+ * Security risks are taken care of by a validation in api.utilities.validateImgUrl
+ * Fetching image will fail if SSL/TLS certificate is invalid or expired, will be handled by onError
+ * Do not use this customLoader in production if you are not using the above mentioned security measures */
const customLoader = ({ src }: { src: string }) => {
return src;
};
+const ImageErrorDisplay = ({
+ src,
+ errorDescription,
+}: {
+ src: string;
+ errorDescription: string;
+}) => (
+ <div className="flex flex-row items-center gap-2">
+ <span title={errorDescription} className="h-4 w-4">
+ <ImageOff className="h-4 w-4" />
+ </span>
+ <Link href={src} className="underline" target="_blank">
+ {src}
+ </Link>
+ </div>
+);
+
const MarkdownImage: Components["img"] = ({ src, alt }) => {
const [isZoomedIn, setIsZoomedIn] = useState(true);
+ const [hasFetchError, setHasFetchError] = useState(false);
if (!isPresent(src)) return null;
@@ -59,47 +80,54 @@ const MarkdownImage: Components["img"] = ({ src, alt }) => {
);
}
+ const isHttp = new URL(src).protocol === "http:";
+ const errorDescription = `Cannot load image. ${isHttp ? "Http images are not rendered in Langfuse for security reasons." : ""} Click to view image in new tab`;
+
if (isValidImage.data?.isValid) {
return (
<div>
- <div
- className={cn(
- "group relative w-full overflow-hidden rounded border",
- isZoomedIn ? "h-1/2 w-1/2" : "h-full w-full",
- )}
- >
- <Image
- loader={customLoader}
- src={src}
- alt={alt ?? `Markdown Image-${Math.random()}`}
- loading="lazy"
- width={0}
- height={0}
- className="h-full w-full object-contain"
- />
- <Button
- type="button"
- className="absolute right-0 top-0 mr-1 mt-1 h-8 w-8 opacity-0 group-hover:!bg-accent/30 group-hover:opacity-100"
- variant="ghost"
- size="icon"
- onClick={() => setIsZoomedIn(!isZoomedIn)}
- >
- {isZoomedIn ? (
- <Maximize2 className="h-4 w-4"></Maximize2>
- ) : (
- <Minimize2 className="h-4 w-4"></Minimize2>
+ {hasFetchError ? (
+ <ImageErrorDisplay src={src} errorDescription={errorDescription} />
+ ) : (
+ <div
+ className={cn(
+ "group relative w-full overflow-hidden rounded border",
+ isZoomedIn ? "h-1/2 w-1/2" : "h-full w-full",
)}
- </Button>
- </div>
+ >
+ <Image
+ loader={customLoader}
+ src={src}
+ alt={alt ?? `Markdown Image-${Math.random()}`}
+ loading="lazy"
+ width={0}
+ height={0}
+ className="h-full w-full object-contain"
+ onError={(error) => {
+ setHasFetchError(true);
+ captureException(error);
+ }}
+ />
+ <Button
+ type="button"
+ className="absolute right-0 top-0 mr-1 mt-1 h-8 w-8 opacity-0 group-hover:!bg-accent/30 group-hover:opacity-100"
+ variant="ghost"
+ size="icon"
+ onClick={() => setIsZoomedIn(!isZoomedIn)}
+ >
+ {isZoomedIn ? (
+ <Maximize2 className="h-4 w-4"></Maximize2>
+ ) : (
+ <Minimize2 className="h-4 w-4"></Minimize2>
+ )}
+ </Button>
+ </div>
+ )}
</div>
);
}
- return (
- <Link href={src} className="underline" target="_blank">
- {src}
- </Link>
- );
+ return <ImageErrorDisplay src={src} errorDescription={errorDescription} />;
};
const isTextElement = (child: ReactNode): child is ReactElement =>
diff --git a/web/src/server/api/routers/utilities.ts b/web/src/server/api/routers/utilities.ts
index 0f4e2fa5a1..43943fab65 100644
--- a/web/src/server/api/routers/utilities.ts
+++ b/web/src/server/api/routers/utilities.ts
@@ -1,19 +1,80 @@
import { createTRPCRouter, protectedProcedure } from "@/src/server/api/trpc";
import { z } from "zod";
+import { promises as dns } from "dns";
+import { Address4, Address6 } from "ip-address";
-const isValidURL = (urlString: string): boolean => {
+const IP_4_LOOPBACK_SUBNET = "127.0.0.0/8";
+const IP_4_LINK_LOCAL_SUBNET = "169.254.0.0/16";
+const IP_4_PRIVATE_A_SUBNET = "10.0.0.0/8";
+const IP_4_PRIVATE_B_SUBNET = "172.16.0.0/12";
+const IP_4_PRIVATE_C_SUBNET = "192.168.0.0/16";
+
+/**
+ * Check if the hostname is a private IP address
+ * This function is used to protect against Server Side Request Forgery (SSRF) attacks.
+ * SSRF attacks can cause the server to make requests to internal resources that should not be accessible.
+ * By checking if a hostname resolves to a private IP address, we can prevent such attacks.
+ *
+ * @param hostname - The hostname to check
+ * @returns True if the hostname is a private IP address, false otherwise
+ */
+const isPrivateIp = (hostname: string): boolean => {
+ try {
+ if (Address6.isValid(hostname)) {
+ const address = new Address6(hostname);
+ return address.isLinkLocal() || address.isLoopback();
+ } else if (Address4.isValid(hostname)) {
+ const address = new Address4(hostname);
+ return [
+ IP_4_LOOPBACK_SUBNET,
+ IP_4_LINK_LOCAL_SUBNET,
+ IP_4_PRIVATE_A_SUBNET,
+ IP_4_PRIVATE_B_SUBNET,
+ IP_4_PRIVATE_C_SUBNET,
+ ].some((subnet) => address.isInSubnet(new Address4(subnet)));
+ } else {
+ console.error("Invalid IP address:", hostname);
+ return false;
+ }
+ } catch (error) {
+ console.error("IP parsing error:", error);
+ return false;
+ }
+};
+
+const resolveHostname = async (hostname: string): Promise<string[]> => {
+ try {
+ const addresses4 = await dns.resolve4(hostname);
+ const addresses6 = await dns.resolve6(hostname);
+ return [...addresses4, ...addresses6];
+ } catch (error) {
+ console.error("DNS resolution error:", error);
+ return [];
+ }
+};
+
+const isValidAndSecureUrl = async (urlString: string): Promise<boolean> => {
try {
const url = new URL(urlString);
- return url.protocol === "https:";
+ if (url.protocol !== "https:") {
+ return false;
+ }
+ const hostname = new URL(url).hostname;
+ const ipAddresses = await resolveHostname(hostname);
+
+ return ipAddresses.every((ip) => !isPrivateIp(ip));
} catch (error) {
- console.log(error);
+ console.error("Invalid URL:", error);
return false;
}
};
const isValidImageUrl = async (url: string): Promise<boolean> => {
try {
- const response = await fetch(url, { method: "HEAD" });
+ const response = await fetch(url, {
+ method: "HEAD",
+ signal: AbortSignal.timeout(5000),
+ });
if (!response.ok) {
return false;
}
@@ -22,26 +83,27 @@ const isValidImageUrl = async (url: string): Promise<boolean> => {
const contentLength = response.headers.get("content-length");
// ensure image is not larger than 1MB in size
- if (contentLength && parseInt(contentLength, 10) > 1 * 1024 * 1024) {
+ if (!contentLength || parseInt(contentLength, 10) > 1 * 1024 * 1024) {
return false;
}
return !!contentType && contentType.startsWith("image/");
} catch (error) {
- console.log(error);
+ console.error("Invalid image error:", error);
return false;
}
};
export const utilsRouter = createTRPCRouter({
validateImgUrl: protectedProcedure
- .input(z.string().url())
+ .input(z.string().url().max(2048))
.query(async ({ input: url }) => {
- if (!isValidURL(url)) {
+ const isValidUrl = await isValidAndSecureUrl(url);
+ if (!isValidUrl) {
return { isValid: false };
}
- const isValidImage = await isValidImageUrl(url);
- return { isValid: isValidImage };
+ const isValidImg = await isValidImageUrl(url);
+ return { isValid: isValidImg };
}),
});