Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
sanitize URL for saferequest logging
Thiago Araujo da Silva561d398fb34c
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 0f9d8017d2..7091c25add 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -337,6 +337,10 @@ logger.info(`getPlan: Process done for [orgId=${orgId}] [projectId=${projectId}]logger.error({ sessionId, err }, "Failed to get connection details");```+**Never log an outbound URL verbatim — a URL is often itself a credential.** Incoming-webhook providers put the bearer secret in the path (`https://hooks.slack.com/services/T…/B…/<secret>`, Discord, Teams, Telegram) and many APIs accept a token as a query param, so a raw URL in a log line ships a working credential to the log sink. Pass it through `sanitizeUrlForLog` from `@app/lib/logger` first (`src/lib/logger/sanitize-url.ts`): it strips userinfo and the fragment, redacts every query value, drops the path for known credential-in-URL hosts, and redacts token-shaped path segments on hosts we can't enumerate (users can point a webhook channel at any host). The global axios response interceptor (`src/lib/config/request.ts`) and `safeRequest`'s dispatch log already do this — when adding a new provider whose path is a secret, add its host to `CREDENTIAL_PATH_HOSTS`.++Note that `logger.ts` also has a `redactedKeys` list applied to structured-object fields up to depth three. It only matches by key name, so it does **not** help with a secret embedded in a `url` field.+### Enterprise (EE) FeaturesEnterprise code lives in `src/ee/`:diff --git a/backend/src/lib/config/request.ts b/backend/src/lib/config/request.tsindex 83c7e1ff90..32dbe898ce 100644--- a/backend/src/lib/config/request.ts+++ b/backend/src/lib/config/request.ts@@ -2,6 +2,7 @@ import axios, { AxiosError, AxiosInstance, AxiosResponse, CreateAxiosDefaults }import axiosRetry, { IAxiosRetryConfig } from "axios-retry";import { CustomLogger, logger } from "../logger/logger";+import { sanitizeUrlForLog } from "../logger/sanitize-url";export function axiosResponseInterceptor(response: AxiosResponse, customLogger: CustomLogger) {try {@@ -14,8 +15,10 @@ export function axiosResponseInterceptor(response: AxiosResponse, customLogger:megabyteSize = `Large payload: ${(responseSize / 1024 / 1024).toFixed(2)} MB`;}+ const url = sanitizeUrlForLog(response.config.url, response.config.baseURL);+customLogger.info(- { url: `${response.config.method || "NO_METHOD"} ${response.config.url}`, responseSize },+ { url: `${response.config.method || "NO_METHOD"} ${url}`, responseSize },`Intercepted axios response ${megabyteSize}`);} catch (error) {diff --git a/backend/src/lib/logger/sanitize-url.test.ts b/backend/src/lib/logger/sanitize-url.test.tsnew file mode 100644index 0000000000..4cc792b5c2--- /dev/null+++ b/backend/src/lib/logger/sanitize-url.test.ts@@ -0,0 +1,61 @@+import { sanitizeUrlForLog } from "./sanitize-url";++describe("sanitizeUrlForLog", () => {+ test("drops the path of an incoming-webhook provider", () => {+ expect(sanitizeUrlForLog("https://hooks.slack.com/services/T0000000/B0000000/aBcDeFgHiJkLmNoPqRsTuVwX")).toBe(+ "https://hooks.slack.com/[REDACTED]"+ );+ });++ test.each([+ "https://discord.com/api/webhooks/1234567890/tokentokentokentoken",+ "https://outlook.webhook.office.com/webhookb2/abc-def@ghi/IncomingWebhook/jkl/mno",+ "https://api.telegram.org/bot123456:AAHrandomsecret/sendMessage"+ ])("drops the path of %s", (url) => {+ const sanitized = sanitizeUrlForLog(url);+ expect(sanitized).toMatch(/\/\[REDACTED\]$/);+ });++ test("keeps query param names but redacts their values", () => {+ expect(sanitizeUrlForLog("https://api.example.com/v1/items?page=2&token=supersecret")).toBe(+ "https://api.example.com/v1/items?page=[REDACTED]&token=[REDACTED]"+ );+ });++ test("keeps readable paths on unknown hosts", () => {+ expect(sanitizeUrlForLog("https://api.example.com/v1/secrets/my-app")).toBe(+ "https://api.example.com/v1/secrets/my-app"+ );+ });++ test("redacts token-shaped path segments on unknown hosts", () => {+ expect(sanitizeUrlForLog("https://webhooks.acme.internal/hook/9f8a7b6c5d4e3f2a1b0c9d8e7f6a5b4c")).toBe(+ "https://webhooks.acme.internal/hook/[REDACTED]"+ );+ });++ test("strips embedded credentials and the fragment", () => {+ expect(sanitizeUrlForLog("https://user:[email protected]/path#frag")).toBe("https://api.example.com/path");+ });++ test("resolves a relative url against the axios baseURL", () => {+ expect(sanitizeUrlForLog("/v1/items", "https://api.example.com/base")).toBe(+ "https://api.example.com/base/v1/items"+ );+ });++ test("keeps an absolute url even when a baseURL is set", () => {+ expect(sanitizeUrlForLog("https://other.example.com/x", "https://api.example.com")).toBe(+ "https://other.example.com/x"+ );+ });++ test("returns a placeholder instead of echoing an unparseable url", () => {+ expect(sanitizeUrlForLog("https://")).toBe("[REDACTED]");+ });++ test("handles a missing url", () => {+ expect(sanitizeUrlForLog(undefined)).toBe("NO_URL");+ expect(sanitizeUrlForLog("")).toBe("NO_URL");+ });+});diff --git a/backend/src/lib/logger/sanitize-url.ts b/backend/src/lib/logger/sanitize-url.tsnew file mode 100644index 0000000000..74276eae93--- /dev/null+++ b/backend/src/lib/logger/sanitize-url.ts@@ -0,0 +1,79 @@+import RE2 from "re2";++const PLACEHOLDER = "[REDACTED]";+const NO_URL = "NO_URL";+const RELATIVE_BASE = "http://relative.invalid";++const CREDENTIAL_PATH_HOSTS = new Set([+ "hooks.slack.com",+ "discord.com",+ "discordapp.com",+ "chat.googleapis.com",+ "hooks.zapier.com",+ "api.telegram.org",+ "maker.ifttt.com"+]);++const CREDENTIAL_PATH_HOST_SUFFIXES = [+ ".webhook.office.com",+ ".logic.azure.com",+ ".slack.com"+];++const hasScheme = new RE2(/^[a-z][a-z\d+\-.]*:\/\//i);+const trailingSlashes = new RE2(/\/+$/);+const leadingSlashes = new RE2(/^\/+/);++const MIN_TOKEN_LENGTH = 20;+const tokenCharset = new RE2(/^[A-Za-z0-9._~=+-]+$/);+const hasDigit = new RE2(/\d/);+const hasLetter = new RE2(/[A-Za-z]/);++const isCredentialPathHost = (hostname: string): boolean =>+ CREDENTIAL_PATH_HOSTS.has(hostname) || CREDENTIAL_PATH_HOST_SUFFIXES.some((suffix) => hostname.endsWith(suffix));++const isTokenLikeSegment = (segment: string): boolean =>+ segment.length >= MIN_TOKEN_LENGTH && tokenCharset.test(segment) && hasDigit.test(segment) && hasLetter.test(segment);++const redactPath = (pathname: string): string =>+ pathname+ .split("/")+ .map((segment) => (isTokenLikeSegment(segment) ? PLACEHOLDER : segment))+ .join("/");++const redactQuery = (searchParams: URLSearchParams): string => {+ const keys = [...searchParams.keys()];+ if (!keys.length) return "";+ return `?${keys.map((key) => `${key}=${PLACEHOLDER}`).join("&")}`;+};++const resolveUrl = (rawUrl?: string, baseUrl?: string): string => {+ if (!rawUrl) return baseUrl ?? "";+ if (!baseUrl || hasScheme.test(rawUrl)) return rawUrl;+ return `${baseUrl.replace(trailingSlashes, "")}/${rawUrl.replace(leadingSlashes, "")}`;+};++/**+ * Renders a URL safe to log: strips userinfo and fragment, redacts every query+ * value, and drops path segments that are credentials. Never returns the raw+ * input, so an unparseable URL is redacted rather than echoed.+ */+export const sanitizeUrlForLog = (rawUrl?: string, baseUrl?: string): string => {+ const target = resolveUrl(rawUrl, baseUrl);+ if (!target) return NO_URL;++ const isAbsolute = hasScheme.test(target);++ let url: URL;+ try {+ url = new URL(target, isAbsolute ? undefined : RELATIVE_BASE);+ } catch {+ return PLACEHOLDER;+ }++ const hostname = url.hostname.toLowerCase();+ const path = isAbsolute && isCredentialPathHost(hostname) ? `/${PLACEHOLDER}` : redactPath(url.pathname);+ const origin = isAbsolute ? `${url.protocol}//${url.host}` : "";++ return `${origin}${path}${redactQuery(url.searchParams)}`;+};diff --git a/backend/src/lib/validator/safe-request.ts b/backend/src/lib/validator/safe-request.tsindex e2738ccf11..6bd79e0914 100644--- a/backend/src/lib/validator/safe-request.ts+++ b/backend/src/lib/validator/safe-request.ts@@ -11,6 +11,7 @@ import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamicimport { getConfig } from "@app/lib/config/env";import { request } from "@app/lib/config/request";import { logger } from "@app/lib/logger";+import { sanitizeUrlForLog } from "@app/lib/logger/sanitize-url";import { BadRequestError } from "../errors";import { isPrivateIp } from "../ip/ipRange";@@ -331,7 +332,9 @@ const resolveBaseUrl = (url: string, baseURL?: string): string => {const logDispatch = (method: string, effectiveUrl: string, validated: TValidatedHost | undefined) => {const pinned = validated ? formatEntries(validated.entries) : "none";- logger.debug(`safeRequest: dispatching [method=${method}] [url=${effectiveUrl}] [pinned=${pinned}]`);+ logger.debug(+ `safeRequest: dispatching [method=${method}] [url=${sanitizeUrlForLog(effectiveUrl)}] [pinned=${pinned}]`+ );};const dispatch = async <T>(