Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
add custom webhook headers option
Thiago Araujo da Silva37dcb7ac61d7
diff --git a/backend/e2e-test/routes/v1/alerts.spec.ts b/backend/e2e-test/routes/v1/alerts.spec.tsindex 718acde1be..7476784b74 100644--- a/backend/e2e-test/routes/v1/alerts.spec.ts+++ b/backend/e2e-test/routes/v1/alerts.spec.ts@@ -86,6 +86,65 @@ describe("Alerts API", () => {expect(await testDb("alert_channels").where({ id: webhook.id })).toHaveLength(0);});+ test("webhook header values are returned redacted, and sending one back redacted keeps it", async () => {+ const alert = await createAlert({+ body: identityAlert({+ name: "headers",+ channels: [+ {+ ...webhookChannel,+ config: { url: "https://example.com/hook", headers: [{ key: "Authorization", value: "Bearer abc" }] }+ }+ ]+ }),+ authToken+ });+ const [webhook] = alert.channels;+ expect(webhook.config.headers).toEqual([{ key: "Authorization", value: "******" }]);++ const updated = await updateAlert({+ alertId: alert.id,+ authToken,+ body: {+ channels: [+ {+ id: webhook.id,+ name: webhook.name,+ channelType: "webhook",+ config: {+ url: "https://example.com/hook",+ headers: [+ { key: "Authorization", value: "******" },+ { key: "X-Env", value: "prod" }+ ]+ }+ }+ ]+ }+ });+ expect(updated.channels[0].config.headers).toEqual([+ { key: "Authorization", value: "******" },+ { key: "X-Env", value: "******" }+ ]);++ const res = await updateAlert({+ alertId: alert.id,+ authToken,+ body: {+ channels: [+ {+ id: webhook.id,+ name: webhook.name,+ channelType: "webhook",+ config: { url: "https://example.com/hook", headers: [{ key: "X-New", value: "******" }] }+ }+ ]+ }+ }).raw();+ expect(res.statusCode).toBe(400);+ expect(res.json().message).toContain("Header 'X-New' has no saved value to keep");+ });+test("updating with another alert's channel id is refused", async () => {const first = await createAlert({ body: identityAlert({ name: "first" }), authToken });const second = await createAlert({ body: identityAlert({ name: "second", projectId }), authToken });diff --git a/backend/e2e-test/testUtils/alerts.ts b/backend/e2e-test/testUtils/alerts.tsindex cca63b15db..3af5e8a4d8 100644--- a/backend/e2e-test/testUtils/alerts.ts+++ b/backend/e2e-test/testUtils/alerts.ts@@ -11,6 +11,7 @@ type TAlertRecord = {name: string;channelType: string;enabled: boolean;+ config: Record<string, unknown>;recipients: { principalType: string; principalId: string }[];}[];};diff --git a/backend/src/services/alert/alert-channel-config-fns.ts b/backend/src/services/alert/alert-channel-config-fns.tsindex cb65fbcc79..e23f3f1888 100644--- a/backend/src/services/alert/alert-channel-config-fns.ts+++ b/backend/src/services/alert/alert-channel-config-fns.ts@@ -43,5 +43,5 @@ export const mergeChannelConfigWithStored = (const value = incomingConfig[field];if (value === "" || value === null || value === undefined) delete merged[field];});- return merged;+ return definition.restoreRedactedConfig ? definition.restoreRedactedConfig(merged, existingConfig) : merged;};diff --git a/backend/src/services/alert/alert-channel-service.test.ts b/backend/src/services/alert/alert-channel-service.test.tsindex 82c892d6d1..2a7d762175 100644--- a/backend/src/services/alert/alert-channel-service.test.ts+++ b/backend/src/services/alert/alert-channel-service.test.ts@@ -1,7 +1,7 @@import { Knex } from "knex";import { alertChannelServiceFactory, TAlertChannelServiceFactoryDep } from "./alert-channel-service";-import { AlertChannelType } from "./alert-channel-types";+import { ALERT_CHANNEL_REDACTED_VALUE, AlertChannelType } from "./alert-channel-types";import { AlertPrincipalType } from "./alert-types";// Identity cipher: encryptedConfig is just JSON bytes of the config.@@ -153,6 +153,91 @@ describe("alert channel service", () => {expect(detail.recipients).toEqual([]);});+ test("returns webhook header names with their values redacted", async () => {+ const { service } = buildService();+ const channel = await createChannel(+ service,+ {+ name: "Ops webhook",+ channelType: AlertChannelType.WEBHOOK,+ config: { url: "https://example.com/hook", headers: [{ key: "Authorization", value: "Bearer abc" }] },+ orgId: "org-1",+ ...CHANNEL_INPUT+ },+ encryptor as never,+ tx+ );++ const [detail] = await service.getDetailsForChannels([channel], { decryptor: decryptor as never });+ expect(detail.config).toEqual({+ url: "https://example.com/hook",+ hasSigningSecret: false,+ headers: [{ key: "Authorization", value: ALERT_CHANNEL_REDACTED_VALUE }]+ });+ });++ test("keeps a webhook header whose value is sent back redacted and replaces the others", async () => {+ const { service, store } = buildService();+ const channel = seedRow({+ id: "ch-1",+ channelType: AlertChannelType.WEBHOOK,+ encryptedConfig: encConfig({+ url: "https://example.com/hook",+ headers: [+ { key: "Authorization", value: "Bearer abc" },+ { key: "X-Env", value: "prod" }+ ]+ })+ });++ await updateChannel(+ service,+ {+ recipientScope: RECIPIENT_SCOPE,+ channelId: "ch-1",+ config: {+ url: "https://example.com/hook",+ headers: [+ { key: "Authorization", value: ALERT_CHANNEL_REDACTED_VALUE },+ { key: "X-Env", value: "staging" }+ ]+ }+ },+ channel as never,+ cipher,+ tx+ );++ const stored = JSON.parse(store.get("ch-1")!.encryptedConfig.toString()) as Record<string, unknown>;+ expect(stored.headers).toEqual([+ { key: "Authorization", value: "Bearer abc" },+ { key: "X-Env", value: "staging" }+ ]);+ });++ test("rejects a redacted webhook header that has no stored value", async () => {+ const { service } = buildService();+ const channel = seedRow({+ id: "ch-1",+ channelType: AlertChannelType.WEBHOOK,+ encryptedConfig: encConfig({ url: "https://example.com/hook" })+ });++ await expect(+ updateChannel(+ service,+ {+ recipientScope: RECIPIENT_SCOPE,+ channelId: "ch-1",+ config: { url: "https://example.com/hook", headers: [{ key: "X-New", value: ALERT_CHANNEL_REDACTED_VALUE }] }+ },+ channel as never,+ cipher,+ tx+ )+ ).rejects.toThrow("Header 'X-New' has no saved value to keep. Enter a value for it");+ });+test("requires recipients for a directed (email) channel and rejects them for others", async () => {const { service } = buildService();await expect(diff --git a/backend/src/services/alert/alert-channel-service.ts b/backend/src/services/alert/alert-channel-service.tsindex e0636e7588..b13a2316a6 100644--- a/backend/src/services/alert/alert-channel-service.ts+++ b/backend/src/services/alert/alert-channel-service.ts@@ -201,7 +201,7 @@ export const alertChannelServiceFactory = ({definition.secretFields.forEach((field) => {redacted[`has${capitalize(field)}`] = Boolean(config[field]);});- return redacted;+ return definition.redactConfig ? definition.redactConfig(redacted) : redacted;};const prepareChannelCreate = async (diff --git a/backend/src/services/alert/alert-channel-types.ts b/backend/src/services/alert/alert-channel-types.tsindex af63499558..3aa8d42cc3 100644--- a/backend/src/services/alert/alert-channel-types.ts+++ b/backend/src/services/alert/alert-channel-types.ts@@ -1,3 +1,4 @@+import RE2 from "re2";import { z } from "zod";import { PAGERDUTY_INTEGRATION_KEY_ERROR, pagerDutyIntegrationKeyRegex } from "@app/lib/pagerduty/integration-key";@@ -5,6 +6,8 @@ import { TSmtpService } from "@app/services/smtp/smtp-service";export const ALERT_CHANNEL_HTTP_TIMEOUT = 7 * 1000;+export const ALERT_CHANNEL_REDACTED_VALUE = "******";+export enum AlertChannelType {EMAIL = "email",SLACK = "slack",@@ -79,18 +82,72 @@ export type TAlertChannelDefinition = {secretFields: string[];configSchema: z.ZodTypeAny;maxTargetsPerRun?: number;+ redactConfig?: (config: Record<string, unknown>) => Record<string, unknown>;+ restoreRedactedConfig?: (+ incomingConfig: Record<string, unknown>,+ storedConfig: Record<string, unknown>+ ) => Record<string, unknown>;send: (ctx: TAlertChannelSendContext) => Promise<TChannelResult>;};export const EmailChannelConfigSchema = z.object({}).strip();+export const WEBHOOK_MAX_HEADERS = 20;++const WEBHOOK_RESERVED_HEADERS = ["content-type", "x-infisical-signature"];++const httpHeaderNameRegex = new RE2("^[A-Za-z0-9!#$%&'*+.^_`|~-]+$");+const noLineBreaksRegex = new RE2("^[^\\r\\n]*$");++export const WebhookChannelHeaderSchema = z+ .object({+ key: z+ .string()+ .trim()+ .min(1, "Header names cannot be empty")+ .max(128, "Header names cannot be longer than 128 characters")+ .refine(+ (key) => httpHeaderNameRegex.test(key),+ "Header names can only contain letters, digits, and -_.!#$%&'*+^`|~"+ )+ .refine(+ (key) => !WEBHOOK_RESERVED_HEADERS.includes(key.toLowerCase()),+ (key) => ({ message: `Header '${key}' is set by Infisical and cannot be overridden` })+ ),+ value: z+ .string()+ .min(1, "Header values cannot be empty")+ .max(4096, "Header values cannot be longer than 4096 characters")+ .refine((value) => noLineBreaksRegex.test(value), "Header values cannot contain line breaks")+ })+ .refine(+ (header) => header.value !== ALERT_CHANNEL_REDACTED_VALUE,+ (header) => ({+ message: `Header '${header.key}' has no saved value to keep. Enter a value for it`,+ path: ["value"]+ })+ );++export type TWebhookChannelHeader = z.infer<typeof WebhookChannelHeaderSchema>;+export const WebhookChannelConfigSchema = z.object({url: z.string().max(2048).url().refine((url) => url.startsWith("https://"), "Webhook URL must use HTTPS"),- signingSecret: z.string().max(256).optional().nullable()+ signingSecret: z.string().max(256).optional().nullable(),+ headers: z+ .array(WebhookChannelHeaderSchema)+ .max(WEBHOOK_MAX_HEADERS, `A webhook channel can have at most ${WEBHOOK_MAX_HEADERS} headers`)+ .optional()+ .refine(+ (headers) => {+ const names = (headers ?? []).map((header) => header.key.toLowerCase());+ return new Set(names).size === names.length;+ },+ { message: "Header names must be unique" }+ )});export const SlackChannelConfigSchema = z.object({diff --git a/backend/src/services/alert/channels/alert-channel-registry.ts b/backend/src/services/alert/channels/alert-channel-registry.tsindex a2754d5cf5..22a02a67c7 100644--- a/backend/src/services/alert/channels/alert-channel-registry.ts+++ b/backend/src/services/alert/channels/alert-channel-registry.ts@@ -9,7 +9,11 @@ import {import { sendEmailNotification } from "./alert-channel-email-fns";import { PAGERDUTY_MAX_INCIDENTS_PER_RUN, sendPagerDutyNotification } from "./alert-channel-pagerduty-fns";import { sendSlackNotification } from "./alert-channel-slack-fns";-import { sendWebhookNotification } from "./alert-channel-webhook-fns";+import {+ redactWebhookHeaders,+ restoreRedactedWebhookHeaders,+ sendWebhookNotification+} from "./alert-channel-webhook-fns";export const ALERT_CHANNEL_REGISTRY: Record<AlertChannelType, TAlertChannelDefinition> = {[AlertChannelType.EMAIL]: {@@ -31,6 +35,8 @@ export const ALERT_CHANNEL_REGISTRY: Record<AlertChannelType, TAlertChannelDefindirected: false,secretFields: ["signingSecret"],configSchema: WebhookChannelConfigSchema,+ redactConfig: redactWebhookHeaders,+ restoreRedactedConfig: restoreRedactedWebhookHeaders,send: sendWebhookNotification},[AlertChannelType.PAGERDUTY]: {diff --git a/backend/src/services/alert/channels/alert-channel-webhook-fns.ts b/backend/src/services/alert/channels/alert-channel-webhook-fns.tsindex d922ddebc4..56bdb9798e 100644--- a/backend/src/services/alert/channels/alert-channel-webhook-fns.ts+++ b/backend/src/services/alert/channels/alert-channel-webhook-fns.ts@@ -4,9 +4,11 @@ import { safeRequest } from "@app/lib/validator";import {ALERT_CHANNEL_HTTP_TIMEOUT,+ ALERT_CHANNEL_REDACTED_VALUE,TAlertChannelSendContext,TAlertPayload,TChannelResult,+ TWebhookChannelHeader,WebhookChannelConfigSchema} from "../alert-channel-types";@@ -53,6 +55,46 @@ export const buildWebhookPayload = (payload: TAlertPayload): TAlertWebhookPayloa}});+// Header lists arrive unvalidated on the update path, so only well-formed entries are looked at.+const isWebhookHeader = (header: unknown): header is TWebhookChannelHeader =>+ typeof header === "object" &&+ header !== null &&+ typeof (header as TWebhookChannelHeader).key === "string" &&+ typeof (header as TWebhookChannelHeader).value === "string";++export const redactWebhookHeaders = (config: Record<string, unknown>): Record<string, unknown> => {+ if (!Array.isArray(config.headers)) return config;+ return {+ ...config,+ headers: config.headers.map((header: unknown) =>+ isWebhookHeader(header) ? { key: header.key, value: ALERT_CHANNEL_REDACTED_VALUE } : header+ )+ };+};++export const restoreRedactedWebhookHeaders = (+ incomingConfig: Record<string, unknown>,+ storedConfig: Record<string, unknown>+): Record<string, unknown> => {+ if (!Array.isArray(incomingConfig.headers)) return incomingConfig;++ const storedValues = new Map<string, string>();+ if (Array.isArray(storedConfig.headers)) {+ storedConfig.headers.forEach((header: unknown) => {+ if (isWebhookHeader(header)) storedValues.set(header.key.toLowerCase(), header.value);+ });+ }++ return {+ ...incomingConfig,+ headers: incomingConfig.headers.map((header: unknown) => {+ if (!isWebhookHeader(header) || header.value !== ALERT_CHANNEL_REDACTED_VALUE) return header;+ const storedValue = storedValues.get(header.key.trim().toLowerCase());+ return storedValue === undefined ? header : { ...header, value: storedValue };+ })+ };+};+const generateHmacSignature = (data: string, secret: string): string =>crypto.createHmac("sha256", secret).update(data).digest("hex");@@ -60,9 +102,14 @@ const triggerWebhook = async (params: {url: string;payload: TAlertWebhookPayload;signingSecret?: string | null;+ customHeaders?: TWebhookChannelHeader[];}): Promise<void> => {- const { url, payload, signingSecret } = params;- const headers: Record<string, string> = { "Content-Type": "application/json" };+ const { url, payload, signingSecret, customHeaders } = params;+ const headers: Record<string, string> = {};+ customHeaders?.forEach(({ key, value }) => {+ headers[key] = value;+ });+ headers["Content-Type"] = "application/json";if (signingSecret) {const payloadString = JSON.stringify(payload);@@ -82,6 +129,11 @@ export const sendWebhookNotification = async (ctx: TAlertChannelSendContext): Prconst config = WebhookChannelConfigSchema.parse(ctx.config);const payload = buildWebhookPayload(ctx.payload);- await triggerWebhook({ url: config.url, payload, signingSecret: config.signingSecret });+ await triggerWebhook({+ url: config.url,+ payload,+ signingSecret: config.signingSecret,+ customHeaders: config.headers+ });return { success: true };};diff --git a/backend/src/services/alert/channels/alert-channels.test.ts b/backend/src/services/alert/channels/alert-channels.test.tsindex 60e9269abe..b4cfe1374b 100644--- a/backend/src/services/alert/channels/alert-channels.test.ts+++ b/backend/src/services/alert/channels/alert-channels.test.ts@@ -1,14 +1,23 @@+import { safeRequest } from "@app/lib/validator";+import {+ ALERT_CHANNEL_REDACTED_VALUE,AlertChannelType,DIRECTED_ALERT_CHANNEL_TYPES,SlackChannelConfigSchema,- TAlertPayload+ TAlertPayload,+ WebhookChannelConfigSchema} from "../alert-channel-types";import { sendEmailNotification } from "./alert-channel-email-fns";import { buildPagerDutyEvent } from "./alert-channel-pagerduty-fns";import { ALERT_CHANNEL_REGISTRY } from "./alert-channel-registry";import { buildSlackPayload } from "./alert-channel-slack-fns";-import { buildWebhookPayload } from "./alert-channel-webhook-fns";+import {+ buildWebhookPayload,+ redactWebhookHeaders,+ restoreRedactedWebhookHeaders,+ sendWebhookNotification+} from "./alert-channel-webhook-fns";// logger is `export let logger` assigned by initLogger(), which unit tests don't run, so the// delivery-failure path (which logs) would otherwise dereference undefined. Mock it per-file.@@ -17,6 +26,11 @@ vi.mock("@app/lib/logger", () => ({initLogger: () => {}}));+vi.mock("@app/lib/validator", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@app/lib/validator")>()),+ safeRequest: { post: vi.fn(async () => ({ status: 200, data: {} })) }+}));+const samplePayload = (): TAlertPayload => ({alert: {id: "alert-1",@@ -208,6 +222,121 @@ describe("buildPagerDutyEvent", () => {});});+describe("WebhookChannelConfigSchema headers", () => {+ const withHeaders = (headers: unknown) =>+ WebhookChannelConfigSchema.safeParse({ url: "https://example.com/hook", headers });++ test("accepts well-formed headers", () => {+ expect(withHeaders([{ key: "Authorization", value: "Bearer abc" }]).success).toBe(true);+ });++ test("rejects the headers Infisical sets itself", () => {+ const result = withHeaders([{ key: "Content-Type", value: "text/plain" }]);+ expect(result.success).toBe(false);+ expect(result.error?.issues[0].message).toBe("Header 'Content-Type' is set by Infisical and cannot be overridden");+ expect(withHeaders([{ key: "X-Infisical-Signature", value: "x" }]).success).toBe(false);+ });++ test("rejects duplicate names regardless of case", () => {+ const result = withHeaders([+ { key: "Authorization", value: "a" },+ { key: "authorization", value: "b" }+ ]);+ expect(result.success).toBe(false);+ expect(result.error?.issues[0].message).toBe("Header names must be unique");+ });++ test("rejects names that are not HTTP tokens and values with line breaks", () => {+ expect(withHeaders([{ key: "X Bad", value: "a" }]).success).toBe(false);+ expect(withHeaders([{ key: "X-Ok", value: "a\r\nX-Injected: b" }]).success).toBe(false);+ });++ test("rejects a redacted value that nothing restored", () => {+ const result = withHeaders([{ key: "Authorization", value: ALERT_CHANNEL_REDACTED_VALUE }]);+ expect(result.success).toBe(false);+ expect(result.error?.issues[0].message).toBe(+ "Header 'Authorization' has no saved value to keep. Enter a value for it"+ );+ });+});++describe("webhook header redaction", () => {+ test("masks every value and keeps the names", () => {+ expect(+ redactWebhookHeaders({+ url: "https://example.com/hook",+ headers: [{ key: "Authorization", value: "Bearer abc" }]+ })+ ).toEqual({+ url: "https://example.com/hook",+ headers: [{ key: "Authorization", value: ALERT_CHANNEL_REDACTED_VALUE }]+ });+ });++ test("leaves a config without headers alone", () => {+ expect(redactWebhookHeaders({ url: "https://example.com/hook" })).toEqual({ url: "https://example.com/hook" });+ });++ test("restores a masked value from the stored header with the same name", () => {+ const stored = {+ url: "https://example.com/hook",+ headers: [+ { key: "Authorization", value: "Bearer abc" },+ { key: "X-Env", value: "prod" }+ ]+ };+ expect(+ restoreRedactedWebhookHeaders(+ {+ url: "https://example.com/hook",+ headers: [+ { key: "authorization", value: ALERT_CHANNEL_REDACTED_VALUE },+ { key: "X-Env", value: "staging" }+ ]+ },+ stored+ )+ ).toEqual({+ url: "https://example.com/hook",+ headers: [+ { key: "authorization", value: "Bearer abc" },+ { key: "X-Env", value: "staging" }+ ]+ });+ });++ test("leaves a masked value in place when no stored header matches, so validation names it", () => {+ const restored = restoreRedactedWebhookHeaders(+ { url: "https://example.com/hook", headers: [{ key: "X-New", value: ALERT_CHANNEL_REDACTED_VALUE }] },+ { url: "https://example.com/hook" }+ );+ expect(restored.headers).toEqual([{ key: "X-New", value: ALERT_CHANNEL_REDACTED_VALUE }]);+ expect(WebhookChannelConfigSchema.safeParse(restored).success).toBe(false);+ });+});++describe("sendWebhookNotification", () => {+ test("sends the custom headers next to the ones Infisical sets", async () => {+ const post = vi.mocked(safeRequest.post);+ post.mockClear();++ await sendWebhookNotification({+ ...baseCtx(),+ config: {+ url: "https://example.com/hook",+ signingSecret: "s3cr3t",+ headers: [{ key: "Authorization", value: "Bearer abc" }]+ }+ });++ expect(post).toHaveBeenCalledTimes(1);+ const [url, , options] = post.mock.calls[0];+ expect(url).toBe("https://example.com/hook");+ expect(options?.headers).toMatchObject({ Authorization: "Bearer abc", "Content-Type": "application/json" });+ expect(options?.headers?.["x-infisical-signature"]).toMatch(/^t=\d+,v1=[0-9a-f]{64}$/);+ });+});+describe("SlackChannelConfigSchema webhook allowlist", () => {test("rejects a lookalike host", () => {expect(SlackChannelConfigSchema.safeParse({ webhookUrl: "https://hooks.slack.com.evil.com/x" }).success).toBe(diff --git a/docs/documentation/platform/identities/machine-identities.mdx b/docs/documentation/platform/identities/machine-identities.mdxindex b2fe8c9023..8c1c37acd5 100644--- a/docs/documentation/platform/identities/machine-identities.mdx+++ b/docs/documentation/platform/identities/machine-identities.mdx@@ -189,7 +189,7 @@ Each alert sends notifications to between 1 and 10 channels:| **Email** | Users and groups in your organization, up to 20 per channel. If someone joins a group after you add the group, they also get the notifications. || **Slack** | An [Incoming Webhook](https://api.slack.com/messaging/webhooks) URL that uses HTTPS and has the exact hostname `hooks.slack.com` || **PagerDuty** | An [Events API v2](https://developer.pagerduty.com/docs/events-api-v2-overview) integration key (a 32-character hex string). Infisical opens one incident per expiring credential, and adds repeated changes of the same kind to the same auth method to one open incident. |-| **Webhook** | An HTTPS URL, with an optional [signing secret](#verify-webhook-signatures) |+| **Webhook** | An HTTPS URL, with an optional [signing secret](#verify-webhook-signatures) and optional custom headers, such as an `Authorization` header your endpoint expects. Header values are encrypted and returned as `******` after you save the channel. |### Webhook payloaddiff --git a/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdx b/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdxindex 83694cd52d..8e4f3fb535 100644--- a/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdx+++ b/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdx@@ -18,6 +18,9 @@ A webhook channel on a certificate [alert](/documentation/platform/pki/applicati<Step>Optionally, enter a **Signing Secret** so your endpoint can [verify the signature](#verify-the-signature) of each request.</Step>+ <Step>+ Optionally, select **Add header** to send [custom headers](#custom-headers) with each request, such as the authorization header your endpoint expects.+ </Step><Step>Optionally, select **Send test** to send a test notification to the channel.</Step>@@ -26,6 +29,14 @@ A webhook channel on a certificate [alert](/documentation/platform/pki/applicati</Step></Steps>+## Custom headers++Infisical sends every custom header you add on the channel with each request. Use them when your endpoint authenticates callers with a header, such as the HTTP source of an incident management tool that expects an `Authorization: Bearer <token>` header.++A channel can have up to 20 headers. Header values are encrypted, and the API returns them as `******` after you save the channel. When you edit the channel, leave a value unchanged to keep it, or enter a new one to replace it.++You can't set the `Content-Type` and `x-infisical-signature` headers, because Infisical sets them on every request.+## Webhook event typesEach request is a [CloudEvents](https://cloudevents.io/) JSON payload. The `type` and `subject` fields name the event:diff --git a/frontend/src/hooks/api/alerts/types.ts b/frontend/src/hooks/api/alerts/types.tsindex 67fbbcde5c..a75972922d 100644--- a/frontend/src/hooks/api/alerts/types.ts+++ b/frontend/src/hooks/api/alerts/types.ts@@ -192,6 +192,14 @@ export const channelFormSchema = zwebhookUrl: z.string().optional(),url: z.string().optional(),signingSecret: z.string().optional(),+ headers: z+ .array(+ z.object({+ key: z.string().trim().min(1, "Header name is required"),+ value: z.string().min(1, "Header value is required")+ })+ )+ .default([]),integrationKey: z.string().optional(),recipients: z.array(diff --git a/frontend/src/hooks/api/alerts/utils.ts b/frontend/src/hooks/api/alerts/utils.tsindex 0260257d0c..d384216907 100644--- a/frontend/src/hooks/api/alerts/utils.ts+++ b/frontend/src/hooks/api/alerts/utils.ts@@ -1,5 +1,7 @@import { AlertChannelType, TAlert, TAlertChannelInput, TChannelForm } from "./types";+export const ALERT_CHANNEL_REDACTED_VALUE = "******";+export const toChannelForm = (channel: TAlert["channels"][number]): TChannelForm => ({id: channel.id,channelType: channel.channelType,@@ -9,6 +11,7 @@ export const toChannelForm = (channel: TAlert["channels"][number]): TChannelFormwebhookUrl: "",url: (channel.config.url as string) ?? "",signingSecret: "",+ headers: (channel.config.headers as TChannelForm["headers"]) ?? [],integrationKey: "",hasWebhookUrl: Boolean(channel.config.hasWebhookUrl),hasSigningSecret: Boolean(channel.config.hasSigningSecret),@@ -33,7 +36,8 @@ export const toChannelInput = (channel: TChannelForm): TAlertChannelInput => {...base,config: {url: channel.url,- ...(channel.signingSecret ? { signingSecret: channel.signingSecret } : {})+ ...(channel.signingSecret ? { signingSecret: channel.signingSecret } : {}),+ ...(channel.headers.length ? { headers: channel.headers } : {})}};case AlertChannelType.PagerDuty:diff --git a/frontend/src/pages/cert-manager/components/CertificateAlerts/types.ts b/frontend/src/pages/cert-manager/components/CertificateAlerts/types.tsindex d201664b97..286e4caea1 100644--- a/frontend/src/pages/cert-manager/components/CertificateAlerts/types.ts+++ b/frontend/src/pages/cert-manager/components/CertificateAlerts/types.ts@@ -12,7 +12,8 @@ import {TAlert,TAlertChannelRecipient,TCertificateAlertEventType,- TChannelForm+ TChannelForm,+ toChannelForm} from "@app/hooks/api/alerts";import { CertSource } from "@app/hooks/api/certificates/enums";import { getCertSourceLabel } from "@app/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils";@@ -380,23 +381,13 @@ export const toCertificateAlertForm = (conditionNames: toConditionNames(alert),channels: alert.channels.map((channel): TChannelForm => ({- id: channel.id,- name: channel.name,- channelType: channel.channelType,- enabled: channel.enabled,+ ...toChannelForm(channel),recipients: channel.recipients.filter((recipient) =>!isAvailable ||recipient.principalType !== AlertPrincipalType.User ||emailByUserId.has(recipient.principalId)- ),- url: (channel.config.url as string) ?? "",- webhookUrl: "",- signingSecret: "",- integrationKey: "",- hasSigningSecret: Boolean(channel.config.hasSigningSecret),- hasWebhookUrl: Boolean(channel.config.hasWebhookUrl),- hasIntegrationKey: Boolean(channel.config.hasIntegrationKey)+ )}))});diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretReminderForm.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretReminderForm.tsxindex be8385982f..a8140676fa 100644--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretReminderForm.tsx+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretReminderForm.tsx@@ -173,6 +173,7 @@ export const SecretReminderForm = ({webhookUrl: "",url: "",signingSecret: "",+ headers: [],integrationKey: ""}),[currentProject.id]diff --git a/frontend/src/views/Alerts/ChannelCard.tsx b/frontend/src/views/Alerts/ChannelCard.tsxindex 9af850e102..ea8b23d13e 100644--- a/frontend/src/views/Alerts/ChannelCard.tsx+++ b/frontend/src/views/Alerts/ChannelCard.tsx@@ -1,6 +1,6 @@-import { ReactElement, useState } from "react";-import { Controller, useFormContext, UseFormRegisterReturn, useWatch } from "react-hook-form";-import { EyeIcon, EyeOffIcon, SendIcon, TrashIcon } from "lucide-react";+import { ReactElement } from "react";+import { Controller, useFormContext, useWatch } from "react-hook-form";+import { SendIcon, TrashIcon } from "lucide-react";import { createNotification } from "@app/components/notifications";import {@@ -11,10 +11,6 @@ import {FieldLabel,IconButton,Input,- InputGroup,- InputGroupAddon,- InputGroupButton,- InputGroupInput,Label,Toggle} from "@app/components/v3";@@ -30,6 +26,8 @@ import {import { getChannelIcon } from "./channelIcons";import { ChannelRecipientsField } from "./ChannelRecipientsField";+import { ChannelSecretInput } from "./ChannelSecretInput";+import { WebhookHeadersField } from "./WebhookHeadersField";export type TChannelRecipientsRenderProps = {value: TAlertChannelRecipient[];@@ -50,41 +48,6 @@ type Props = {const KEEP_PLACEHOLDER = "•••••••• (leave blank to keep)";-const ChannelSecretInput = ({- id,- placeholder,- isError,- registration-}: {- id: string;- placeholder?: string;- isError?: boolean;- registration: UseFormRegisterReturn;-}) => {- const [isRevealed, setIsRevealed] = useState(false);-- return (- <InputGroup>- <InputGroupInput- {...registration}- id={id}- type={isRevealed ? "text" : "password"}- placeholder={placeholder}- autoComplete="off"- aria-invalid={Boolean(isError)}- />- <InputGroupAddon align="inline-end">- <InputGroupButton- aria-label={isRevealed ? "Hide value" : "Reveal value"}- onClick={() => setIsRevealed((current) => !current)}- >- {isRevealed ? <EyeOffIcon /> : <EyeIcon />}- </InputGroupButton>- </InputGroupAddon>- </InputGroup>- );-};-export const ChannelCard = ({index,projectId,@@ -274,6 +237,7 @@ export const ChannelCard = ({<FieldError errors={[channelErrors?.signingSecret]} /></FieldContent></Field>+ <WebhookHeadersField index={index} isExisting={isExisting} /></>)}diff --git a/frontend/src/views/Alerts/ChannelSecretInput.tsx b/frontend/src/views/Alerts/ChannelSecretInput.tsxnew file mode 100644index 0000000000..bce2a798b1--- /dev/null+++ b/frontend/src/views/Alerts/ChannelSecretInput.tsx@@ -0,0 +1,54 @@+import { FocusEventHandler, useState } from "react";+import { UseFormRegisterReturn } from "react-hook-form";+import { EyeIcon, EyeOffIcon } from "lucide-react";++import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@app/components/v3";++type Props = {+ id: string;+ placeholder?: string;+ isError?: boolean;+ registration: UseFormRegisterReturn;+ ariaLabel?: string;+ onFocus?: FocusEventHandler<HTMLInputElement>;+ onBlur?: FocusEventHandler<HTMLInputElement>;+};++export const ChannelSecretInput = ({+ id,+ placeholder,+ isError,+ registration,+ ariaLabel,+ onFocus,+ onBlur+}: Props) => {+ const [isRevealed, setIsRevealed] = useState(false);++ return (+ <InputGroup>+ <InputGroupInput+ {...registration}+ id={id}+ type={isRevealed ? "text" : "password"}+ placeholder={placeholder}+ autoComplete="off"+ aria-label={ariaLabel}+ aria-invalid={Boolean(isError)}+ onFocus={onFocus}+ onBlur={(event) => {+ registration.onBlur(event);+ onBlur?.(event);+ }}+ />+ <InputGroupAddon align="inline-end">+ <InputGroupButton+ aria-label={isRevealed ? "Hide value" : "Reveal value"}+ onClick={() => setIsRevealed((current) => !current)}+ >+ {isRevealed ? <EyeOffIcon /> : <EyeIcon />}+ </InputGroupButton>+ </InputGroupAddon>+ </InputGroup>+ );+};diff --git a/frontend/src/views/Alerts/ChannelsField.tsx b/frontend/src/views/Alerts/ChannelsField.tsxindex 48cf4bb639..5c9b4abcd0 100644--- a/frontend/src/views/Alerts/ChannelsField.tsx+++ b/frontend/src/views/Alerts/ChannelsField.tsx@@ -26,6 +26,7 @@ const buildNewChannel = (channelType: AlertChannelType, name: string): TChannelFwebhookUrl: "",url: "",signingSecret: "",+ headers: [],integrationKey: ""});diff --git a/frontend/src/views/Alerts/WebhookHeadersField.tsx b/frontend/src/views/Alerts/WebhookHeadersField.tsxnew file mode 100644index 0000000000..0facfb7511--- /dev/null+++ b/frontend/src/views/Alerts/WebhookHeadersField.tsx@@ -0,0 +1,100 @@+import { useState } from "react";+import { useFieldArray, useFormContext } from "react-hook-form";+import { PlusIcon, TrashIcon } from "lucide-react";++import {+ Button,+ Field,+ FieldContent,+ FieldError,+ FieldLabel,+ IconButton,+ Input+} from "@app/components/v3";+import { ALERT_CHANNEL_REDACTED_VALUE, TChannelsForm } from "@app/hooks/api/alerts";++import { ChannelSecretInput } from "./ChannelSecretInput";++type Props = {+ index: number;+ isExisting: boolean;+};++export const WebhookHeadersField = ({ index, isExisting }: Props) => {+ const {+ control,+ register,+ getValues,+ setValue,+ formState: { errors }+ } = useFormContext<TChannelsForm>();+ const { fields, append, remove } = useFieldArray({ control, name: `channels.${index}.headers` });+ const headerErrors = errors.channels?.[index]?.headers;++ const [clearedRows, setClearedRows] = useState<Set<string>>(() => new Set());++ return (+ <Field>+ <FieldLabel>+ Headers <span className="text-muted">(optional)</span>+ </FieldLabel>+ <FieldContent>+ <div className="flex flex-col gap-2">+ {fields.map((field, i) => {+ const valueName = `channels.${index}.headers.${i}.value` as const;+ return (+ <div key={field.id} className="flex items-start gap-2">+ <Field className="w-2/5">+ <Input+ aria-label="Header name"+ placeholder="Authorization"+ isError={Boolean(headerErrors?.[i]?.key)}+ {...register(`channels.${index}.headers.${i}.key`)}+ />+ <FieldError errors={[headerErrors?.[i]?.key]} />+ </Field>+ <Field className="grow">+ <ChannelSecretInput+ id={`channel-${index}-header-${i}-value`}+ ariaLabel="Header value"+ placeholder="Bearer <token>"+ isError={Boolean(headerErrors?.[i]?.value)}+ registration={register(valueName)}+ onFocus={() => {+ if (getValues(valueName) !== ALERT_CHANNEL_REDACTED_VALUE) return;+ setValue(valueName, "");+ setClearedRows((current) => new Set(current).add(field.id));+ }}+ onBlur={() => {+ if (!clearedRows.has(field.id) || getValues(valueName) !== "") return;+ setValue(valueName, ALERT_CHANNEL_REDACTED_VALUE);+ }}+ />+ <FieldError errors={[headerErrors?.[i]?.value]} />+ </Field>+ <IconButton aria-label="Remove header" variant="outline" onClick={() => remove(i)}>+ <TrashIcon className="size-4" />+ </IconButton>+ </div>+ );+ })}+ <Button+ type="button"+ variant="outline"+ size="xs"+ className="self-start"+ onClick={() => append({ key: "", value: "" })}+ >+ <PlusIcon className="size-3.5" />+ Add header+ </Button>+ {isExisting && fields.length > 0 && (+ <p className="text-xs text-muted">+ Saved values are hidden. Leave a value unchanged to keep it.+ </p>+ )}+ </div>+ </FieldContent>+ </Field>+ );+};