Skip to content

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

fix(security): require secrets again when webhook or PostHog destination changes (#19261)

Niklas Semmler6d693584d056
diff --git a/web/src/__tests__/server/automations-trpc.servertest.ts b/web/src/__tests__/server/automations-trpc.servertest.ts
index ba70e612fc..98e1a1c78a 100644
--- a/web/src/__tests__/server/automations-trpc.servertest.ts
+++ b/web/src/__tests__/server/automations-trpc.servertest.ts
@@ -1805,111 +1805,175 @@ describe("automations trpc", () => {
});
});
- it("should allow URL update without requiring secret header values", async () => {
- const { project, caller } = await prepare();
-
- // Create initial automation with secret headers
- const trigger = await prisma.trigger.create({
- data: {
- id: v4(),
- projectId: project.id,
- eventSource: "prompt",
- eventActions: ["created"],
- filter: [],
- status: JobConfigState.ACTIVE,
- },
- });
+ describe("webhook URL changes", () => {
+ const createWebhookAutomation = async (projectId: string) => {
+ const trigger = await prisma.trigger.create({
+ data: {
+ id: v4(),
+ projectId,
+ eventSource: "prompt",
+ eventActions: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ },
+ });
- const { secretKey, displaySecretKey } = generateWebhookSecret();
- const action = await prisma.action.create({
- data: {
- id: v4(),
- projectId: project.id,
- type: "WEBHOOK",
- config: {
+ const { secretKey, displaySecretKey } = generateWebhookSecret();
+ const action = await prisma.action.create({
+ data: {
+ id: v4(),
+ projectId,
type: "WEBHOOK",
- url: "https://example.com/webhook",
- requestHeaders: {
- "content-type": { secret: false, value: "application/json" },
- "x-api-key": { secret: true, value: encrypt("secret-key-123") },
- authorization: {
- secret: true,
- value: encrypt("Bearer token-456"),
+ config: {
+ type: "WEBHOOK",
+ url: "https://example.com/webhook",
+ requestHeaders: {
+ "content-type": { secret: false, value: "application/json" },
+ "x-api-key": { secret: true, value: encrypt("secret-key-123") },
},
+ displayHeaders: {
+ "content-type": { secret: false, value: "application/json" },
+ "x-api-key": { secret: true, value: "secr...-123" },
+ },
+ apiVersion: { prompt: "v1" },
+ secretKey: encrypt(secretKey),
+ displaySecretKey,
},
- displayHeaders: {
- "content-type": { secret: false, value: "application/json" },
- "x-api-key": { secret: true, value: "secr...-123" },
- authorization: { secret: true, value: "Bear...-456" },
- },
- apiVersion: { prompt: "v1" },
- secretKey: encrypt(secretKey),
- displaySecretKey,
},
- },
- });
+ });
- const automation = await prisma.automation.create({
- data: {
- projectId: project.id,
- triggerId: trigger.id,
- actionId: action.id,
- name: "URL Update Test",
- },
- });
+ const automation = await prisma.automation.create({
+ data: {
+ projectId,
+ triggerId: trigger.id,
+ actionId: action.id,
+ name: "URL Update Test",
+ },
+ });
- // Update only the URL without providing secret header values
- const response = await caller.automations.updateAutomation({
- projectId: project.id,
- automationId: automation.id,
- name: "Updated URL Automation",
- eventSource: "prompt",
- eventAction: ["created"],
- filter: [],
- status: JobConfigState.ACTIVE,
- actionType: "WEBHOOK",
+ return { action, automation };
+ };
+
+ const updateWebhook = (
+ caller: Awaited<ReturnType<typeof prepare>>["caller"],
+ projectId: string,
+ automationId: string,
actionConfig: {
- type: "WEBHOOK",
- url: "https://example.com/new-webhook-url",
- requestHeaders: {}, // No headers provided
- apiVersion: { prompt: "v1" },
+ url: string;
+ requestHeaders: Record<string, { secret: boolean; value: string }>;
},
- });
- const actionConfig = response.action.config as SafeWebhookActionConfig;
+ ) =>
+ caller.automations.updateAutomation({
+ projectId,
+ automationId,
+ name: "Updated URL Automation",
+ eventSource: "prompt",
+ eventAction: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ actionType: "WEBHOOK",
+ actionConfig: {
+ type: "WEBHOOK",
+ apiVersion: { prompt: "v1" },
+ ...actionConfig,
+ },
+ });
- // Verify the URL was updated
- expect(actionConfig.url).toBe("https://example.com/new-webhook-url");
+ it("should reject a URL change when stored secret headers are left blank", async () => {
+ const { project, caller } = await prepare();
+ const { action, automation } = await createWebhookAutomation(
+ project.id,
+ );
- // Verify secret headers were preserved
- expect(actionConfig.displayHeaders).toMatchObject({
- "content-type": { secret: false, value: "application/json" },
- "x-api-key": { secret: true, value: "secr...-123" },
- authorization: { secret: true, value: "Bear...-456" },
+ await expect(
+ updateWebhook(caller, project.id, automation.id, {
+ url: "https://example.org/webhook",
+ requestHeaders: {
+ "content-type": { secret: false, value: "" },
+ "x-api-key": { secret: true, value: "" },
+ },
+ }),
+ ).rejects.toThrow(
+ 'Secret header "x-api-key" must be re-entered when changing the webhook URL',
+ );
+
+ const unchangedAction = await prisma.action.findUniqueOrThrow({
+ where: { id: action.id },
+ });
+ const config = unchangedAction.config as WebhookActionConfigWithSecrets;
+ expect(config.url).toBe("https://example.com/webhook");
+ expect(decrypt(config.requestHeaders!["x-api-key"].value)).toBe(
+ "secret-key-123",
+ );
});
- // Verify the action was updated correctly in the database
- const updatedAction = await prisma.action.findUnique({
- where: { id: action.id },
+ it("should drop stored secret headers on a URL change when no headers are submitted", async () => {
+ const { project, caller } = await prepare();
+ const { action, automation } = await createWebhookAutomation(
+ project.id,
+ );
+
+ await updateWebhook(caller, project.id, automation.id, {
+ url: "https://example.org/webhook",
+ requestHeaders: {},
+ });
+
+ const updatedAction = await prisma.action.findUniqueOrThrow({
+ where: { id: action.id },
+ });
+ const config = updatedAction.config as WebhookActionConfigWithSecrets;
+ expect(config.url).toBe("https://example.org/webhook");
+ expect(config.requestHeaders).toEqual({
+ "content-type": { secret: false, value: "application/json" },
+ });
});
- const config = updatedAction?.config as WebhookActionConfigWithSecrets;
+ it("should accept a URL change when secret headers are re-entered", async () => {
+ const { project, caller } = await prepare();
+ const { action, automation } = await createWebhookAutomation(
+ project.id,
+ );
- // URL should be updated
- expect(config.url).toBe("https://example.com/new-webhook-url");
+ await updateWebhook(caller, project.id, automation.id, {
+ url: "https://example.com/new-webhook-url",
+ requestHeaders: {
+ "content-type": { secret: false, value: "" },
+ "x-api-key": { secret: true, value: "rotated-key-456" },
+ },
+ });
- // Secret headers should still be encrypted and preserved
- expect(config.requestHeaders!["x-api-key"].value).not.toBe(
- "secret-key-123",
- );
- expect(config.requestHeaders!["authorization"].value).not.toBe(
- "Bearer token-456",
- );
+ const updatedAction = await prisma.action.findUniqueOrThrow({
+ where: { id: action.id },
+ });
+ const config = updatedAction.config as WebhookActionConfigWithSecrets;
+ expect(config.url).toBe("https://example.com/new-webhook-url");
+ expect(decrypt(config.requestHeaders!["x-api-key"].value)).toBe(
+ "rotated-key-456",
+ );
+ expect(config.requestHeaders!["content-type"]).toEqual({
+ secret: false,
+ value: "application/json",
+ });
+ });
- // Display values should be preserved
- expect(config.displayHeaders).toMatchObject({
- "content-type": { secret: false, value: "application/json" },
- "x-api-key": { secret: true, value: "secr...-123" },
- authorization: { secret: true, value: "Bear...-456" },
+ it("should keep stored secret headers when the URL is unchanged", async () => {
+ const { project, caller } = await prepare();
+ const { action, automation } = await createWebhookAutomation(
+ project.id,
+ );
+
+ await updateWebhook(caller, project.id, automation.id, {
+ url: "https://EXAMPLE.com/webhook",
+ requestHeaders: {},
+ });
+
+ const updatedAction = await prisma.action.findUniqueOrThrow({
+ where: { id: action.id },
+ });
+ const config = updatedAction.config as WebhookActionConfigWithSecrets;
+ expect(decrypt(config.requestHeaders!["x-api-key"].value)).toBe(
+ "secret-key-123",
+ );
});
});
@@ -2075,7 +2139,7 @@ describe("automations trpc", () => {
actionType: "WEBHOOK",
actionConfig: {
type: "WEBHOOK",
- url: "https://example.com/updated-webhook",
+ url: "https://example.com/webhook",
requestHeaders,
apiVersion: { prompt: "v1" },
},
diff --git a/web/src/__tests__/server/posthog-integration.servertest.ts b/web/src/__tests__/server/posthog-integration.servertest.ts
index 7103fe467e..a51a25a6a7 100644
--- a/web/src/__tests__/server/posthog-integration.servertest.ts
+++ b/web/src/__tests__/server/posthog-integration.servertest.ts
@@ -870,6 +870,28 @@ describe("PostHog Integration legacy export source cutoff gate", () => {
expect(row.enabled).toBe(false);
});
+ it("update changing the hostname with a blank key → BAD_REQUEST", async () => {
+ const { caller, project } = await prepare();
+ await caller.posthogIntegration.update({
+ projectId: project.id,
+ ...baseConfig,
+ });
+ await expect(
+ caller.posthogIntegration.update({
+ projectId: project.id,
+ ...baseConfig,
+ posthogHostname: "https://eu.posthog.com",
+ posthogProjectApiKey: "",
+ }),
+ ).rejects.toThrow(
+ "PostHog Project API Key is required when changing the hostname",
+ );
+ const row = await prisma.posthogIntegration.findUniqueOrThrow({
+ where: { projectId: project.id },
+ });
+ expect(row.posthogHostName).toBe("https://us.posthog.com/");
+ });
+
it("create with a blank key → BAD_REQUEST", async () => {
const { caller, project } = await prepare();
await expect(
diff --git a/web/src/features/automations/components/AutomationForm.tsx b/web/src/features/automations/components/AutomationForm.tsx
index f6d23274d0..41eb98a2c9 100644
--- a/web/src/features/automations/components/AutomationForm.tsx
+++ b/web/src/features/automations/components/AutomationForm.tsx
@@ -490,6 +490,7 @@ export const AutomationForm = ({
webhook: {
url: webhookDefaults.webhook.url || "",
headers: webhookDefaults.webhook.headers || [],
+ originalUrl: webhookDefaults.webhook.originalUrl,
},
};
} else if (actionType === "SLACK") {
diff --git a/web/src/features/automations/components/actions/GitHubDispatchActionForm.tsx b/web/src/features/automations/components/actions/GitHubDispatchActionForm.tsx
index 3ff21267a5..3f9db35cba 100644
--- a/web/src/features/automations/components/actions/GitHubDispatchActionForm.tsx
+++ b/web/src/features/automations/components/actions/GitHubDispatchActionForm.tsx
@@ -12,7 +12,7 @@ import { type UseFormReturn } from "react-hook-form";
import { type ActionDomain } from "@langfuse/shared";
import { ExternalLink } from "@langfuse/icons";
import Link from "next/link";
-import { areGitHubDispatchUrlsEquivalent } from "../../githubDispatchUrl";
+import { areDestinationUrlsEquivalent } from "@/src/features/automations/destinationUrl";
interface GitHubDispatchActionFormProps {
form: UseFormReturn<any>;
@@ -29,7 +29,7 @@ export const GitHubDispatchActionForm: React.FC<
const originalUrl = form.watch("githubDispatch.originalUrl");
const isUrlChanged =
originalUrl !== undefined &&
- !areGitHubDispatchUrlsEquivalent(currentUrl, originalUrl);
+ !areDestinationUrlsEquivalent(currentUrl, originalUrl);
return (
<div className="space-y-4">
diff --git a/web/src/features/automations/components/actions/GitHubDispatchActionHandler.tsx b/web/src/features/automations/components/actions/GitHubDispatchActionHandler.tsx
index a5587bee5a..7012e41cd3 100644
--- a/web/src/features/automations/components/actions/GitHubDispatchActionHandler.tsx
+++ b/web/src/features/automations/components/actions/GitHubDispatchActionHandler.tsx
@@ -8,7 +8,7 @@ import {
type ActionDomain,
} from "@langfuse/shared";
import { z } from "zod";
-import { areGitHubDispatchUrlsEquivalent } from "../../githubDispatchUrl";
+import { areDestinationUrlsEquivalent } from "@/src/features/automations/destinationUrl";
// Define the form schema for GitHub dispatch actions
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Used via z.infer
@@ -82,10 +82,7 @@ export class GitHubDispatchActionHandler implements BaseActionHandler<GitHubDisp
const existingUrl = formData.githubDispatch?.originalUrl;
const isUrlChanged =
existingUrl !== undefined &&
- !areGitHubDispatchUrlsEquivalent(
- formData.githubDispatch.url,
- existingUrl,
- );
+ !areDestinationUrlsEquivalent(formData.githubDispatch.url, existingUrl);
if (isUrlChanged && !formData.githubDispatch?.githubToken.trim()) {
errors.push("GitHub token is required when changing the dispatch URL");
diff --git a/web/src/features/automations/components/actions/WebhookActionForm.tsx b/web/src/features/automations/components/actions/WebhookActionForm.tsx
index 59371c6f2e..1703327eb2 100644
--- a/web/src/features/automations/components/actions/WebhookActionForm.tsx
+++ b/web/src/features/automations/components/actions/WebhookActionForm.tsx
@@ -38,6 +38,7 @@ import {
import { WebhookSecretRender } from "../WebhookSecretRender";
import { CodeSection } from "@/src/components/design-system/CodeSection/CodeSection";
import { showSuccessToast } from "@/src/features/notifications";
+import { areDestinationUrlsEquivalent } from "@/src/features/automations/destinationUrl";
import { cn } from "@/src/utils/tailwind";
export const webhookSchema = z.object({
@@ -60,6 +61,7 @@ export const webhookSchema = z.object({
wasSecret: z.boolean(),
}),
),
+ originalUrl: z.string().optional(),
});
interface WebhookActionFormProps {
@@ -84,6 +86,12 @@ export const WebhookActionForm: React.FC<WebhookActionFormProps> = ({
name: "webhook.headers",
});
+ const currentUrl = form.watch("webhook.url");
+ const originalUrl = form.watch("webhook.originalUrl");
+ const isUrlChanged =
+ originalUrl !== undefined &&
+ !areDestinationUrlsEquivalent(currentUrl, originalUrl);
+
// Filter out headers managed by Langfuse from the user-editable headers
const customHeaderFields = headerFields.filter((field, index) => {
const headerName = form.watch(`webhook.headers.${index}.name`);
@@ -128,6 +136,9 @@ export const WebhookActionForm: React.FC<WebhookActionFormProps> = ({
<FormDescription>
The HTTP URL to call when the trigger fires. We will send a POST
request to this URL. Only HTTPS URLs are allowed for security.
+ {isUrlChanged
+ ? " Re-enter the values of secret headers when changing the URL."
+ : ""}
</FormDescription>
<FormMessage />
</FormItem>
@@ -184,6 +195,13 @@ export const WebhookActionForm: React.FC<WebhookActionFormProps> = ({
const displayValue = form.watch(
`webhook.headers.${originalIndex}.displayValue`,
);
+ const wasSecret = form.watch(
+ `webhook.headers.${originalIndex}.wasSecret`,
+ );
+ const valuePlaceholder =
+ wasSecret && isUrlChanged
+ ? "Re-enter secret value"
+ : displayValue || "Value";
return (
<div
@@ -213,11 +231,7 @@ export const WebhookActionForm: React.FC<WebhookActionFormProps> = ({
<FormItem>
<FormControl>
<Input
- placeholder={
- isSecret && displayValue
- ? displayValue
- : displayValue || "Value"
- }
+ placeholder={valuePlaceholder}
{...field}
disabled={disabled}
type={isSecret ? "password" : "text"}
diff --git a/web/src/features/automations/components/actions/WebhookActionHandler.clienttest.ts b/web/src/features/automations/components/actions/WebhookActionHandler.clienttest.ts
index 2826404741..30a08feaf4 100644
--- a/web/src/features/automations/components/actions/WebhookActionHandler.clienttest.ts
+++ b/web/src/features/automations/components/actions/WebhookActionHandler.clienttest.ts
@@ -43,3 +43,36 @@ describe("WebhookActionHandler.buildActionConfig apiVersion", () => {
expect(apiVersionFor(undefined)).toEqual({ prompt: "v1" });
});
});
+
+describe("WebhookActionHandler.validateFormData URL changes", () => {
+ const storedSecretHeader = {
+ name: "x-api-key",
+ value: "",
+ displayValue: "secr...-123",
+ isSecret: true,
+ wasSecret: true,
+ };
+
+ const validate = (url: string, value = "") =>
+ handler.validateFormData({
+ webhook: {
+ url,
+ headers: [{ ...storedSecretHeader, value }],
+ originalUrl: "https://example.com/hook",
+ },
+ });
+
+ it("requires stored secret headers to be re-entered when the URL changes", () => {
+ expect(validate("https://example.org/hook").errors).toEqual([
+ "Header 1: Re-enter the secret value when changing the webhook URL",
+ ]);
+ });
+
+ it("accepts a URL change with the secret re-entered", () => {
+ expect(validate("https://example.org/hook", "new-key").isValid).toBe(true);
+ });
+
+ it("keeps stored secrets when the URL is unchanged", () => {
+ expect(validate("https://EXAMPLE.com/hook").isValid).toBe(true);
+ });
+});
diff --git a/web/src/features/automations/components/actions/WebhookActionHandler.tsx b/web/src/features/automations/components/actions/WebhookActionHandler.tsx
index 3f44d9e4ab..ed5284e8d4 100644
--- a/web/src/features/automations/components/actions/WebhookActionHandler.tsx
+++ b/web/src/features/automations/components/actions/WebhookActionHandler.tsx
@@ -11,6 +11,7 @@ import {
type ActionDomain,
} from "@langfuse/shared";
import { z } from "zod";
+import { areDestinationUrlsEquivalent } from "@/src/features/automations/destinationUrl";
// Define the form schema for webhook actions
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Used via z.infer
@@ -28,6 +29,7 @@ const WebhookActionFormSchema = z.object({
}),
)
.default([]),
+ originalUrl: z.string().optional(),
}),
});
@@ -91,15 +93,17 @@ export class WebhookActionHandler implements BaseActionHandler<WebhookActionForm
}
getDefaultValues(automation?: AutomationDomain): WebhookActionFormData {
+ const storedUrl =
+ automation?.action?.type === "WEBHOOK" &&
+ automation?.action?.config &&
+ "url" in automation.action.config
+ ? automation.action.config.url
+ : undefined;
return {
webhook: {
- url:
- (automation?.action?.type === "WEBHOOK" &&
- automation?.action?.config &&
- "url" in automation.action.config &&
- automation.action.config.url) ||
- "",
+ url: storedUrl || "",
headers: this.parseHeaders(automation),
+ originalUrl: storedUrl,
},
};
}
@@ -114,9 +118,25 @@ export class WebhookActionHandler implements BaseActionHandler<WebhookActionForm
errors.push("Webhook URL is required");
}
+ const originalUrl = formData.webhook?.originalUrl;
+ const isUrlChanged =
+ originalUrl !== undefined &&
+ !areDestinationUrlsEquivalent(formData.webhook.url, originalUrl);
+
// Validate headers
if (formData.webhook?.headers) {
formData.webhook.headers.forEach((header: HeaderPair, index: number) => {
+ if (
+ isUrlChanged &&
+ header.wasSecret &&
+ header.name.trim() &&
+ !header.value.trim()
+ ) {
+ errors.push(
+ `Header ${index + 1}: Re-enter the secret value when changing the webhook URL`,
+ );
+ }
+
// Only validate non-empty headers
if (header.name.trim() || header.value.trim()) {
if (!header.name.trim()) {
diff --git a/web/src/features/automations/githubDispatchUrl.ts b/web/src/features/automations/destinationUrl.ts
similarity index 78%
rename from web/src/features/automations/githubDispatchUrl.ts
rename to web/src/features/automations/destinationUrl.ts
index a5c6ea58d0..cee1be6b41 100644
--- a/web/src/features/automations/githubDispatchUrl.ts
+++ b/web/src/features/automations/destinationUrl.ts
@@ -1,4 +1,4 @@
-export function areGitHubDispatchUrlsEquivalent(
+export function areDestinationUrlsEquivalent(
firstUrl: string,
secondUrl: string,
): boolean {
diff --git a/web/src/features/automations/server/githubDispatchHelpers.ts b/web/src/features/automations/server/githubDispatchHelpers.ts
index 626287f079..250450518d 100644
--- a/web/src/features/automations/server/githubDispatchHelpers.ts
+++ b/web/src/features/automations/server/githubDispatchHelpers.ts
@@ -12,7 +12,7 @@ import {
validateWebhookURL,
} from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
-import { areGitHubDispatchUrlsEquivalent } from "../githubDispatchUrl";
+import { areDestinationUrlsEquivalent } from "@/src/features/automations/destinationUrl";
interface GitHubDispatchConfigOptions {
actionConfig: ActionCreate;
@@ -86,7 +86,7 @@ export async function processGitHubDispatchActionConfig({
const isUrlChanged =
existingActionConfig !== undefined &&
- !areGitHubDispatchUrlsEquivalent(urlToUse, existingActionConfig.url);
+ !areDestinationUrlsEquivalent(urlToUse, existingActionConfig.url);
const newGithubToken =
typeof gitHubDispatchConfig.githubToken === "string" &&
gitHubDispatchConfig.githubToken.trim() !== ""
diff --git a/web/src/features/automations/server/webhookHelpers.ts b/web/src/features/automations/server/webhookHelpers.ts
index 2971df09d7..afbba16ee3 100644
--- a/web/src/features/automations/server/webhookHelpers.ts
+++ b/web/src/features/automations/server/webhookHelpers.ts
@@ -16,6 +16,7 @@ import {
webhookWhitelistFromEnv,
} from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
+import { areDestinationUrlsEquivalent } from "@/src/features/automations/destinationUrl";
interface WebhookConfigOptions {
actionConfig: ActionCreate;
@@ -64,10 +65,15 @@ export async function processWebhookActionConfig({
const { secretKey: newSecretKey, displaySecretKey: newDisplaySecretKey } =
generateWebhookSecret();
+ const isUrlChanged =
+ existingActionConfig !== undefined &&
+ !areDestinationUrlsEquivalent(actionConfig.url, existingActionConfig.url);
+
// Process headers and generate final action config
const finalActionConfig = processWebhookHeaders(
actionConfig,
existingActionConfig,
+ isUrlChanged,
);
return {
finalActionConfig: {
@@ -86,14 +92,30 @@ export async function processWebhookActionConfig({
* Processes webhook headers by:
* 1. Merging legacy headers with new requestHeaders
* 2. Handling header removal (headers not in input are removed)
- * 3. Preserving existing values when empty values are submitted
+ * 3. Preserving existing values when empty values are submitted, except for
+ * secret values when the URL changes (they must be re-entered, or are
+ * dropped when no headers are submitted, so they are never sent to a
+ * destination they were not entered for)
* 4. Encrypting secret headers based on secret flag
* 5. Generating display values for secret headers
*/
function processWebhookHeaders(
actionConfig: WebhookActionCreate,
existingConfig: WebhookActionConfigWithSecrets | undefined,
+ isUrlChanged: boolean,
): WebhookActionConfigWithSecrets {
+ const assertSecretMayBeKept = (
+ key: string,
+ header: { secret: boolean; value: string },
+ ) => {
+ if (isUrlChanged && header.secret) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Secret header "${key}" must be re-entered when changing the webhook URL`,
+ });
+ }
+ };
+
// Get existing headers for comparison
const existingLegacyHeaders = existingConfig?.headers ?? {}; // legacy headers
const existingRequestHeaders = existingConfig?.requestHeaders ?? {}; // new headers
@@ -111,10 +133,11 @@ function processWebhookHeaders(
{ secret: boolean; value: string }
> = {};
- // If no headers are provided in input, preserve all existing headers
- // This allows URL-only updates without requiring all headers to be resent
+ // An empty input keeps existing headers so URL-only updates need not resend
+ // them; secret headers are dropped instead when the URL changes.
if (Object.keys(inputRequestHeaders).length === 0) {
for (const [key, headerObj] of Object.entries(mergedExistingHeaders)) {
+ if (isUrlChanged && headerObj.secret) continue;
finalRequestHeaders[key] = headerObj;
}
} else {
@@ -148,6 +171,7 @@ function processWebhookHeaders(
// If value is empty, preserve existing value if it exists
if (headerObj.value.trim() === "" && existingHeader) {
+ assertSecretMayBeKept(key, existingHeader);
finalRequestHeaders[key] = existingHeader;
} else if (headerObj.value.trim() !== "") {
// Only process non-empty values
diff --git a/web/src/features/posthog-integration/components/PostHogIntegrationForm.tsx b/web/src/features/posthog-integration/components/PostHogIntegrationForm.tsx
index de39a529a5..eaa61f789f 100644
--- a/web/src/features/posthog-integration/components/PostHogIntegrationForm.tsx
+++ b/web/src/features/posthog-integration/components/PostHogIntegrationForm.tsx
@@ -22,6 +22,7 @@ import {
isExportSourceSelectable,
} from "@/src/features/analytics-integrations";
import { posthogIntegrationFormSchema } from "@/src/features/posthog-integration/types";
+import { areDestinationUrlsEquivalent } from "@/src/features/automations/destinationUrl";
type PostHogIntegrationFormInput = z.input<typeof posthogIntegrationFormSchema>;
@@ -47,6 +48,19 @@ type PostHogIntegrationFormProps = {
resetError?: string;
};
+function getApiKeyDescription(
+ configurationState: PostHogIntegrationFormProps["configurationState"],
+ isHostnameChanged: boolean,
+): string | undefined {
+ if (isHostnameChanged) {
+ return "Enter the API key again when changing the hostname.";
+ }
+ if (configurationState === "configured") {
+ return "Leave blank to keep the current API key.";
+ }
+ return undefined;
+}
+
export function PostHogIntegrationForm({
actionState,
configurationState,
@@ -69,6 +83,21 @@ export function PostHogIntegrationForm({
message: "PostHog Project API Key is required",
});
}
+ if (
+ configurationState === "configured" &&
+ !data.posthogProjectApiKey &&
+ !areDestinationUrlsEquivalent(
+ data.posthogHostname,
+ defaultValues.posthogHostname,
+ )
+ ) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["posthogProjectApiKey"],
+ message:
+ "PostHog Project API Key is required when changing the hostname",
+ });
+ }
if (!isExportSourceSelectable(data.exportSource, exportSourceContext)) {
ctx.addIssue({
code: "custom",
@@ -78,7 +107,7 @@ export function PostHogIntegrationForm({
});
}
}),
- [configurationState, exportSourceContext],
+ [configurationState, defaultValues.posthogHostname, exportSourceContext],
);
const form = useForm({
resolver: zodResolver(formSchema),
@@ -88,6 +117,20 @@ export function PostHogIntegrationForm({
control: form.control,
name: "exportSource",
});
+ const posthogHostname = useWatch({
+ control: form.control,
+ name: "posthogHostname",
+ });
+ const isHostnameChanged =
+ configurationState === "configured" &&
+ !areDestinationUrlsEquivalent(
+ posthogHostname,
+ defaultValues.posthogHostname,
+ );
+ const apiKeyDescription = getApiKeyDescription(
+ configurationState,
+ isHostnameChanged,
+ );
const exportSourceValidation = exportSource
? validateExportSource(exportSource, exportSourceContext)
: ({ ok: true } as const);
@@ -146,11 +189,7 @@ export function PostHogIntegrationForm({
<PostHogForm.Field
name="posthogProjectApiKey"
label="Posthog Project API Key"
- description={
- configurationState === "configured"
- ? "Leave blank to keep the current API key."
- : undefined
- }
+ description={apiKeyDescription}
>
{(field) => (
<PasswordInput
diff --git a/web/src/features/posthog-integration/posthog-integration-router.ts b/web/src/features/posthog-integration/posthog-integration-router.ts
index 2c3abf3a64..ea3e0090ad 100644
--- a/web/src/features/posthog-integration/posthog-integration-router.ts
+++ b/web/src/features/posthog-integration/posthog-integration-router.ts
@@ -17,6 +17,7 @@ import { posthogIntegrationFormSchema } from "@/src/features/posthog-integration
import { TRPCError } from "@trpc/server";
import { env } from "@/src/env.mjs";
import { validateWebhookURL } from "@langfuse/shared/src/server";
+import { areDestinationUrlsEquivalent } from "@/src/features/automations/destinationUrl";
import {
AnalyticsIntegrationExportSource,
LangfuseNotFoundError,
@@ -116,9 +117,26 @@ export const posthogIntegrationRouter = createTRPCRouter({
createdAt: true,
enabled: true,
encryptedPosthogApiKey: true,
+ posthogHostName: true,
},
});
+ // A stored key is only sent to the hostname it was entered for.
+ if (
+ existingIntegration &&
+ !input.posthogProjectApiKey &&
+ !areDestinationUrlsEquivalent(
+ input.posthogHostname,
+ existingIntegration.posthogHostName,
+ )
+ ) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message:
+ "PostHog Project API Key is required when changing the hostname",
+ });
+ }
+
// Write-only credential: blank/omitted keeps the persisted encrypted
// value (write-only credential).
const encryptedPosthogApiKey = input.posthogProjectApiKey