Skip to content

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

feat: automation secrets (#7807)

Thorsten Spieker4cc10840abbc
diff --git a/.codespellrc b/.codespellrc
index 09e92873b0..9ddfafafea 100644
--- a/.codespellrc
+++ b/.codespellrc
@@ -1,4 +1,4 @@
[codespell]
skip = .git,*.pdf,*.svg,package-lock.json,*.prisma,pnpm-lock.yaml
-ignore-words-list = afterall,vertx,notIn
+ignore-words-list = afterall,vertx,notIn,alue
diff --git a/packages/shared/src/domain/automations.ts b/packages/shared/src/domain/automations.ts
index b88727e36a..9a9ad81a31 100644
--- a/packages/shared/src/domain/automations.ts
+++ b/packages/shared/src/domain/automations.ts
@@ -44,10 +44,17 @@ export const AvailableWebhookApiSchema = z.record(
z.enum(["v1"]),
);
+export const RequestHeaderSchema = z.object({
+ secret: z.boolean(),
+ value: z.string(),
+});
+
export const WebhookActionConfigSchema = z.object({
type: z.literal("WEBHOOK"),
url: z.url(),
headers: z.record(z.string(), z.string()),
+ requestHeaders: z.record(z.string(), RequestHeaderSchema),
+ displayHeaders: z.record(z.string(), RequestHeaderSchema),
apiVersion: AvailableWebhookApiSchema,
secretKey: z.string(),
displaySecretKey: z.string(),
@@ -55,6 +62,8 @@ export const WebhookActionConfigSchema = z.object({
export const SafeWebhookActionConfigSchema = WebhookActionConfigSchema.omit({
secretKey: true,
+ headers: true,
+ requestHeaders: true,
});
export type SafeWebhookActionConfig = z.infer<
@@ -64,6 +73,8 @@ export type SafeWebhookActionConfig = z.infer<
export const WebhookActionCreateSchema = WebhookActionConfigSchema.omit({
secretKey: true,
displaySecretKey: true,
+ headers: true, // don't use legacy field anymore
+ displayHeaders: true,
});
export const ActionConfigSchema = z.discriminatedUnion("type", [
diff --git a/packages/shared/src/domain/webhooks.ts b/packages/shared/src/domain/webhooks.ts
index 622c8a324d..f551169990 100644
--- a/packages/shared/src/domain/webhooks.ts
+++ b/packages/shared/src/domain/webhooks.ts
@@ -3,8 +3,8 @@ import { jsonSchema } from "../utils/zod";
import { EventActionSchema } from "./automations";
export const WebhookDefaultHeaders = {
- "Content-Type": "application/json",
- "User-Agent": "Langfuse/1.0",
+ "content-type": "application/json",
+ "user-agent": "Langfuse/1.0",
};
export const WebhookOutboundBaseSchema = z.object({
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index b6c85ff7fc..b26cd1665c 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -68,3 +68,4 @@ export * from "./s3";
// test utils
export * from "./test-utils";
+export * from "./utils/headerUtils";
diff --git a/packages/shared/src/server/repositories/automation-repository.ts b/packages/shared/src/server/repositories/automation-repository.ts
index a637245d4d..d2e375cd9c 100644
--- a/packages/shared/src/server/repositories/automation-repository.ts
+++ b/packages/shared/src/server/repositories/automation-repository.ts
@@ -15,6 +15,7 @@ import {
SafeWebhookActionConfig,
} from "../../domain/automations";
import { FilterState } from "../../types";
+import { decryptSecretHeaders, mergeHeaders } from "../utils/headerUtils";
export const getActionByIdWithSecrets = async ({
projectId,
@@ -35,12 +36,25 @@ export const getActionByIdWithSecrets = async ({
}
const config = actionConfig.config as WebhookActionConfigWithSecrets;
+
+ // Decrypt secret headers for webhook execution using new structure
+ const decryptedHeaders = config.requestHeaders
+ ? decryptSecretHeaders(mergeHeaders(config.headers, config.requestHeaders))
+ : Object.entries(config.headers).reduce(
+ (acc, [key, value]) => {
+ acc[key] = { secret: false, value };
+ return acc;
+ },
+ {} as Record<string, { secret: boolean; value: string }>,
+ );
+
return {
...actionConfig,
config: {
type: config.type,
url: config.url,
- headers: config.headers,
+ requestHeaders: decryptedHeaders,
+ displayHeaders: config.displayHeaders,
apiVersion: config.apiVersion,
displaySecretKey: config.displaySecretKey,
secretKey: config.secretKey,
@@ -116,12 +130,26 @@ const convertTriggerToDomain = (trigger: Trigger): TriggerDomain => {
const convertActionToDomain = (action: Action): ActionDomain => {
const config = action.config as WebhookActionConfigWithSecrets;
+
+ // Handle legacy headers - convert them to displayHeaders format if displayHeaders is undefined
+ let displayHeaders = config.displayHeaders;
+ if (!displayHeaders && config.headers) {
+ // Convert legacy headers to displayHeaders format
+ displayHeaders = Object.entries(config.headers).reduce(
+ (acc, [key, value]) => {
+ acc[key] = { secret: false, value };
+ return acc;
+ },
+ {} as Record<string, { secret: boolean; value: string }>,
+ );
+ }
+
return {
...action,
config: {
type: config.type,
url: config.url,
- headers: config.headers,
+ displayHeaders,
apiVersion: config.apiVersion,
displaySecretKey: config.displaySecretKey,
} as SafeWebhookActionConfig,
diff --git a/packages/shared/src/server/utils/headerUtils.ts b/packages/shared/src/server/utils/headerUtils.ts
new file mode 100644
index 0000000000..417a340602
--- /dev/null
+++ b/packages/shared/src/server/utils/headerUtils.ts
@@ -0,0 +1,90 @@
+import { encrypt, decrypt } from "../../encryption";
+
+export function mergeHeaders(
+ legacyHeaders: Record<string, string> = {},
+ requestHeaders: Record<string, { secret: boolean; value: string }> = {},
+): Record<string, { secret: boolean; value: string }> {
+ const merged: Record<string, { secret: boolean; value: string }> = {};
+
+ // Add legacy headers as non-secret
+ for (const [key, value] of Object.entries(legacyHeaders)) {
+ merged[key] = { secret: false, value };
+ }
+
+ // requestHeaders takes precedence
+ for (const [key, headerObj] of Object.entries(requestHeaders)) {
+ merged[key] = headerObj;
+ }
+
+ return merged;
+}
+
+export function createDisplayHeaders(
+ mergedHeaders: Record<string, { secret: boolean; value: string }>,
+): Record<string, { secret: boolean; value: string }> {
+ const displayHeaders: Record<string, { secret: boolean; value: string }> = {};
+
+ for (const [key, headerObj] of Object.entries(mergedHeaders)) {
+ displayHeaders[key] = {
+ secret: headerObj.secret,
+ value: headerObj.secret
+ ? maskSecretValue(headerObj.value)
+ : headerObj.value,
+ };
+ }
+
+ return displayHeaders;
+}
+
+export function encryptSecretHeaders(
+ headers: Record<string, { secret: boolean; value: string }>,
+): Record<string, { secret: boolean; value: string }> {
+ const processedRequestHeaders: Record<
+ string,
+ { secret: boolean; value: string }
+ > = {};
+
+ for (const [key, headerObj] of Object.entries(headers)) {
+ if (headerObj.secret) {
+ processedRequestHeaders[key] = {
+ secret: true,
+ value: encrypt(headerObj.value),
+ };
+ } else {
+ processedRequestHeaders[key] = { secret: false, value: headerObj.value };
+ }
+ }
+
+ return processedRequestHeaders;
+}
+
+export function decryptSecretHeaders(
+ requestHeaders: Record<string, { secret: boolean; value: string }>,
+): Record<string, { secret: boolean; value: string }> {
+ const decryptedRequestHeaders: Record<
+ string,
+ { secret: boolean; value: string }
+ > = {};
+
+ for (const [key, headerObj] of Object.entries(requestHeaders)) {
+ if (headerObj.secret) {
+ try {
+ decryptedRequestHeaders[key] = {
+ secret: true,
+ value: decrypt(headerObj.value),
+ };
+ } catch (error) {
+ console.error(`Failed to decrypt header ${key}:`, error);
+ }
+ } else {
+ decryptedRequestHeaders[key] = { secret: false, value: headerObj.value };
+ }
+ }
+
+ return decryptedRequestHeaders;
+}
+
+function maskSecretValue(value: string): string {
+ if (value.length <= 8) return "****";
+ return `${value.substring(0, 4)}...${value.substring(value.length - 4)}`;
+}
diff --git a/web/src/__tests__/async/automations-trpc.servertest.ts b/web/src/__tests__/async/automations-trpc.servertest.ts
index 8108306131..bb1225b167 100644
--- a/web/src/__tests__/async/automations-trpc.servertest.ts
+++ b/web/src/__tests__/async/automations-trpc.servertest.ts
@@ -7,9 +7,15 @@ import { prisma } from "@langfuse/shared/src/db";
import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
import type { Session } from "next-auth";
import { v4 } from "uuid";
-import { ActionExecutionStatus, JobConfigState } from "@langfuse/shared";
+import {
+ ActionExecutionStatus,
+ JobConfigState,
+ type SafeWebhookActionConfig,
+ type WebhookActionConfigWithSecrets,
+} from "@langfuse/shared";
import { encrypt, decrypt } from "@langfuse/shared/encryption";
import { generateWebhookSecret } from "@langfuse/shared/encryption";
+import { TRPCError } from "@trpc/server";
const __orgIds: string[] = [];
@@ -155,6 +161,92 @@ describe("automations trpc", () => {
expect(response[0].action.config).not.toHaveProperty("secretKey");
});
+ it("should not expose secret headers in response", async () => {
+ const { project, caller } = await prepare();
+
+ // Create test prompt
+ await prisma.prompt.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ name: "test-prompt",
+ version: 1,
+ type: "text",
+ prompt: { text: "Hello world" },
+ createdBy: "test-user",
+ },
+ });
+
+ // Create test trigger
+ const trigger = await prisma.trigger.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ eventSource: "prompt",
+ eventActions: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ },
+ });
+
+ // Create test action with secret headers
+ const { secretKey, displaySecretKey } = generateWebhookSecret();
+ const action = await prisma.action.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ type: "WEBHOOK",
+ config: {
+ type: "WEBHOOK",
+ url: "https://example.com/webhook",
+ headers: {
+ "content-type": "application/json",
+ "x-api-key": encrypt("secret-api-key-123"),
+ authorization: encrypt("Bearer secret-token-456"),
+ },
+ secretHeaderKeys: ["x-api-key", "authorization"],
+ displayHeaders: {
+ "content-type": "application/json",
+ "x-api-key": "secr***123",
+ authorization: "Bear***456",
+ },
+ apiVersion: { prompt: "v1" },
+ secretKey: encrypt(secretKey),
+ displaySecretKey,
+ },
+ },
+ });
+
+ // Link trigger to action
+ await prisma.automation.create({
+ data: {
+ projectId: project.id,
+ triggerId: trigger.id,
+ actionId: action.id,
+ name: "Secret Headers Automation",
+ },
+ });
+
+ const response = await caller.automations.getAutomations({
+ projectId: project.id,
+ });
+
+ expect(response).toHaveLength(1);
+ const automationConfig = response[0].action.config;
+
+ // Should have display values, not encrypted values
+ expect(automationConfig.displayHeaders).toEqual({
+ "content-type": "application/json",
+ "x-api-key": "secr***123",
+ authorization: "Bear***456",
+ });
+
+ // Should NOT have the raw headers with encrypted values
+ expect(automationConfig).not.toHaveProperty("headers");
+ expect(automationConfig).not.toHaveProperty("decryptedHeaders");
+ expect(automationConfig).not.toHaveProperty("requestHeaders");
+ });
+
it("should return empty array when no automations exist", async () => {
const { project, caller } = await prepare();
@@ -199,15 +291,835 @@ describe("automations trpc", () => {
projectId: project.id,
});
- expect(response).toEqual([]);
+ expect(response).toEqual([]);
+ });
+ });
+
+ describe("automations.getAutomation", () => {
+ it("should retrieve a specific automation", async () => {
+ const { project, caller } = await prepare();
+
+ // Create test trigger and action
+ const trigger = await prisma.trigger.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ 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: {
+ type: "WEBHOOK",
+ url: "https://example.com/webhook",
+ headers: { "Content-Type": "application/json" },
+ displayHeaders: { "Content-Type": "application/json" },
+ apiVersion: { prompt: "v1" },
+ secretKey: encrypt(secretKey),
+ displaySecretKey,
+ },
+ },
+ });
+
+ const automation = await prisma.automation.create({
+ data: {
+ projectId: project.id,
+ triggerId: trigger.id,
+ actionId: action.id,
+ name: "Specific Automation",
+ },
+ });
+
+ const response = await caller.automations.getAutomation({
+ projectId: project.id,
+ automationId: automation.id,
+ });
+
+ expect(response).toMatchObject({
+ name: "Specific Automation",
+ trigger: expect.objectContaining({
+ id: trigger.id,
+ }),
+ action: expect.objectContaining({
+ id: action.id,
+ }),
+ });
+
+ // check that the action does not have a secret key in the config
+ expect(response.action.config).not.toHaveProperty("secretKey");
+ expect(response.action.config).toHaveProperty("displaySecretKey");
+ expect(response.action.config.url).toBe("https://example.com/webhook");
+ expect(response.action.config).not.toHaveProperty("headers");
+ expect(response.action.config.displayHeaders).toEqual({
+ "Content-Type": "application/json",
+ });
+ expect(response.action.config.apiVersion).toEqual({ prompt: "v1" });
+ expect(response.action.config.type).toBe("WEBHOOK");
+ expect(response.action.config.displaySecretKey).toBe(displaySecretKey);
+ expect(response.action.config).not.toHaveProperty("headers");
+ expect(response.action.config).not.toHaveProperty("decryptedHeaders");
+ expect(response.action.config).not.toHaveProperty("requestHeaders");
+ });
+
+ it("should not expose secret headers in single automation response", async () => {
+ const { project, caller } = await prepare();
+
+ // Create test trigger and action with secret headers
+ const trigger = await prisma.trigger.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ 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: {
+ type: "WEBHOOK",
+ url: "https://example.com/webhook",
+ headers: {
+ "content-type": "application/json",
+ "x-custom": "public-value",
+ "x-secret": encrypt("secret-value-789"),
+ },
+ secretHeaderKeys: ["x-secret"],
+ displayHeaders: {
+ "content-type": "application/json",
+ "x-custom": "public-value",
+ "x-secret": "secr***789",
+ },
+ apiVersion: { prompt: "v1" },
+ secretKey: encrypt(secretKey),
+ displaySecretKey,
+ },
+ },
+ });
+
+ const automation = await prisma.automation.create({
+ data: {
+ projectId: project.id,
+ triggerId: trigger.id,
+ actionId: action.id,
+ name: "Mixed Headers Automation",
+ },
+ });
+
+ const response = await caller.automations.getAutomation({
+ projectId: project.id,
+ automationId: automation.id,
+ });
+
+ const config = response.action.config;
+
+ // Should have display values
+ expect(config.displayHeaders).toEqual({
+ "content-type": "application/json",
+ "x-custom": "public-value",
+ "x-secret": "secr***789",
+ });
+
+ // Should NOT have raw encrypted headers
+ expect(config).not.toHaveProperty("headers");
+ });
+
+ it("should return all legacy header values when reading automation", async () => {
+ const { project, caller } = await prepare();
+
+ // Create test trigger and action with legacy headers
+ const trigger = await prisma.trigger.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ 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: {
+ type: "WEBHOOK",
+ url: "https://example.com/webhook",
+ // Legacy headers format - plain object with string values
+ headers: {
+ "content-type": "application/json",
+ "x-api-key": "legacy-api-key-value",
+ },
+ apiVersion: { prompt: "v1" },
+ secretKey: encrypt(secretKey),
+ displaySecretKey,
+ },
+ },
+ });
+
+ const automation = await prisma.automation.create({
+ data: {
+ projectId: project.id,
+ triggerId: trigger.id,
+ actionId: action.id,
+ name: "Legacy Headers Read Test",
+ },
+ });
+
+ const response = await caller.automations.getAutomation({
+ projectId: project.id,
+ automationId: automation.id,
+ });
+
+ const config = response.action.config;
+
+ // Should have display values with all legacy header values returned
+ // Legacy headers are converted to the new format with secret: false
+ expect(config.displayHeaders).toEqual({
+ "content-type": { secret: false, value: "application/json" },
+ "x-api-key": { secret: false, value: "legacy-api-key-value" },
+ });
+
+ // Should NOT have raw headers object in response
+ expect(config).not.toHaveProperty("headers");
+ expect(config).not.toHaveProperty("requestHeaders");
+ });
+
+ it("should throw error when automation not found", async () => {
+ const { project, caller } = await prepare();
+
+ await expect(
+ caller.automations.getAutomation({
+ projectId: project.id,
+ automationId: "non-existent-automation",
+ }),
+ ).rejects.toThrow(
+ `Automation with id non-existent-automation not found.`,
+ );
+ });
+ });
+
+ describe("automations.createAutomation", () => {
+ it("should create a new webhook automation", async () => {
+ const { project, caller } = await prepare();
+
+ // Create test prompt
+ await prisma.prompt.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ name: "test-prompt",
+ version: 1,
+ type: "text",
+ prompt: { text: "Hello world" },
+ createdBy: "test-user",
+ },
+ });
+
+ const response = await caller.automations.createAutomation({
+ projectId: project.id,
+ name: "New Webhook Automation",
+ eventSource: "prompt",
+ eventAction: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ actionType: "WEBHOOK",
+ actionConfig: {
+ type: "WEBHOOK",
+ url: "https://example.com/new-webhook",
+ requestHeaders: {
+ "Content-Type": { secret: false, value: "application/json" },
+ },
+ apiVersion: { prompt: "v1" },
+ },
+ });
+
+ expect(response.trigger).toMatchObject({
+ projectId: project.id,
+ eventSource: "prompt",
+ eventActions: ["created"],
+ status: JobConfigState.ACTIVE,
+ });
+
+ expect(response.action).toMatchObject({
+ projectId: project.id,
+ type: "WEBHOOK",
+ config: expect.objectContaining({
+ type: "WEBHOOK",
+ url: "https://example.com/new-webhook",
+ }),
+ });
+
+ expect(response.webhookSecret).toBeDefined();
+ expect(typeof response.webhookSecret).toBe("string");
+
+ // Verify the automation link was created
+ const automation = await prisma.automation.findFirst({
+ where: {
+ triggerId: response.trigger.id,
+ actionId: response.action.id,
+ },
+ });
+
+ expect(automation).toMatchObject({
+ name: "New Webhook Automation",
+ });
+ });
+
+ it("should create automation with both plain and secret headers", async () => {
+ const { project, caller } = await prepare();
+
+ // Create test prompt
+ await prisma.prompt.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ name: "test-prompt",
+ version: 1,
+ type: "text",
+ prompt: { text: "Hello world" },
+ createdBy: "test-user",
+ },
+ });
+
+ const response = await caller.automations.createAutomation({
+ projectId: project.id,
+ name: "Mixed Headers Automation",
+ eventSource: "prompt",
+ eventAction: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ actionType: "WEBHOOK",
+ actionConfig: {
+ type: "WEBHOOK",
+ url: "https://example.com/mixed-headers",
+ requestHeaders: {
+ "content-type": { secret: false, value: "application/json" },
+ "x-public": { secret: false, value: "public-value" },
+ "x-api-key": { secret: true, value: "secret-key-123" },
+ authorization: { secret: true, value: "Bearer secret-token-456" },
+ },
+ apiVersion: { prompt: "v1" },
+ },
+ });
+
+ // Verify the action was created correctly in the database
+ const createdAction = await prisma.action.findUnique({
+ where: { id: response.action.id },
+ });
+
+ expect(createdAction?.config).toMatchObject({
+ type: "WEBHOOK",
+ url: "https://example.com/mixed-headers",
+ });
+
+ // Headers should be encrypted for secret ones, plain for others
+ const config = createdAction?.config as WebhookActionConfigWithSecrets;
+ expect(config.requestHeaders["content-type"].value).toBe(
+ "application/json",
+ );
+ expect(config.requestHeaders["x-public"].value).toBe("public-value");
+ expect(config.requestHeaders["x-api-key"].secret).toBe(true);
+ expect(config.requestHeaders["x-api-key"].value).not.toBe(
+ "secret-key-123",
+ ); // Should be encrypted
+ expect(config.requestHeaders["authorization"].secret).toBe(true);
+ expect(config.requestHeaders["authorization"].value).not.toBe(
+ "Bearer secret-token-456",
+ ); // Should be encrypted
+
+ // Display values should be present
+ expect(config.displayHeaders).toMatchObject({
+ "content-type": { secret: false, value: "application/json" },
+ "x-public": { secret: false, value: "public-value" },
+ });
+ expect(config.displayHeaders["x-api-key"].value).toBe("secr...-123");
+ expect(config.displayHeaders["authorization"].value).toBe("Bear...-456");
+ });
+
+ it("should create automation with secret headers that do not expose values in response", async () => {
+ const { project, caller } = await prepare();
+
+ const response = await caller.automations.createAutomation({
+ projectId: project.id,
+ name: "Secret Headers Test",
+ eventSource: "prompt",
+ eventAction: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ actionType: "WEBHOOK",
+ actionConfig: {
+ type: "WEBHOOK",
+ url: "https://example.com/webhook",
+ requestHeaders: {
+ "content-type": { secret: false, value: "application/json" },
+ "x-public": { secret: false, value: "public-value" },
+ "x-api-key": { secret: true, value: "secret-value-123" },
+ authorization: { secret: true, value: "Bearer token-456" },
+ },
+ apiVersion: { prompt: "v1" },
+ },
+ });
+
+ const responseConfig = response.action.config as SafeWebhookActionConfig;
+ // Response should NOT contain the raw secret values
+ expect(responseConfig.displayHeaders).not.toMatchObject({
+ "x-api-key": { secret: true, value: "secret-value-123" },
+ authorization: { secret: true, value: "Bearer token-456" },
+ });
+
+ // Response should contain masked values
+ expect(responseConfig.displayHeaders).toMatchObject({
+ "content-type": { secret: false, value: "application/json" },
+ "x-public": { secret: false, value: "public-value" },
+ "x-api-key": { secret: true, value: "secr...-123" },
+ authorization: { secret: true, value: "Bear...-456" },
+ });
+
+ // Verify secrets fields are not present in response
+ expect(responseConfig).not.toHaveProperty("headers");
+ expect(responseConfig).not.toHaveProperty("requestHeaders");
+
+ // Check the actual stored data in the database
+ const createdAction = await prisma.action.findUnique({
+ where: { id: response.action.id },
+ });
+
+ const config = createdAction?.config as WebhookActionConfigWithSecrets;
+ // Public headers should remain plain
+ // Secret headers should be encrypted in storage
+ expect(config.requestHeaders).toMatchObject({
+ "content-type": { secret: false, value: "application/json" },
+ "x-public": { secret: false, value: "public-value" },
+ });
+ expect(config.requestHeaders["x-api-key"].value).not.toBe(
+ "secret-value-123",
+ );
+ expect(config.requestHeaders["authorization"].value).not.toBe(
+ "Bearer token-456",
+ );
+
+ // Display values should be present with masked secrets
+ expect(config.displayHeaders).toMatchObject({
+ "content-type": { secret: false, value: "application/json" },
+ "x-public": { secret: false, value: "public-value" },
+ "x-api-key": { secret: true, value: "secr...-123" },
+ authorization: { secret: true, value: "Bear...-456" },
+ });
+ });
+
+ it("should throw error when user lacks automations:CUD access", async () => {
+ const { project, session } = await prepare();
+
+ // Create a session with limited permissions
+ const limitedSession: Session = {
+ ...session,
+ user: {
+ ...session.user!,
+ admin: false,
+ organizations: [
+ {
+ ...session.user!.organizations[0],
+ role: "MEMBER",
+ projects: [
+ {
+ ...session.user!.organizations[0].projects[0],
+ role: "VIEWER", // VIEWER role doesn't have automations:CUD scope
+ },
+ ],
+ },
+ ],
+ },
+ };
+
+ const limitedCtx = createInnerTRPCContext({
+ session: limitedSession,
+ headers: {},
+ });
+ const limitedCaller = appRouter.createCaller({ ...limitedCtx, prisma });
+
+ await expect(
+ limitedCaller.automations.createAutomation({
+ projectId: project.id,
+ name: "Unauthorized Automation",
+ eventSource: "prompt",
+ eventAction: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ actionType: "WEBHOOK",
+ actionConfig: {
+ type: "WEBHOOK",
+ url: "https://example.com/webhook",
+ requestHeaders: {},
+ apiVersion: { prompt: "v1" },
+ },
+ }),
+ ).rejects.toThrow("User does not have access to this resource or action");
+ });
+
+ it("should validate required fields", async () => {
+ const { project, caller } = await prepare();
+
+ await expect(
+ caller.automations.createAutomation({
+ projectId: project.id,
+ name: "", // Empty name should fail
+ eventSource: "prompt",
+ eventAction: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ actionType: "WEBHOOK",
+ actionConfig: {
+ type: "WEBHOOK",
+ url: "https://example.com/webhook",
+ requestHeaders: {},
+ apiVersion: { prompt: "v1" },
+ },
+ }),
+ ).rejects.toThrow("Name is required");
+ });
+ });
+
+ describe("automations.updateAutomation", () => {
+ it("should update an existing automation", async () => {
+ const { project, caller } = await prepare();
+
+ // Create initial automation
+ const trigger = await prisma.trigger.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ 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: {
+ type: "WEBHOOK",
+ url: "https://example.com/webhook",
+ requestHeaders: {
+ "Content-Type": { secret: false, value: "application/json" },
+ },
+ apiVersion: { prompt: "v1" },
+ secretKey: encrypt(secretKey),
+ displaySecretKey,
+ },
+ },
+ });
+
+ const automation = await prisma.automation.create({
+ data: {
+ projectId: project.id,
+ triggerId: trigger.id,
+ actionId: action.id,
+ name: "Original Name",
+ },
+ });
+
+ const response = await caller.automations.updateAutomation({
+ projectId: project.id,
+ automationId: automation.id,
+ name: "Updated Name",
+ eventSource: "prompt",
+ eventAction: ["created", "updated"],
+ filter: [],
+ status: JobConfigState.INACTIVE,
+ actionType: "WEBHOOK",
+ actionConfig: {
+ type: "WEBHOOK",
+ url: "https://example.com/updated-webhook",
+ requestHeaders: {
+ "Content-Type": { secret: false, value: "application/json" },
+ "X-Custom": { secret: false, value: "value" },
+ },
+ apiVersion: { prompt: "v1" },
+ },
+ });
+
+ expect(response.trigger).toMatchObject({
+ id: trigger.id,
+ eventActions: ["created", "updated"],
+ status: JobConfigState.INACTIVE,
+ });
+
+ expect(response.action.id).toBe(action.id);
+ expect(response.action.type).toBe("WEBHOOK");
+ expect(response.action.config).toMatchObject({
+ type: "WEBHOOK",
+ url: "https://example.com/updated-webhook",
+ displayHeaders: {
+ "Content-Type": { secret: false, value: "application/json" },
+ "X-Custom": { secret: false, value: "value" },
+ },
+ });
+
+ // Verify secrets fields are not present in response
+ expect(response.action.config).not.toHaveProperty("headers");
+ expect(response.action.config).not.toHaveProperty("secretKey");
+
+ // Verify the automation name was updated
+ const updatedAutomation = await prisma.automation.findFirst({
+ where: {
+ id: automation.id,
+ },
+ });
+
+ expect(updatedAutomation?.name).toBe("Updated Name");
+ });
+
+ it("should update automation with both plain and secret headers", async () => {
+ const { project, caller } = await prepare();
+
+ // Create initial automation
+ const trigger = await prisma.trigger.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ 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: {
+ type: "WEBHOOK",
+ url: "https://example.com/webhook",
+ requestHeaders: {
+ "content-type": { secret: false, value: "application/json" },
+ "x-old-header": { secret: false, value: "old-value" },
+ "x-case-key": { secret: false, value: "some-value" },
+ },
+ displayHeaders: {
+ "content-type": "application/json",
+ "x-old-header": "old-value",
+ "x-case-key": "some-value",
+ },
+ apiVersion: { prompt: "v1" },
+ secretKey: encrypt(secretKey),
+ displaySecretKey,
+ },
+ },
+ });
+
+ const automation = await prisma.automation.create({
+ data: {
+ projectId: project.id,
+ triggerId: trigger.id,
+ actionId: action.id,
+ name: "Headers Update Test",
+ },
+ });
+
+ const response = await caller.automations.updateAutomation({
+ projectId: project.id,
+ automationId: automation.id,
+ name: "Updated Headers Automation",
+ eventSource: "prompt",
+ eventAction: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ actionType: "WEBHOOK",
+ actionConfig: {
+ type: "WEBHOOK",
+ url: "https://example.com/updated-webhook",
+ requestHeaders: {
+ "content-type": { secret: false, value: "" },
+ "x-public": { secret: false, value: "new-public-value" },
+ "x-secret-key": { secret: true, value: "new-secret-123" },
+ "x-Case-KEY": { secret: false, value: "new-value" },
+ },
+ apiVersion: { prompt: "v1" },
+ },
+ });
+
+ // Verify the API response contains safe display values
+ expect(response.action.config.displayHeaders).toMatchObject({
+ "content-type": { secret: false, value: "application/json" }, // header preserved
+ "x-public": { secret: false, value: "new-public-value" }, // new public header
+ "x-secret-key": { secret: true, value: "new-...-123" }, // new secret header
+ "x-Case-KEY": { secret: false, value: "new-value" }, // matched existing key, but new value
+ });
+
+ expect(response.action.config.displayHeaders).not.toHaveProperty(
+ "x-old-header", // header deleted
+ );
+ expect(response.action.config.displayHeaders).not.toHaveProperty(
+ "x-case-key", // new case replaced the old header name
+ );
+
+ expect(response.action.config).not.toHaveProperty("headers");
+ expect(response.action.config).not.toHaveProperty("secretKey");
+
+ // Verify the action was updated correctly in the database
+ const updatedAction = await prisma.action.findUnique({
+ where: { id: action.id },
+ });
+
+ const config = updatedAction?.config as any;
+
+ // Public headers should remain plain
+ expect(config.requestHeaders["content-type"].value).toBe(
+ "application/json",
+ );
+ expect(config.requestHeaders["x-public"].value).toBe("new-public-value");
+
+ // Secret headers should be encrypted
+ expect(config.requestHeaders["x-secret-key"].value).not.toBe(
+ "new-secret-123",
+ );
+ expect(config.requestHeaders["x-Case-KEY"].value).toBe("new-value");
+ expect(config.requestHeaders["x-case-key"]).toBeUndefined();
+
+ // Display values should be present with masked secrets
+ expect(config.displayHeaders).toMatchObject({
+ "content-type": { secret: false, value: "application/json" },
+ "x-public": { secret: false, value: "new-public-value" },
+ "x-secret-key": { secret: true, value: "new-...-123" },
+ "x-Case-KEY": { secret: false, value: "new-value" },
+ });
+ expect(config.displayHeaders).not.toHaveProperty("x-case-key");
+ });
+
+ it("should handle switching header types from secret to plain and vice versa", async () => {
+ const { project, caller } = await prepare();
+
+ // Create initial automation with mixed headers
+ const trigger = await prisma.trigger.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ 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: {
+ type: "WEBHOOK",
+ url: "https://example.com/webhook",
+ requestHeaders: {
+ "content-type": { secret: false, value: "application/json" },
+ "x-currently-public": { secret: false, value: "public-value" },
+ "x-currently-secret": { secret: true, value: "secret-value" },
+ },
+ displayHeaders: {
+ "content-type": { secret: false, value: "application/json" },
+ "x-currently-public": { secret: false, value: "public-value" },
+ "x-currently-secret": { secret: true, value: "secr...alue" },
+ },
+ apiVersion: { prompt: "v1" },
+ secretKey: encrypt(secretKey),
+ displaySecretKey,
+ },
+ },
+ });
+
+ const automation = await prisma.automation.create({
+ data: {
+ projectId: project.id,
+ triggerId: trigger.id,
+ actionId: action.id,
+ name: "Header Type Switch Test",
+ },
+ });
+
+ // Update: switch the header types
+ const response = await caller.automations.updateAutomation({
+ projectId: project.id,
+ automationId: automation.id,
+ name: "Switched Headers Automation",
+ eventSource: "prompt",
+ eventAction: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ actionType: "WEBHOOK",
+ actionConfig: {
+ type: "WEBHOOK",
+ url: "https://example.com/updated-webhook",
+ requestHeaders: {
+ "content-type": { secret: false, value: "application/json" },
+ "x-currently-public": { secret: true, value: "now-secret-value" }, // Was public, now secret
+ "x-currently-secret": { secret: false, value: "now-public-value" }, // Was secret, now public
+ },
+ apiVersion: { prompt: "v1" },
+ },
+ });
+
+ // Verify the API response contains safe display values reflecting the switch
+ expect(response.action.config.displayHeaders).toMatchObject({
+ "x-currently-public": { secret: true, value: "now-...alue" },
+ "x-currently-secret": { secret: false, value: "now-public-value" },
+ });
+ expect(response.action.config).not.toHaveProperty("headers");
+ expect(response.action.config).not.toHaveProperty("secretKey");
+
+ // Verify the switch worked correctly
+ const updatedAction = await prisma.action.findUnique({
+ where: { id: action.id },
+ });
+
+ const config = updatedAction?.config as any;
+
+ // x-currently-public should now be encrypted (was plain, now secret)
+ expect(config.requestHeaders["x-currently-public"].value).not.toBe(
+ "now-secret-value",
+ );
+
+ // x-currently-secret should now be plain (was secret, now public)
+ expect(config.requestHeaders["x-currently-secret"].value).toBe(
+ "now-public-value",
+ );
+
+ // Display values should reflect the changes
+ expect(config.displayHeaders).toMatchObject({
+ "x-currently-public": { secret: true, value: "now-...alue" },
+ "x-currently-secret": { secret: false, value: "now-public-value" },
+ });
});
- });
- describe("automations.getAutomation", () => {
- it("should retrieve a specific automation", async () => {
+ it("should fail to flip secret header without providing a value", async () => {
const { project, caller } = await prepare();
- // Create test trigger and action
+ // Create initial automation with mixed headers
const trigger = await prisma.trigger.create({
data: {
id: v4(),
@@ -228,7 +1140,15 @@ describe("automations trpc", () => {
config: {
type: "WEBHOOK",
url: "https://example.com/webhook",
- headers: { "Content-Type": "application/json" },
+ requestHeaders: {
+ "x-currently-secret": {
+ secret: true,
+ value: encrypt("secret-value"),
+ },
+ },
+ displayHeaders: {
+ "x-currently-secret": { secret: true, value: "secr...alue" },
+ },
apiVersion: { prompt: "v1" },
secretKey: encrypt(secretKey),
displaySecretKey,
@@ -241,71 +1161,116 @@ describe("automations trpc", () => {
projectId: project.id,
triggerId: trigger.id,
actionId: action.id,
- name: "Specific Automation",
+ name: "Header Type Switch Failed Test",
},
});
- const response = await caller.automations.getAutomation({
- projectId: project.id,
- automationId: automation.id,
- });
+ // Update: try to switch the header types
+ try {
+ await caller.automations.updateAutomation({
+ projectId: project.id,
+ automationId: automation.id,
+ name: "Switched Headers Automation",
+ eventSource: "prompt",
+ eventAction: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ actionType: "WEBHOOK",
+ actionConfig: {
+ type: "WEBHOOK",
+ url: "https://example.com/updated-webhook",
+ requestHeaders: {
+ "x-currently-secret": { secret: false, value: "" }, // Was secret, now public
+ },
+ apiVersion: { prompt: "v1" },
+ },
+ });
- expect(response).toMatchObject({
- name: "Specific Automation",
- trigger: expect.objectContaining({
- id: trigger.id,
- }),
- action: expect.objectContaining({
- id: action.id,
- }),
- });
+ fail("Expected an error to be thrown");
+ } catch (error: any) {
+ expect(error).toBeInstanceOf(TRPCError);
+ expect(error.message).toBe(
+ 'Header "x-currently-secret" secret status can only be changed when providing a value',
+ );
+ expect(error.code).toBe("BAD_REQUEST");
+ }
- // check that the action does not have a secret key in the config
- expect(response.action.config).not.toHaveProperty("secretKey");
- expect(response.action.config).toHaveProperty("displaySecretKey");
- expect(response.action.config.url).toBe("https://example.com/webhook");
- expect(response.action.config.headers).toEqual({
- "Content-Type": "application/json",
+ // Verify the switch did not work
+ const updatedAction = await prisma.action.findUnique({
+ where: { id: action.id },
});
- expect(response.action.config.apiVersion).toEqual({ prompt: "v1" });
- expect(response.action.config.type).toBe("WEBHOOK");
- expect(response.action.config.displaySecretKey).toBe(displaySecretKey);
- });
- it("should throw error when automation not found", async () => {
- const { project, caller } = await prepare();
+ const config = updatedAction?.config as WebhookActionConfigWithSecrets;
- await expect(
- caller.automations.getAutomation({
- projectId: project.id,
- automationId: "non-existent-automation",
- }),
- ).rejects.toThrow(
- `Automation with id non-existent-automation not found.`,
+ // x-currently-secret should still be encrypted
+ expect(config.requestHeaders["x-currently-secret"].value).not.toBe(
+ "secret-value",
);
+
+ // Display values should reflect the changes
+ expect(config.displayHeaders).toMatchObject({
+ "x-currently-secret": { secret: true, value: "secr...alue" },
+ });
});
- });
- describe("automations.createAutomation", () => {
- it("should create a new webhook automation", async () => {
+ it("should allow URL update without requiring secret header values", async () => {
const { project, caller } = await prepare();
- // Create test prompt
- await prisma.prompt.create({
+ // Create initial automation with secret headers
+ const trigger = await prisma.trigger.create({
data: {
id: v4(),
projectId: project.id,
- name: "test-prompt",
- version: 1,
- type: "text",
- prompt: { text: "Hello world" },
- createdBy: "test-user",
+ eventSource: "prompt",
+ eventActions: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
},
});
- const response = await caller.automations.createAutomation({
+ const { secretKey, displaySecretKey } = generateWebhookSecret();
+ const action = await prisma.action.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ type: "WEBHOOK",
+ 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") },
+ authorization: {
+ secret: true,
+ value: encrypt("Bearer token-456"),
+ },
+ },
+ 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",
+ },
+ });
+
+ // Update only the URL without providing secret header values
+ const response = await caller.automations.updateAutomation({
projectId: project.id,
- name: "New Webhook Automation",
+ automationId: automation.id,
+ name: "Updated URL Automation",
eventSource: "prompt",
eventAction: ["created"],
filter: [],
@@ -313,121 +1278,54 @@ describe("automations trpc", () => {
actionType: "WEBHOOK",
actionConfig: {
type: "WEBHOOK",
- url: "https://example.com/new-webhook",
- headers: { "Content-Type": "application/json" },
+ url: "https://example.com/new-webhook-url",
+ requestHeaders: {}, // No headers provided
apiVersion: { prompt: "v1" },
},
});
- expect(response.trigger).toMatchObject({
- projectId: project.id,
- eventSource: "prompt",
- eventActions: ["created"],
- status: JobConfigState.ACTIVE,
- });
+ // Verify the URL was updated
+ expect(response.action.config.url).toBe(
+ "https://example.com/new-webhook-url",
+ );
- expect(response.action).toMatchObject({
- projectId: project.id,
- type: "WEBHOOK",
- config: expect.objectContaining({
- type: "WEBHOOK",
- url: "https://example.com/new-webhook",
- }),
+ // Verify secret headers were preserved
+ expect(response.action.config.displayHeaders).toMatchObject({
+ "content-type": { secret: false, value: "application/json" },
+ "x-api-key": { secret: true, value: "secr...-123" },
+ authorization: { secret: true, value: "Bear...-456" },
});
- expect(response.webhookSecret).toBeDefined();
- expect(typeof response.webhookSecret).toBe("string");
-
- // Verify the automation link was created
- const automation = await prisma.automation.findFirst({
- where: {
- triggerId: response.trigger.id,
- actionId: response.action.id,
- },
+ // Verify the action was updated correctly in the database
+ const updatedAction = await prisma.action.findUnique({
+ where: { id: action.id },
});
- expect(automation).toMatchObject({
- name: "New Webhook Automation",
- });
- });
+ const config = updatedAction?.config as WebhookActionConfigWithSecrets;
- it("should throw error when user lacks automations:CUD access", async () => {
- const { project, session } = await prepare();
+ // URL should be updated
+ expect(config.url).toBe("https://example.com/new-webhook-url");
- // Create a session with limited permissions
- const limitedSession: Session = {
- ...session,
- user: {
- ...session.user!,
- admin: false,
- organizations: [
- {
- ...session.user!.organizations[0],
- role: "MEMBER",
- projects: [
- {
- ...session.user!.organizations[0].projects[0],
- role: "VIEWER", // VIEWER role doesn't have automations:CUD scope
- },
- ],
- },
- ],
- },
- };
+ // 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 limitedCtx = createInnerTRPCContext({
- session: limitedSession,
- headers: {},
+ // 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" },
});
- const limitedCaller = appRouter.createCaller({ ...limitedCtx, prisma });
-
- await expect(
- limitedCaller.automations.createAutomation({
- projectId: project.id,
- name: "Unauthorized Automation",
- eventSource: "prompt",
- eventAction: ["created"],
- filter: [],
- status: JobConfigState.ACTIVE,
- actionType: "WEBHOOK",
- actionConfig: {
- type: "WEBHOOK",
- url: "https://example.com/webhook",
- headers: {},
- apiVersion: { prompt: "v1" },
- },
- }),
- ).rejects.toThrow("User does not have access to this resource or action");
- });
-
- it("should validate required fields", async () => {
- const { project, caller } = await prepare();
-
- await expect(
- caller.automations.createAutomation({
- projectId: project.id,
- name: "", // Empty name should fail
- eventSource: "prompt",
- eventAction: ["created"],
- filter: [],
- status: JobConfigState.ACTIVE,
- actionType: "WEBHOOK",
- actionConfig: {
- type: "WEBHOOK",
- url: "https://example.com/webhook",
- headers: {},
- apiVersion: { prompt: "v1" },
- },
- }),
- ).rejects.toThrow("Name is required");
});
- });
- describe("automations.updateAutomation", () => {
- it("should update an existing automation", async () => {
+ it("should migrate legacy headers to new format on update", async () => {
const { project, caller } = await prepare();
- // Create initial automation
+ // Create initial automation with legacy headers format
const trigger = await prisma.trigger.create({
data: {
id: v4(),
@@ -448,7 +1346,11 @@ describe("automations trpc", () => {
config: {
type: "WEBHOOK",
url: "https://example.com/webhook",
- headers: { "Content-Type": "application/json" },
+ // Legacy headers format - plain object with string values
+ headers: {
+ "content-type": "application/json",
+ "x-api-key": "legacy-api-key",
+ },
apiVersion: { prompt: "v1" },
secretKey: encrypt(secretKey),
displaySecretKey,
@@ -461,55 +1363,64 @@ describe("automations trpc", () => {
projectId: project.id,
triggerId: trigger.id,
actionId: action.id,
- name: "Original Name",
+ name: "Legacy Headers Migration Test",
},
});
+ // Update the automation with new headers format, making one secret
const response = await caller.automations.updateAutomation({
projectId: project.id,
automationId: automation.id,
- name: "Updated Name",
+ name: "Migrated Headers Automation",
eventSource: "prompt",
- eventAction: ["created", "updated"],
+ eventAction: ["created"],
filter: [],
- status: JobConfigState.INACTIVE,
+ status: JobConfigState.ACTIVE,
actionType: "WEBHOOK",
actionConfig: {
type: "WEBHOOK",
url: "https://example.com/updated-webhook",
- headers: { "Content-Type": "application/json", "X-Custom": "value" },
+ requestHeaders: {
+ "content-type": { secret: false, value: "application/json" },
+ "x-api-key": { secret: true, value: "new-secret-key" },
+ },
apiVersion: { prompt: "v1" },
},
});
- expect(response.trigger).toMatchObject({
- id: trigger.id,
- eventActions: ["created", "updated"],
- status: JobConfigState.INACTIVE,
+ // Verify the API response
+ expect(response.action.config.displayHeaders).toMatchObject({
+ "content-type": { secret: false, value: "application/json" },
+ "x-api-key": { secret: true, value: "new-...-key" },
});
- expect(response.action.id).toBe(action.id);
- expect(response.action.type).toBe("WEBHOOK");
- expect(response.action.config).toMatchObject({
- type: "WEBHOOK",
- url: "https://example.com/updated-webhook",
- headers: {
- "Content-Type": "application/json",
- "X-Custom": "value",
- },
+ // Verify the action was updated correctly in the database
+ const updatedAction = await prisma.action.findUnique({
+ where: { id: action.id },
});
- // Note: secretKey might be present in update response but shouldn't be in read operations
- // The important test is that it doesn't appear in getAutomations/getAutomation responses
+ const config = updatedAction?.config as WebhookActionConfigWithSecrets;
- // Verify the automation name was updated
- const updatedAutomation = await prisma.automation.findFirst({
- where: {
- id: automation.id,
- },
- });
+ // Legacy headers object should be empty
+ expect(config.headers).toEqual({});
- expect(updatedAutomation?.name).toBe("Updated Name");
+ // Secret header should be encrypted in requestHeaders
+ expect(config.requestHeaders["x-api-key"].secret).toBe(true);
+ expect(config.requestHeaders["x-api-key"].value).not.toBe(
+ "new-secret-key",
+ );
+
+ // Public header should remain plain
+ expect(config.requestHeaders["content-type"].secret).toBe(false);
+ expect(config.requestHeaders["content-type"].value).toBe(
+ "application/json",
+ );
+
+ // Both headers should be in displayHeaders
+ expect(config.displayHeaders).toMatchObject({
+ "content-type": { secret: false, value: "application/json" },
+ "x-api-key": { secret: true, value: "new-...-key" },
+ });
});
});
@@ -538,7 +1449,9 @@ describe("automations trpc", () => {
config: {
type: "WEBHOOK",
url: "https://example.com/webhook",
- headers: { "Content-Type": "application/json" },
+ requestHeaders: {
+ "Content-Type": { secret: false, value: "application/json" },
+ },
apiVersion: { prompt: "v1" },
secretKey: encrypt(secretKey),
displaySecretKey,
@@ -654,7 +1567,9 @@ describe("automations trpc", () => {
config: {
type: "WEBHOOK",
url: "https://example.com/webhook",
- headers: { "Content-Type": "application/json" },
+ requestHeaders: {
+ "Content-Type": { secret: false, value: "application/json" },
+ },
apiVersion: { prompt: "v1" },
secretKey: encrypt(secretKey),
displaySecretKey,
@@ -732,7 +1647,9 @@ describe("automations trpc", () => {
config: {
type: "WEBHOOK",
url: "https://example.com/webhook",
- headers: { "Content-Type": "application/json" },
+ requestHeaders: {
+ "Content-Type": { secret: false, value: "application/json" },
+ },
apiVersion: { prompt: "v1" },
secretKey: encrypt(secretKey),
displaySecretKey,
@@ -819,7 +1736,9 @@ describe("automations trpc", () => {
config: {
type: "WEBHOOK",
url: "https://example.com/webhook",
- headers: { "Content-Type": "application/json" },
+ requestHeaders: {
+ "Content-Type": { secret: false, value: "application/json" },
+ },
apiVersion: { prompt: "v1" },
secretKey: encrypt(secretKey),
displaySecretKey,
@@ -880,7 +1799,9 @@ describe("automations trpc", () => {
config: {
type: "WEBHOOK",
url: "https://example.com/webhook",
- headers: { "Content-Type": "application/json" },
+ requestHeaders: {
+ "Content-Type": { secret: false, value: "application/json" },
+ },
apiVersion: { prompt: "v1" },
secretKey: encrypt(originalSecretKey),
displaySecretKey: originalDisplaySecretKey,
@@ -956,7 +1877,9 @@ describe("automations trpc", () => {
config: {
type: "WEBHOOK",
url: "https://example.com/webhook",
- headers: { "Content-Type": "application/json" },
+ requestHeaders: {
+ "Content-Type": { secret: false, value: "application/json" },
+ },
apiVersion: { prompt: "v1" },
secretKey: encrypt(secretKey),
displaySecretKey,
diff --git a/web/src/features/automations/components/AutomationDetails.tsx b/web/src/features/automations/components/AutomationDetails.tsx
index def72fdd41..631b12f55f 100644
--- a/web/src/features/automations/components/AutomationDetails.tsx
+++ b/web/src/features/automations/components/AutomationDetails.tsx
@@ -97,7 +97,7 @@ export const AutomationDetails: React.FC<AutomationDetailsProps> = ({
config: automation.action.config as {
type: "WEBHOOK";
url: string;
- headers: Record<string, string>;
+ displayHeaders: Record<string, { secret: boolean; value: string }>;
apiVersion: Record<"prompt", "v1">;
displaySecretKey: string;
},
diff --git a/web/src/features/automations/components/actions/BaseActionHandler.ts b/web/src/features/automations/components/actions/BaseActionHandler.ts
index f91f911f91..6ef26d3139 100644
--- a/web/src/features/automations/components/actions/BaseActionHandler.ts
+++ b/web/src/features/automations/components/actions/BaseActionHandler.ts
@@ -1,9 +1,9 @@
import { type UseFormReturn, type FieldValues } from "react-hook-form";
import {
+ type ActionCreate,
type ActionDomain,
type ActionType,
type AutomationDomain,
- type SafeWebhookActionConfig,
} from "@langfuse/shared";
export interface BaseActionHandler<
@@ -21,9 +21,7 @@ export interface BaseActionHandler<
};
// Build the action config for API submission
- buildActionConfig(
- formData: TFormData,
- ): Omit<SafeWebhookActionConfig, "displaySecretKey">;
+ buildActionConfig(formData: TFormData): ActionCreate;
// Render the action form UI - using any for form to allow flexibility
renderForm(props: {
diff --git a/web/src/features/automations/components/actions/WebhookActionForm.tsx b/web/src/features/automations/components/actions/WebhookActionForm.tsx
index 1b4ceda2c9..3e4376309d 100644
--- a/web/src/features/automations/components/actions/WebhookActionForm.tsx
+++ b/web/src/features/automations/components/actions/WebhookActionForm.tsx
@@ -15,7 +15,7 @@ import {
SelectTrigger,
SelectValue,
} from "@/src/components/ui/select";
-import { X, Plus, RefreshCw } from "lucide-react";
+import { X, Plus, RefreshCw, Lock, LockOpen } from "lucide-react";
import { useFieldArray, type UseFormReturn } from "react-hook-form";
import { z } from "zod/v4";
import {
@@ -60,6 +60,9 @@ export const webhookSchema = z.object({
},
),
value: z.string(),
+ displayValue: z.string(),
+ isSecret: z.boolean(),
+ wasSecret: z.boolean(),
}),
),
apiVersion: AvailableWebhookApiSchema,
@@ -100,7 +103,19 @@ export const WebhookActionForm: React.FC<WebhookActionFormProps> = ({
// Function to add a new header pair
const addHeader = () => {
- appendHeader({ name: "", value: "" });
+ appendHeader({
+ name: "",
+ value: "",
+ displayValue: "",
+ isSecret: false,
+ wasSecret: false,
+ });
+ };
+
+ // Function to toggle secret status of a header
+ const toggleHeaderSecret = (index: number) => {
+ const currentValue = form.watch(`webhook.headers.${index}.isSecret`);
+ form.setValue(`webhook.headers.${index}.isSecret`, !currentValue);
};
return (
@@ -171,7 +186,10 @@ export const WebhookActionForm: React.FC<WebhookActionFormProps> = ({
...WebhookDefaultHeaders,
"x-langfuse-signature": `t=<timestamp>,v1=<signature>`,
}).map(([key, value]) => (
- <div key={key} className="mb-2 grid grid-cols-[1fr,1fr,auto] gap-2">
+ <div
+ key={key}
+ className="mb-2 grid grid-cols-[1fr,1fr,auto,auto] gap-2"
+ >
<FormItem>
<FormControl>
<Input value={key} disabled={true} className="bg-muted/50" />
@@ -186,8 +204,6 @@ export const WebhookActionForm: React.FC<WebhookActionFormProps> = ({
/>
</FormControl>
</FormItem>
- <div className="w-10" />{" "}
- {/* Spacer to align with editable headers */}
</div>
))}
</div>
@@ -202,10 +218,17 @@ export const WebhookActionForm: React.FC<WebhookActionFormProps> = ({
const originalIndex = headerFields.findIndex(
(f) => f.id === field.id,
);
+ const isSecret = form.watch(
+ `webhook.headers.${originalIndex}.isSecret`,
+ );
+ const displayValue = form.watch(
+ `webhook.headers.${originalIndex}.displayValue`,
+ );
+
return (
<div
key={field.id}
- className="mb-2 grid grid-cols-[1fr,1fr,auto] gap-2"
+ className="mb-2 grid grid-cols-[1fr,1fr,auto,auto] gap-2"
>
<FormField
control={form.control}
@@ -230,15 +253,34 @@ export const WebhookActionForm: React.FC<WebhookActionFormProps> = ({
<FormItem>
<FormControl>
<Input
- placeholder="Value"
+ placeholder={
+ isSecret && displayValue
+ ? displayValue
+ : displayValue || "Value"
+ }
{...field}
disabled={disabled}
+ type={isSecret ? "password" : "text"}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={() => toggleHeaderSecret(originalIndex)}
+ disabled={disabled}
+ title={isSecret ? "Make header public" : "Make header secret"}
+ >
+ {isSecret ? (
+ <Lock className="h-4 w-4 text-orange-500" />
+ ) : (
+ <LockOpen className="h-4 w-4 text-muted-foreground" />
+ )}
+ </Button>
<Button
type="button"
variant="ghost"
@@ -425,19 +467,28 @@ export const RegenerateWebhookSecretButton = ({
// Function to convert the array of header objects to a Record for API
export const formatWebhookHeaders = (
- headers: { name: string; value: string }[],
-): Record<string, string> => {
- const headersObject: Record<string, string> = {};
+ headers: {
+ name: string;
+ value: string;
+ displayValue: string;
+ isSecret: boolean;
+ wasSecret: boolean;
+ }[],
+): Record<string, { secret: boolean; value: string }> => {
+ const requestHeaders: Record<string, { secret: boolean; value: string }> = {};
const defaultHeaderKeys = Object.keys(WebhookDefaultHeaders);
headers.forEach((header) => {
- if (header.name.trim() && header.value.trim()) {
+ if (header.name.trim()) {
// Exclude default headers - they will be added automatically by the API
if (!defaultHeaderKeys.includes(header.name.trim().toLowerCase())) {
- headersObject[header.name.trim()] = header.value.trim();
+ requestHeaders[header.name.trim()] = {
+ secret: header.isSecret || false,
+ value: header.value.trim(),
+ };
}
}
});
- return headersObject;
+ return requestHeaders;
};
diff --git a/web/src/features/automations/components/actions/WebhookActionHandler.tsx b/web/src/features/automations/components/actions/WebhookActionHandler.tsx
index 992ffeee9b..f7ad1d921b 100644
--- a/web/src/features/automations/components/actions/WebhookActionHandler.tsx
+++ b/web/src/features/automations/components/actions/WebhookActionHandler.tsx
@@ -6,7 +6,7 @@ import {
type AutomationDomain,
AvailableWebhookApiSchema,
WebhookDefaultHeaders,
- type SafeWebhookActionConfig,
+ type ActionCreate,
type ActionDomain,
} from "@langfuse/shared";
import { z } from "zod/v4";
@@ -20,6 +20,9 @@ const WebhookActionFormSchema = z.object({
z.object({
name: z.string(),
value: z.string(),
+ displayValue: z.string(),
+ isSecret: z.boolean(),
+ wasSecret: z.boolean(),
}),
)
.default([]),
@@ -33,6 +36,9 @@ type WebhookActionFormData = z.infer<typeof WebhookActionFormSchema>;
type HeaderPair = {
name: string;
value: string;
+ displayValue: string;
+ isSecret: boolean;
+ wasSecret: boolean;
};
export class WebhookActionHandler
@@ -45,14 +51,18 @@ export class WebhookActionHandler
if (
automation?.action?.type === "WEBHOOK" &&
automation?.action?.config &&
- "headers" in automation.action.config &&
- automation.action.config.headers
+ "displayHeaders" in automation.action.config &&
+ automation.action.config.displayHeaders
) {
try {
- const headersObject = automation.action.config.headers;
- return Object.entries(headersObject).map(([name, value]) => ({
+ const displayHeaders = automation.action.config.displayHeaders;
+
+ return Object.entries(displayHeaders).map(([name, headerObj]) => ({
name,
- value: value as string,
+ value: headerObj.secret ? "" : headerObj.value,
+ displayValue: headerObj.value,
+ isSecret: headerObj.secret,
+ wasSecret: headerObj.secret,
}));
} catch (e) {
console.error("Failed to parse headers:", e);
@@ -108,9 +118,14 @@ export class WebhookActionHandler
if (!header.name.trim()) {
errors.push(`Header ${index + 1}: Name cannot be empty`);
}
- if (!header.value.trim()) {
+ if (!header.value.trim() && !header.isSecret) {
errors.push(`Header ${index + 1}: Value cannot be empty`);
}
+ if (header.wasSecret !== header.isSecret && !header.value.trim()) {
+ errors.push(
+ `Header ${index + 1}: A value must be provided when making a header ${header.wasSecret ? "public" : "secret"}`,
+ );
+ }
// Check if header name conflicts with default headers
if (
@@ -123,6 +138,19 @@ export class WebhookActionHandler
}
}
});
+
+ // check if header name is already in the form
+ // Check for duplicate header names (case-insensitive)
+ const headerNames = formData.webhook.headers
+ .filter((h) => h.name.trim()) // Only check non-empty header names
+ .map((h) => h.name.trim().toLowerCase());
+
+ const uniqueHeaderNames = new Set(headerNames);
+ if (uniqueHeaderNames.size < headerNames.length) {
+ errors.push(
+ "Duplicate header names are not allowed (case-insensitive)",
+ );
+ }
}
return {
@@ -131,11 +159,9 @@ export class WebhookActionHandler
};
}
- buildActionConfig(
- formData: WebhookActionFormData,
- ): Omit<SafeWebhookActionConfig, "displaySecretKey"> {
- // Convert headers array to object
- let headersObject: Record<string, string> = {};
+ buildActionConfig(formData: WebhookActionFormData): ActionCreate {
+ // Convert headers array to requestHeaders format
+ let headersObject: Record<string, { secret: boolean; value: string }> = {};
if (formData.webhook?.headers) {
headersObject = formatWebhookHeaders(formData.webhook.headers);
@@ -144,7 +170,7 @@ export class WebhookActionHandler
return {
type: "WEBHOOK",
url: formData.webhook?.url || "",
- headers: headersObject,
+ requestHeaders: headersObject,
apiVersion: formData.webhook?.apiVersion || { prompt: "v1" },
};
}
diff --git a/web/src/features/automations/server/router.ts b/web/src/features/automations/server/router.ts
index 78b17a608f..cfc20dc34f 100644
--- a/web/src/features/automations/server/router.ts
+++ b/web/src/features/automations/server/router.ts
@@ -2,10 +2,12 @@ import { createTRPCRouter } from "@/src/server/api/trpc";
import { protectedProjectProcedure } from "@/src/server/api/trpc";
import { z } from "zod/v4";
import {
+ type WebhookActionConfigWithSecrets,
ActionCreateSchema,
ActionType,
ActionTypeSchema,
JobConfigState,
+ singleFilter,
} from "@langfuse/shared";
import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { v4 } from "uuid";
@@ -17,7 +19,10 @@ import {
logger,
} from "@langfuse/shared/src/server";
import { generateWebhookSecret, encrypt } from "@langfuse/shared/encryption";
-import { processWebhookActionConfig } from "./webhookHelpers";
+import {
+ processWebhookActionConfig,
+ convertToSafeWebhookConfig,
+} from "./webhookHelpers";
import { TRPCError } from "@trpc/server";
import { auditLog } from "@/src/features/audit-logs/auditLog";
@@ -26,7 +31,7 @@ export const CreateAutomationInputSchema = z.object({
name: z.string().min(1, "Name is required"),
eventSource: z.string(),
eventAction: z.array(z.string()),
- filter: z.array(z.any()).nullable(),
+ filter: z.array(singleFilter).nullable(),
status: z.enum(JobConfigState).default(JobConfigState.ACTIVE),
// Action fields
actionType: z.enum(ActionType),
@@ -303,7 +308,12 @@ export const automationsRouter = createTRPCRouter({
logger.info(`Created automation ${trigger.id} for action ${action.id}`);
return {
- action,
+ action: {
+ ...action,
+ config: convertToSafeWebhookConfig(
+ action.config as WebhookActionConfigWithSecrets,
+ ),
+ },
trigger,
automation,
webhookSecret: newUnencryptedWebhookSecret, // Return webhook secret at top level for one-time display
@@ -408,7 +418,16 @@ export const automationsRouter = createTRPCRouter({
},
});
- return { action, trigger, automation };
+ return {
+ action: {
+ ...action,
+ config: convertToSafeWebhookConfig(
+ action.config as WebhookActionConfigWithSecrets,
+ ),
+ },
+ trigger,
+ automation,
+ };
}),
// Delete an automation (both trigger and action)
diff --git a/web/src/features/automations/server/webhookHelpers.ts b/web/src/features/automations/server/webhookHelpers.ts
index 5ef8b9db65..e9996bb650 100644
--- a/web/src/features/automations/server/webhookHelpers.ts
+++ b/web/src/features/automations/server/webhookHelpers.ts
@@ -3,8 +3,19 @@ import {
encrypt,
generateWebhookSecret,
} from "@langfuse/shared/encryption";
-import { type ActionCreate, type ActionConfig } from "@langfuse/shared";
-import { getActionByIdWithSecrets } from "@langfuse/shared/src/server";
+import {
+ type ActionCreate,
+ type ActionConfig,
+ type SafeWebhookActionConfig,
+ type WebhookActionConfigWithSecrets,
+} from "@langfuse/shared";
+import {
+ getActionByIdWithSecrets,
+ mergeHeaders,
+ createDisplayHeaders,
+ encryptSecretHeaders,
+} from "@langfuse/shared/src/server";
+import { TRPCError } from "@trpc/server";
interface WebhookConfigOptions {
actionConfig: ActionCreate;
@@ -14,9 +25,13 @@ interface WebhookConfigOptions {
/**
* Processes webhook action configuration by:
- * 1. Adding default headers
- * 2. Generating or preserving webhook secrets
- * 3. Encrypting secrets for storage
+ * 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
+ * 4. Encrypting secret headers based on secret flag
+ * 5. Generating display values for secret headers
+ * 6. Generating or preserving webhook secrets
+ * 7. Encrypting secrets for storage
*/
export async function processWebhookActionConfig({
actionConfig,
@@ -40,24 +55,110 @@ export async function processWebhookActionConfig({
const { secretKey: newSecretKey, displaySecretKey: newDisplaySecretKey } =
generateWebhookSecret();
- const finalActionConfig = {
- ...actionConfig,
- headers: {
- ...actionConfig.headers,
- },
- secretKey: existingAction?.config.secretKey ?? encrypt(newSecretKey),
- displaySecretKey:
- existingAction?.config.displaySecretKey ?? newDisplaySecretKey,
- };
+ // Process headers and generate final action config
+ const finalActionConfig = processWebhookHeaders(
+ actionConfig,
+ existingAction?.config as WebhookActionConfigWithSecrets | undefined,
+ );
return {
- finalActionConfig,
+ finalActionConfig: {
+ ...finalActionConfig,
+ secretKey: existingAction?.config.secretKey ?? encrypt(newSecretKey),
+ displaySecretKey:
+ existingAction?.config.displaySecretKey ?? newDisplaySecretKey,
+ },
newUnencryptedWebhookSecret: existingAction?.config.secretKey
? undefined
: newSecretKey,
};
}
+/**
+ * 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
+ * 4. Encrypting secret headers based on secret flag
+ * 5. Generating display values for secret headers
+ */
+function processWebhookHeaders(
+ actionConfig: ActionCreate,
+ existingConfig: WebhookActionConfigWithSecrets | undefined,
+): ActionConfig {
+ // Get existing headers for comparison
+ const existingLegacyHeaders = existingConfig?.headers ?? {}; // legacy headers
+ const existingRequestHeaders = existingConfig?.requestHeaders ?? {}; // new headers
+ const mergedExistingHeaders = mergeHeaders(
+ existingLegacyHeaders,
+ existingRequestHeaders,
+ );
+
+ // Process new headers from input
+ const inputRequestHeaders = actionConfig.requestHeaders || {};
+
+ // Start with empty headers - only include what's in the input
+ const finalRequestHeaders: Record<
+ string,
+ { 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
+ if (Object.keys(inputRequestHeaders).length === 0) {
+ for (const [key, headerObj] of Object.entries(mergedExistingHeaders)) {
+ finalRequestHeaders[key] = headerObj;
+ }
+ } else {
+ // Process each header from input
+ for (const [key, headerObj] of Object.entries(inputRequestHeaders)) {
+ const existingHeader = mergedExistingHeaders[key];
+
+ // Validate secret toggle: can only change secret status when providing a value
+ if (
+ headerObj.secret &&
+ headerObj.value.trim() === "" &&
+ !existingHeader
+ ) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Header "${key}" cannot be made secret without providing a value`,
+ });
+ }
+
+ // If changing secret status, ensure a value is provided
+ if (
+ existingHeader &&
+ headerObj.secret !== existingHeader.secret &&
+ headerObj.value.trim() === ""
+ ) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Header "${key}" secret status can only be changed when providing a value`,
+ });
+ }
+
+ // If value is empty, preserve existing value if it exists
+ if (headerObj.value.trim() === "" && existingHeader) {
+ finalRequestHeaders[key] = existingHeader;
+ } else if (headerObj.value.trim() !== "") {
+ // Only process non-empty values
+ finalRequestHeaders[key] = headerObj;
+ }
+ // If value is empty and no existing header, skip it (effectively removing it)
+ }
+ }
+
+ return {
+ ...actionConfig,
+ headers: {}, // remove legacy headers on write
+ requestHeaders: encryptSecretHeaders(finalRequestHeaders),
+ displayHeaders: createDisplayHeaders(finalRequestHeaders),
+ secretKey: "", // will be overwritten by the caller
+ displaySecretKey: "", // will be overwritten by the caller
+ };
+}
+
/**
* Extracts webhook secret for one-time display after creation
*/
@@ -75,3 +176,18 @@ export function extractWebhookSecret(
return undefined;
}
}
+
+/**
+ * Converts webhook config with secrets to safe config by only including allowed fields
+ */
+export function convertToSafeWebhookConfig(
+ webhookConfig: WebhookActionConfigWithSecrets,
+): SafeWebhookActionConfig {
+ return {
+ type: webhookConfig.type,
+ url: webhookConfig.url,
+ displayHeaders: webhookConfig.displayHeaders,
+ apiVersion: webhookConfig.apiVersion,
+ displaySecretKey: webhookConfig.displaySecretKey,
+ };
+}
diff --git a/worker/src/__tests__/webhooks.test.ts b/worker/src/__tests__/webhooks.test.ts
index ea23c36f51..88c7a13ff2 100644
--- a/worker/src/__tests__/webhooks.test.ts
+++ b/worker/src/__tests__/webhooks.test.ts
@@ -155,7 +155,7 @@ describe("Webhook Integration Tests", () => {
type: "WEBHOOK",
url: "https://webhook.example.com/test",
headers: {
- "Content-Type": "application/json",
+ "X-Custom-Header-2": "test-value-2",
"X-Custom-Header": "test-value",
},
apiVersion: { prompt: "v1" },
@@ -227,7 +227,7 @@ describe("Webhook Integration Tests", () => {
const request = requests[0];
expect(request.url).toBe("https://webhook.example.com/test");
expect(request.method).toBe("POST");
- expect(request.headers["content-type"]).toBe("application/json");
+ expect(request.headers["x-custom-header-2"]).toBe("test-value-2");
expect(request.headers["x-custom-header"]).toBe("test-value");
expect(request.headers["x-langfuse-signature"]).toMatch(
@@ -499,6 +499,430 @@ describe("Webhook Integration Tests", () => {
expect(trigger?.status).toBe(JobConfigState.INACTIVE);
});
+ it("should execute webhook with secret headers correctly", async () => {
+ // Get the full prompt for the payload
+ const fullPrompt = await prisma.prompt.findUnique({
+ where: { id: promptId },
+ });
+
+ // Update action config to include both public and secret headers
+ const action = await prisma.action.findUnique({
+ where: { id: actionId },
+ });
+
+ if (!action) {
+ throw new Error("Action not found");
+ }
+
+ const updatedConfig = {
+ ...(action.config as WebhookActionConfigWithSecrets),
+ requestHeaders: {
+ "x-public-header": { secret: false, value: "public-value" },
+ "x-secret-api-key": {
+ secret: true,
+ value: encrypt("secret-api-key-value"),
+ },
+ "x-secret-token": {
+ secret: true,
+ value: encrypt("bearer-token-value"),
+ },
+ },
+ displayHeaders: {
+ "x-secret-api-key": { secret: true, value: "secr...alue" },
+ "x-secret-token": { secret: true, value: "bear...alue" },
+ },
+ };
+
+ await prisma.action.update({
+ where: { id: actionId },
+ data: {
+ config: updatedConfig,
+ },
+ });
+
+ const webhookInput: WebhookInput = {
+ projectId,
+ automationId,
+ executionId,
+ payload: {
+ prompt: PromptDomainSchema.parse(fullPrompt),
+ action: "created",
+ type: "prompt-version",
+ },
+ };
+
+ await prisma.automationExecution.create({
+ data: {
+ id: executionId,
+ projectId,
+ triggerId,
+ automationId,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: webhookInput.executionId,
+ input: webhookInput,
+ },
+ });
+
+ await executeWebhook(webhookInput);
+
+ // Verify webhook request was made with decrypted secret headers
+ const requests = webhookServer.getReceivedRequests();
+ expect(requests).toHaveLength(1);
+
+ const request = requests[0];
+ expect(request.url).toBe("https://webhook.example.com/test");
+ expect(request.method).toBe("POST");
+
+ // Verify public header is present
+ expect(request.headers["x-public-header"]).toBe("public-value");
+
+ // Verify secret headers are present and decrypted
+ expect(request.headers["x-secret-api-key"]).toBe("secret-api-key-value");
+ expect(request.headers["x-secret-token"]).toBe("bearer-token-value");
+
+ // Verify signature is present
+ expect(request.headers["x-langfuse-signature"]).toMatch(
+ /^t=\d+,v1=[a-f0-9]+$/,
+ );
+
+ // Verify database execution record was updated
+ const execution = await prisma.automationExecution.findUnique({
+ where: { id: executionId },
+ });
+ expect(execution?.status).toBe(ActionExecutionStatus.COMPLETED);
+ });
+
+ it("should handle webhook with only secret headers", async () => {
+ // Get the full prompt for the payload
+ const fullPrompt = await prisma.prompt.findUnique({
+ where: { id: promptId },
+ });
+
+ // Update action config to include only secret headers
+ const action = await prisma.action.findUnique({
+ where: { id: actionId },
+ });
+
+ if (!action) {
+ throw new Error("Action not found");
+ }
+
+ const updatedConfig = {
+ ...(action.config as WebhookActionConfigWithSecrets),
+ requestHeaders: {
+ authorization: {
+ secret: true,
+ value: encrypt("Bearer secret-token-12345"),
+ },
+ "x-api-key": { secret: true, value: encrypt("api-key-67890") },
+ },
+ displayHeaders: {
+ authorization: { secret: true, value: "Bear***12345" },
+ "x-api-key": { secret: true, value: "api-***67890" },
+ },
+ };
+
+ await prisma.action.update({
+ where: { id: actionId },
+ data: {
+ config: updatedConfig,
+ },
+ });
+
+ const newExecutionId = v4();
+ const webhookInput: WebhookInput = {
+ projectId,
+ automationId,
+ executionId: newExecutionId,
+ payload: {
+ prompt: PromptDomainSchema.parse(fullPrompt),
+ action: "created",
+ type: "prompt-version",
+ },
+ };
+
+ await prisma.automationExecution.create({
+ data: {
+ id: newExecutionId,
+ projectId,
+ triggerId,
+ automationId,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: webhookInput.executionId,
+ input: webhookInput,
+ },
+ });
+
+ await executeWebhook(webhookInput);
+
+ // Verify webhook request was made with decrypted secret headers
+ const requests = webhookServer.getReceivedRequests();
+ expect(requests).toHaveLength(1); // This test only
+
+ const request = requests[0]; // Get the request
+ expect(request.url).toBe("https://webhook.example.com/test");
+
+ // Verify secret headers are present and decrypted
+ expect(request.headers["authorization"]).toBe(
+ "Bearer secret-token-12345",
+ );
+ expect(request.headers["x-api-key"]).toBe("api-key-67890");
+
+ // Verify database execution record was updated
+ const execution = await prisma.automationExecution.findUnique({
+ where: { id: newExecutionId },
+ });
+ expect(execution?.status).toBe(ActionExecutionStatus.COMPLETED);
+ });
+
+ it("should handle webhook with only legacy public headers", async () => {
+ // Get the full prompt for the payload
+ const fullPrompt = await prisma.prompt.findUnique({
+ where: { id: promptId },
+ });
+
+ // Update action config to include only public headers
+ const action = await prisma.action.findUnique({
+ where: { id: actionId },
+ });
+
+ if (!action) {
+ throw new Error("Action not found");
+ }
+
+ const updatedConfig = {
+ ...(action.config as WebhookActionConfigWithSecrets),
+ headers: {
+ "x-public-header-1": "public-value-1",
+ "x-public-header-2": "public-value-2",
+ },
+ secretHeaderKeys: [], // No secret headers
+ displayHeaders: {},
+ };
+
+ await prisma.action.update({
+ where: { id: actionId },
+ data: {
+ config: updatedConfig,
+ },
+ });
+
+ const newExecutionId = v4();
+ const webhookInput: WebhookInput = {
+ projectId,
+ automationId,
+ executionId: newExecutionId,
+ payload: {
+ prompt: PromptDomainSchema.parse(fullPrompt),
+ action: "created",
+ type: "prompt-version",
+ },
+ };
+
+ await prisma.automationExecution.create({
+ data: {
+ id: newExecutionId,
+ projectId,
+ triggerId,
+ automationId,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: webhookInput.executionId,
+ input: webhookInput,
+ },
+ });
+
+ await executeWebhook(webhookInput);
+
+ // Verify webhook request was made with public headers
+ const requests = webhookServer.getReceivedRequests();
+ expect(requests).toHaveLength(1); // This test only
+
+ const request = requests[0]; // Get the request
+ expect(request.url).toBe("https://webhook.example.com/test");
+
+ // Verify public headers are present
+ expect(request.headers["x-public-header-1"]).toBe("public-value-1");
+ expect(request.headers["x-public-header-2"]).toBe("public-value-2");
+
+ // Verify database execution record was updated
+ const execution = await prisma.automationExecution.findUnique({
+ where: { id: newExecutionId },
+ });
+ expect(execution?.status).toBe(ActionExecutionStatus.COMPLETED);
+ });
+
+ it("should handle webhook with legacy public headers + new public and secret headers", async () => {
+ // Get the full prompt for the payload
+ const fullPrompt = await prisma.prompt.findUnique({
+ where: { id: promptId },
+ });
+
+ // Update action config to include only public headers
+ const action = await prisma.action.findUnique({
+ where: { id: actionId },
+ });
+
+ if (!action) {
+ throw new Error("Action not found");
+ }
+
+ const updatedConfig = {
+ ...(action.config as WebhookActionConfigWithSecrets),
+ headers: {
+ "x-public-header-1": "public-value-1",
+ "x-public-header-2": "public-value-2",
+ },
+ requestHeaders: {
+ "x-public-header-3": { secret: false, value: "public-value-3" },
+ "x-secret-header-4": {
+ secret: true,
+ value: encrypt("secret-value-4"),
+ },
+ "x-public-header-1": { secret: false, value: "public-value-5" },
+ },
+ displayHeaders: {},
+ };
+
+ await prisma.action.update({
+ where: { id: actionId },
+ data: {
+ config: updatedConfig,
+ },
+ });
+
+ const newExecutionId = v4();
+ const webhookInput: WebhookInput = {
+ projectId,
+ automationId,
+ executionId: newExecutionId,
+ payload: {
+ prompt: PromptDomainSchema.parse(fullPrompt),
+ action: "created",
+ type: "prompt-version",
+ },
+ };
+
+ await prisma.automationExecution.create({
+ data: {
+ id: newExecutionId,
+ projectId,
+ triggerId,
+ automationId,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: webhookInput.executionId,
+ input: webhookInput,
+ },
+ });
+
+ await executeWebhook(webhookInput);
+
+ // Verify webhook request was made with public headers
+ const requests = webhookServer.getReceivedRequests();
+ expect(requests).toHaveLength(1); // This test only
+
+ const request = requests[0]; // Get the request
+ expect(request.url).toBe("https://webhook.example.com/test");
+
+ // Verify public headers are present
+ expect(request.headers["x-public-header-1"]).toBe("public-value-5");
+ expect(request.headers["x-public-header-2"]).toBe("public-value-2");
+ expect(request.headers["x-public-header-3"]).toBe("public-value-3");
+ expect(request.headers["x-secret-header-4"]).toBe("secret-value-4");
+
+ // Verify database execution record was updated
+ const execution = await prisma.automationExecution.findUnique({
+ where: { id: newExecutionId },
+ });
+ expect(execution?.status).toBe(ActionExecutionStatus.COMPLETED);
+ });
+
+ it("should handle decryption failure gracefully", async () => {
+ // Get the full prompt for the payload
+ const fullPrompt = await prisma.prompt.findUnique({
+ where: { id: promptId },
+ });
+
+ // Update action config with invalid encrypted header
+ const action = await prisma.action.findUnique({
+ where: { id: actionId },
+ });
+
+ if (!action) {
+ throw new Error("Action not found");
+ }
+
+ const updatedConfig = {
+ ...(action.config as WebhookActionConfigWithSecrets),
+ requestHeaders: {
+ "x-valid-header": { secret: false, value: "valid-public-value" },
+ "x-invalid-secret": {
+ secret: true,
+ value: "invalid-encrypted-value", // This is not properly encrypted
+ },
+ },
+ displayHeaders: {
+ "x-invalid-secret": { secret: true, value: "inva...alue" },
+ },
+ };
+
+ await prisma.action.update({
+ where: { id: actionId },
+ data: {
+ config: updatedConfig,
+ },
+ });
+
+ const newExecutionId = v4();
+ const webhookInput: WebhookInput = {
+ projectId,
+ automationId,
+ executionId: newExecutionId,
+ payload: {
+ prompt: PromptDomainSchema.parse(fullPrompt),
+ action: "created",
+ type: "prompt-version",
+ },
+ };
+
+ await prisma.automationExecution.create({
+ data: {
+ id: newExecutionId,
+ projectId,
+ triggerId,
+ automationId,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: webhookInput.executionId,
+ input: webhookInput,
+ },
+ });
+
+ await executeWebhook(webhookInput);
+
+ // Verify webhook request was made with valid headers only
+ const requests = webhookServer.getReceivedRequests();
+ expect(requests).toHaveLength(1); // This test only
+
+ const request = requests[0]; // Get the request
+ expect(request.url).toBe("https://webhook.example.com/test");
+
+ // Verify valid header is present
+ expect(request.headers["x-valid-header"]).toBe("valid-public-value");
+
+ // Verify invalid secret header is not present (skipped due to decryption failure)
+ expect(request.headers["x-invalid-secret"]).toBeUndefined();
+
+ // Verify database execution record was updated (should still succeed)
+ const execution = await prisma.automationExecution.findUnique({
+ where: { id: newExecutionId },
+ });
+ expect(execution?.status).toBe(ActionExecutionStatus.COMPLETED);
+ });
+
it("should handle missing automation gracefully without throwing error", async () => {
const fullPrompt = await prisma.prompt.findUnique({
where: { id: promptId },
diff --git a/worker/src/queues/webhooks.ts b/worker/src/queues/webhooks.ts
index 48dfabc7a6..dc367c2a46 100644
--- a/worker/src/queues/webhooks.ts
+++ b/worker/src/queues/webhooks.ts
@@ -94,10 +94,17 @@ export const executeWebhook = async (input: WebhookInput) => {
});
// Prepare headers with signature if secret exists
- const requestHeaders: Record<string, string> = {
- ...WebhookDefaultHeaders,
- ...webhookConfig.headers,
- };
+ const requestHeaders: Record<string, string> = {};
+
+ // Add webhook config headers first
+ for (const [key, value] of Object.entries(webhookConfig.requestHeaders)) {
+ requestHeaders[key] = value.value;
+ }
+
+ // Add default headers with precedence
+ for (const [key, value] of Object.entries(WebhookDefaultHeaders)) {
+ requestHeaders[key] = value;
+ }
if (!webhookConfig.secretKey) {
logger.warn(