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
segregate each type of field so we have a clear structure
Thiago Araujo da Silva0db4d4f1fa14
diff --git a/backend/e2e-test/routes/v1/alerts.spec.ts b/backend/e2e-test/routes/v1/alerts.spec.tsindex 7476784b74..9fc22bef65 100644--- a/backend/e2e-test/routes/v1/alerts.spec.ts+++ b/backend/e2e-test/routes/v1/alerts.spec.ts@@ -86,63 +86,54 @@ 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 () => {+ test("webhook headers are returned as they are, and saved credentials only go to the URL they were saved with", async () => {const alert = await createAlert({body: identityAlert({- name: "headers",+ name: "webhook-auth",channels: [{...webhookChannel,- config: { url: "https://example.com/hook", headers: [{ key: "Authorization", value: "Bearer abc" }] }+ config: {+ url: "https://example.com/hook",+ authType: "bearer",+ authCredentials: "abc",+ headers: [{ key: "X-Env", value: "prod" }]+ }}]}),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(webhook.config).toMatchObject({+ authType: "bearer",+ hasAuthCredentials: true,+ headers: [{ key: "X-Env", value: "prod" }]+ });+ expect(webhook.config).not.toHaveProperty("authCredentials");++ const updateConfig = (config: Record<string, unknown>) =>+ updateAlert({+ alertId: alert.id,+ authToken,+ body: { channels: [{ id: webhook.id, name: webhook.name, channelType: "webhook", config }] }+ });++ const kept = await updateConfig({+ url: "https://example.com/hook",+ authType: "bearer",+ headers: [{ key: "X-Env", value: "staging" }]+ });+ expect(kept.channels[0].config).toMatchObject({+ hasAuthCredentials: true,+ headers: [{ key: "X-Env", value: "staging" }]});- 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");+ const moved = await updateConfig({ url: "https://example.com/other-hook", authType: "bearer" }).raw();+ expect(moved.statusCode).toBe(400);+ expect(moved.json().message).toContain(+ "Enter the authentication credentials again because the webhook URL changed"+ );});test("updating with another alert's channel id is refused", async () => {diff --git a/backend/src/services/alert/alert-channel-config-fns.ts b/backend/src/services/alert/alert-channel-config-fns.tsindex a49e6dc5b4..d89214cd4b 100644--- a/backend/src/services/alert/alert-channel-config-fns.ts+++ b/backend/src/services/alert/alert-channel-config-fns.ts@@ -34,6 +34,8 @@ export const mergeChannelConfigWithStored = (const definition = ALERT_CHANNEL_REGISTRY[channelType as AlertChannelType];if (!definition) return incomingConfig;+ definition.assertKeptSecretsAllowed?.(incomingConfig, existingConfig);+const merged: Record<string, unknown> = { ...incomingConfig };definition.secretFields.forEach((field) => {if (!(field in incomingConfig)) {@@ -43,5 +45,5 @@ export const mergeChannelConfigWithStored = (const value = incomingConfig[field];if (value === "" || value === null || value === undefined) delete merged[field];});- return definition.restoreRedactedConfig ? definition.restoreRedactedConfig(merged, existingConfig) : merged;+ return merged;};diff --git a/backend/src/services/alert/alert-channel-service.test.ts b/backend/src/services/alert/alert-channel-service.test.tsindex 2432f84f0d..666f1ee716 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 { ALERT_CHANNEL_REDACTED_VALUE, AlertChannelType } from "./alert-channel-types";+import { AlertChannelType } from "./alert-channel-types";import { AlertPrincipalType } from "./alert-types";// Identity cipher: encryptedConfig is just JSON bytes of the config.@@ -149,18 +149,29 @@ describe("alert channel service", () => {const [detail] = await service.getDetailsForChannels([channel], { decryptor: decryptor as never });expect(detail.name).toBe("Ops webhook");// Secret is redacted on the way out.- expect(detail.config).toEqual({ url: "https://example.com/hook", hasSigningSecret: true });+ expect(detail.config).toEqual({+ url: "https://example.com/hook",+ hasSigningSecret: true,+ hasAuthCredentials: false,+ hasBasicPassword: false,+ hasAuthHeaderValue: false+ });expect(detail.recipients).toEqual([]);});- test("returns webhook header names with their values redacted", async () => {+ test("returns custom headers as they are and hides the authentication secret", 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" }] },+ config: {+ url: "https://example.com/hook",+ authType: "bearer",+ authCredentials: "abc",+ headers: [{ key: "X-Env", value: "prod" }]+ },orgId: "org-1",...CHANNEL_INPUT},@@ -171,58 +182,68 @@ describe("alert channel service", () => {const [detail] = await service.getDetailsForChannels([channel], { decryptor: decryptor as never });expect(detail.config).toEqual({url: "https://example.com/hook",+ authType: "bearer",+ headers: [{ key: "X-Env", value: "prod" }],hasSigningSecret: false,- headers: [{ key: "Authorization", value: ALERT_CHANNEL_REDACTED_VALUE }]+ hasAuthCredentials: true,+ hasBasicPassword: false,+ hasAuthHeaderValue: false});});- 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({+ describe("webhook authentication on update", () => {+ const seedBearer = () =>+ seedRow({+ id: "ch-1",+ channelType: AlertChannelType.WEBHOOK,+ encryptedConfig: encConfig({ url: "https://example.com/hook", authType: "bearer", authCredentials: "abc" })+ });++ const update = async (config: Record<string, unknown>) => {+ const { service, store } = buildService();+ await updateChannel(+ service,+ { recipientScope: RECIPIENT_SCOPE, channelId: "ch-1", config },+ seedBearer() as never,+ cipher,+ tx+ );+ return JSON.parse(store.get("ch-1")!.encryptedConfig.toString()) as Record<string, unknown>;+ };++ test("keeps the saved credentials when the update leaves them out", async () => {+ expect(await update({ url: "https://example.com/hook", authType: "bearer" })).toEqual({url: "https://example.com/hook",- headers: [- { key: "Authorization", value: "Bearer abc" },- { key: "X-Env", value: "prod" }- ]- })+ authType: "bearer",+ authCredentials: "abc"+ });});- 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- );+ test("drops the old type's secret when the authentication type changes", async () => {+ expect(+ await update({ url: "https://example.com/hook", authType: "basic", basicUsername: "ops", basicPassword: "pw" })+ ).toEqual({ url: "https://example.com/hook", authType: "basic", basicUsername: "ops", basicPassword: "pw" });+ });- 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("removes authentication when the update has no type", async () => {+ expect(await update({ url: "https://example.com/hook" })).toEqual({ url: "https://example.com/hook" });+ });++ test("refuses to keep the saved credentials for a different URL", async () => {+ await expect(update({ url: "https://example.com/other-hook", authType: "bearer" })).rejects.toThrow(+ "Enter the authentication credentials again because the webhook URL changed"+ );+ });});- test("stores webhook header names trimmed, so a redacted value can be kept later", async () => {+ test("stores webhook header names trimmed", async () => {const { service, store } = buildService();const created = await createChannel(service,{name: "Ops webhook",channelType: AlertChannelType.WEBHOOK,- config: { url: "https://example.com/hook", headers: [{ key: " Authorization ", value: "Bearer abc" }] },+ config: { url: "https://example.com/hook", headers: [{ key: " X-Env ", value: "prod" }] },orgId: "org-1",...CHANNEL_INPUT},@@ -230,78 +251,8 @@ describe("alert channel service", () => {tx);- await updateChannel(- service,- {- recipientScope: RECIPIENT_SCOPE,- channelId: created.id,- config: {- url: "https://example.com/hook",- headers: [{ key: "Authorization", value: ALERT_CHANNEL_REDACTED_VALUE }]- }- },- store.get(created.id) as never,- cipher,- tx- );-const stored = JSON.parse(store.get(created.id)!.encryptedConfig.toString()) as Record<string, unknown>;- expect(stored.headers).toEqual([{ key: "Authorization", value: "Bearer abc" }]);- });-- test("counts kept webhook header values toward the combined header length", async () => {- const { service } = buildService();- const channel = seedRow({- id: "ch-1",- channelType: AlertChannelType.WEBHOOK,- encryptedConfig: encConfig({- url: "https://example.com/hook",- headers: [{ key: "Authorization", value: "a".repeat(4000) }]- })- });-- await expect(- updateChannel(- service,- {- recipientScope: RECIPIENT_SCOPE,- channelId: "ch-1",- config: {- url: "https://example.com/hook",- headers: [- { key: "Authorization", value: ALERT_CHANNEL_REDACTED_VALUE },- { key: "X-Trace", value: "b".repeat(200) }- ]- }- },- channel as never,- cipher,- tx- )- ).rejects.toThrow("Webhook header names and values can add up to at most 4096 characters");- });-- 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");+ expect(stored.headers).toEqual([{ key: "X-Env", value: "prod" }]);});test("requires recipients for a directed (email) channel and rejects them for others", async () => {diff --git a/backend/src/services/alert/alert-channel-service.ts b/backend/src/services/alert/alert-channel-service.tsindex 11a86aec36..7ce91fcc03 100644--- a/backend/src/services/alert/alert-channel-service.ts+++ b/backend/src/services/alert/alert-channel-service.ts@@ -197,7 +197,7 @@ export const alertChannelServiceFactory = ({definition.secretFields.forEach((field) => {redacted[`has${capitalize(field)}`] = Boolean(config[field]);});- return definition.redactConfig ? definition.redactConfig(redacted) : redacted;+ return redacted;};const prepareChannelCreate = async (diff --git a/backend/src/services/alert/alert-channel-test-service.test.ts b/backend/src/services/alert/alert-channel-test-service.test.tsindex 015d40633f..30afd4f74d 100644--- a/backend/src/services/alert/alert-channel-test-service.test.ts+++ b/backend/src/services/alert/alert-channel-test-service.test.ts@@ -141,7 +141,10 @@ const buildDeps = (overrides?: {};};-const stubSend = (channelType: "slack" | "email", impl: (ctx: TAlertChannelSendContext) => Promise<TChannelResult>) => {+const stubSend = (+ channelType: "slack" | "email" | "webhook",+ impl: (ctx: TAlertChannelSendContext) => Promise<TChannelResult>+) => {const definition = ALERT_CHANNEL_REGISTRY[channelType];const original = definition.send;definition.send = impl;@@ -363,6 +366,49 @@ describe("alertChannelTestService", () => {}});+ test("does not send saved webhook credentials to a different URL", async () => {+ const sent: TAlertChannelSendContext[] = [];+ const restore = stubSend("webhook", async (ctx) => {+ sent.push(ctx);+ return { success: true };+ });++ try {+ const { deps } = buildDeps({+ channel: {+ id: "channel-1",+ orgId: ORG_ID,+ projectId: null,+ channelType: "webhook",+ encryptedConfig: Buffer.from(+ JSON.stringify({+ url: "https://example.com/hook",+ authType: "bearer",+ authCredentials: "abc"+ })+ )+ }+ });+ const service = alertChannelTestServiceFactory(deps);++ await expect(+ service.testChannel({+ ...actor,+ resourceType: RESOURCE_TYPE,+ channelId: "channel-1",+ channelType: "webhook" as never,+ config: {+ url: "https://attacker.example.net/hook",+ authType: "bearer"+ }+ })+ ).rejects.toThrow("Enter the authentication credentials again because the webhook URL changed");+ expect(sent).toHaveLength(0);+ } finally {+ restore();+ }+ });+test("rejects a saved channel that belongs to another organization", async () => {const { deps } = buildDeps({channel: {diff --git a/backend/src/services/alert/alert-channel-types.ts b/backend/src/services/alert/alert-channel-types.tsindex 925585efb3..e8455eda2c 100644--- a/backend/src/services/alert/alert-channel-types.ts+++ b/backend/src/services/alert/alert-channel-types.ts@@ -6,8 +6,6 @@ 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",@@ -82,11 +80,7 @@ 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>;+ assertKeptSecretsAllowed?: (incomingConfig: Record<string, unknown>, storedConfig: Record<string, unknown>) => void;send: (ctx: TAlertChannelSendContext) => Promise<TChannelResult>;};@@ -94,10 +88,26 @@ export const EmailChannelConfigSchema = z.object({}).strip();export const WEBHOOK_MAX_HEADERS = 20;-// Keeps the largest valid webhook config (URL, signing secret, headers) under the route's 8192-character-// config cap. It is checked on the merged config, so headers kept as "******" across edits count too.export const WEBHOOK_MAX_HEADERS_LENGTH = 4096;+export enum WebhookAuthType {+ BEARER = "bearer",+ BASIC = "basic",+ HEADER = "header"+}++const WEBHOOK_AUTH_FIELDS_BY_TYPE: Record<WebhookAuthType, string[]> = {+ [WebhookAuthType.BEARER]: ["authCredentials"],+ [WebhookAuthType.BASIC]: ["basicUsername", "basicPassword"],+ [WebhookAuthType.HEADER]: ["authHeaderName", "authHeaderValue"]+};++export const WEBHOOK_AUTH_SECRET_FIELD_BY_TYPE: Record<WebhookAuthType, string> = {+ [WebhookAuthType.BEARER]: "authCredentials",+ [WebhookAuthType.BASIC]: "basicPassword",+ [WebhookAuthType.HEADER]: "authHeaderValue"+};+const WEBHOOK_RESERVED_HEADERS = ["content-type","x-infisical-signature",@@ -110,21 +120,38 @@ const WEBHOOK_RESERVED_HEADERS = [const httpHeaderNameRegex = new RE2("^[A-Za-z0-9!#$%&'*+.^_`|~-]+$");const httpHeaderValueRegex = new RE2("^[\\t\\x20-\\x7e\\x80-\\xff]*$");+const UNSENDABLE_CHARACTER_MESSAGE =+ "has a character that can't be sent in an HTTP header, such as an emoji, a control character, or an invisible space. Re-enter the value";++const headerNameSchema = (reserved: string[]) =>+ 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) => !reserved.includes(key.toLowerCase()),+ (key) => ({+ message:+ key.toLowerCase() === "authorization"+ ? "Use Authentication to set the 'Authorization' header"+ : `Header '${key}' is set by Infisical and cannot be overridden`+ })+ );++const headerValueSchema = (label: string) =>+ z+ .string()+ .max(4096, `${label} cannot be longer than 4096 characters`)+ .refine((value) => httpHeaderValueRegex.test(value), `${label} ${UNSENDABLE_CHARACTER_MESSAGE}`);+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` })- ),+ key: headerNameSchema([...WEBHOOK_RESERVED_HEADERS, "authorization"]),value: z.string().min(1, "Header values cannot be empty")@@ -132,46 +159,95 @@ export const WebhookChannelHeaderSchema = z}).refine((header) => httpHeaderValueRegex.test(header.value),- (header) => ({- message: `Header '${header.key}' has a character that can't be sent in an HTTP header, such as an emoji, a control character, or an invisible space. Re-enter the value`,- path: ["value"]- })- )- .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"]- })+ (header) => ({ message: `Header '${header.key}' ${UNSENDABLE_CHARACTER_MESSAGE}`, 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(),- 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" }- )- .refine(- (headers) =>- (headers ?? []).reduce((total, header) => total + header.key.length + header.value.length, 0) <=- WEBHOOK_MAX_HEADERS_LENGTH,- { message: `Webhook header names and values can add up to at most ${WEBHOOK_MAX_HEADERS_LENGTH} characters` }- )-});+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(),+ authType: z.nativeEnum(WebhookAuthType).optional(),+ authCredentials: headerValueSchema("The token").optional(),+ basicUsername: z+ .string()+ .max(256, "The username cannot be longer than 256 characters")+ .refine((username) => !username.includes(":"), "The username cannot contain ':'")+ .optional(),+ basicPassword: z.string().max(256, "The password cannot be longer than 256 characters").optional(),+ authHeaderName: headerNameSchema(WEBHOOK_RESERVED_HEADERS).optional(),+ authHeaderValue: headerValueSchema("The API key").optional(),+ 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" }+ )+ })+ .superRefine((config, ctx) => {+ const require = (field: keyof typeof config, message: string) => {+ if (!config[field]) ctx.addIssue({ code: z.ZodIssueCode.custom, path: [field], message });+ };++ let authLength = 0;+ switch (config.authType) {+ case WebhookAuthType.BEARER:+ require("authCredentials", "Enter a token for bearer authentication");+ authLength = config.authCredentials?.length ?? 0;+ break;+ case WebhookAuthType.BASIC:+ require("basicUsername", "Enter a username for basic authentication");+ require("basicPassword", "Enter a password for basic authentication");+ authLength = (config.basicUsername?.length ?? 0) + (config.basicPassword?.length ?? 0);+ break;+ case WebhookAuthType.HEADER: {+ require("authHeaderName", "Enter a header name for API key authentication");+ require("authHeaderValue", "Enter an API key for API key authentication");+ authLength = (config.authHeaderName?.length ?? 0) + (config.authHeaderValue?.length ?? 0);+ const authHeaderName = config.authHeaderName?.toLowerCase();+ if (authHeaderName && config.headers?.some((header) => header.key.toLowerCase() === authHeaderName)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["headers"],+ message: `Header '${config.authHeaderName}' is already set by Authentication`+ });+ }+ break;+ }+ default:+ break;+ }++ const headersLength = (config.headers ?? []).reduce(+ (total, header) => total + header.key.length + header.value.length,+ 0+ );+ if (authLength + headersLength > WEBHOOK_MAX_HEADERS_LENGTH) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["headers"],+ message: `Authentication and custom headers can add up to at most ${WEBHOOK_MAX_HEADERS_LENGTH} characters`+ });+ }+ })+ .transform((config) => {+ const kept = new Set(config.authType ? WEBHOOK_AUTH_FIELDS_BY_TYPE[config.authType] : []);+ return Object.fromEntries(+ Object.entries(config).filter(+ ([field]) => kept.has(field) || !Object.values(WEBHOOK_AUTH_FIELDS_BY_TYPE).flat().includes(field)+ )+ ) as typeof config;+ });export const SlackChannelConfigSchema = z.object({webhookUrl: zdiff --git a/backend/src/services/alert/channels/alert-channel-registry.ts b/backend/src/services/alert/channels/alert-channel-registry.tsindex 22a02a67c7..c486034611 100644--- a/backend/src/services/alert/channels/alert-channel-registry.ts+++ b/backend/src/services/alert/channels/alert-channel-registry.ts@@ -9,11 +9,7 @@ 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 {- redactWebhookHeaders,- restoreRedactedWebhookHeaders,- sendWebhookNotification-} from "./alert-channel-webhook-fns";+import { assertWebhookKeptSecretsAllowed, sendWebhookNotification } from "./alert-channel-webhook-fns";export const ALERT_CHANNEL_REGISTRY: Record<AlertChannelType, TAlertChannelDefinition> = {[AlertChannelType.EMAIL]: {@@ -33,10 +29,9 @@ export const ALERT_CHANNEL_REGISTRY: Record<AlertChannelType, TAlertChannelDefin[AlertChannelType.WEBHOOK]: {type: AlertChannelType.WEBHOOK,directed: false,- secretFields: ["signingSecret"],+ secretFields: ["signingSecret", "authCredentials", "basicPassword", "authHeaderValue"],configSchema: WebhookChannelConfigSchema,- redactConfig: redactWebhookHeaders,- restoreRedactedConfig: restoreRedactedWebhookHeaders,+ assertKeptSecretsAllowed: assertWebhookKeptSecretsAllowed,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 c4c5e73d33..bed50ab681 100644--- a/backend/src/services/alert/channels/alert-channel-webhook-fns.ts+++ b/backend/src/services/alert/channels/alert-channel-webhook-fns.ts@@ -1,17 +1,22 @@import crypto from "node:crypto";+import { z } from "zod";++import { BadRequestError } from "@app/lib/errors";import { safeRequest } from "@app/lib/validator";import {ALERT_CHANNEL_HTTP_TIMEOUT,- ALERT_CHANNEL_REDACTED_VALUE,TAlertChannelSendContext,TAlertPayload,TChannelResult,- TWebhookChannelHeader,+ WEBHOOK_AUTH_SECRET_FIELD_BY_TYPE,+ WebhookAuthType,WebhookChannelConfigSchema} from "../alert-channel-types";+type TWebhookChannelConfig = z.infer<typeof WebhookChannelConfigSchema>;+type TAlertWebhookPayload = {specversion: "1.0";type: string;@@ -55,58 +60,54 @@ 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- )- };+const normalizeUrl = (url: unknown): string | null => {+ if (typeof url !== "string") return null;+ try {+ return new URL(url).href;+ } catch {+ return null;+ }};-export const restoreRedactedWebhookHeaders = (+export const assertWebhookKeptSecretsAllowed = (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);- });- }+) => {+ const secretField = WEBHOOK_AUTH_SECRET_FIELD_BY_TYPE[incomingConfig.authType as WebhookAuthType];+ if (!secretField || incomingConfig[secretField] || storedConfig[secretField] == null) return;- 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 incomingUrl = normalizeUrl(incomingConfig.url);+ if (incomingUrl === null || incomingUrl === normalizeUrl(storedConfig.url)) return;++ throw new BadRequestError({+ message:+ "Enter the authentication credentials again because the webhook URL changed. Saved credentials are only sent to the URL they were saved with"+ });+};++const buildAuthHeaders = (config: TWebhookChannelConfig): Record<string, string> => {+ switch (config.authType) {+ case WebhookAuthType.BEARER:+ return { Authorization: `Bearer ${config.authCredentials}` };+ case WebhookAuthType.BASIC:+ return {+ Authorization: `Basic ${Buffer.from(`${config.basicUsername}:${config.basicPassword}`).toString("base64")}`+ };+ case WebhookAuthType.HEADER:+ return config.authHeaderName ? { [config.authHeaderName]: config.authHeaderValue ?? "" } : {};+ default:+ return {};+ }};const generateHmacSignature = (data: string, secret: string): string =>crypto.createHmac("sha256", secret).update(data).digest("hex");-const triggerWebhook = async (params: {- url: string;- payload: TAlertWebhookPayload;- signingSecret?: string | null;- customHeaders?: TWebhookChannelHeader[];-}): Promise<void> => {- const { url, payload, signingSecret, customHeaders } = params;+const triggerWebhook = async (config: TWebhookChannelConfig, payload: TAlertWebhookPayload): Promise<void> => {+ const { url, signingSecret } = config;const headers: Record<string, string> = {- ...Object.fromEntries((customHeaders ?? []).map(({ key, value }) => [key, value])),+ ...Object.fromEntries((config.headers ?? []).map(({ key, value }) => [key, value])),+ ...buildAuthHeaders(config),"Content-Type": "application/json"};@@ -128,11 +129,6 @@ 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,- customHeaders: config.headers- });+ await triggerWebhook(config, payload);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 b0dafbb31b..001645b7b2 100644--- a/backend/src/services/alert/channels/alert-channels.test.ts+++ b/backend/src/services/alert/channels/alert-channels.test.ts@@ -3,12 +3,12 @@ import { validateHeaderValue } from "node:http";import { safeRequest } from "@app/lib/validator";import {- ALERT_CHANNEL_REDACTED_VALUE,AlertChannelType,DIRECTED_ALERT_CHANNEL_TYPES,SlackChannelConfigSchema,TAlertPayload,WEBHOOK_MAX_HEADERS_LENGTH,+ WebhookAuthType,WebhookChannelConfigSchema} from "../alert-channel-types";import { sendEmailNotification } from "./alert-channel-email-fns";@@ -16,9 +16,8 @@ import { buildPagerDutyEvent } from "./alert-channel-pagerduty-fns";import { ALERT_CHANNEL_REGISTRY } from "./alert-channel-registry";import { buildSlackPayload } from "./alert-channel-slack-fns";import {+ assertWebhookKeptSecretsAllowed,buildWebhookPayload,- redactWebhookHeaders,- restoreRedactedWebhookHeaders,sendWebhookNotification} from "./alert-channel-webhook-fns";@@ -230,7 +229,7 @@ describe("WebhookChannelConfigSchema headers", () => {WebhookChannelConfigSchema.safeParse({ url: "https://example.com/hook", headers });test("accepts well-formed headers", () => {- expect(withHeaders([{ key: "Authorization", value: "Bearer abc" }]).success).toBe(true);+ expect(withHeaders([{ key: "X-Env", value: "prod" }]).success).toBe(true);});test("rejects the headers Infisical sets itself", () => {@@ -242,27 +241,18 @@ describe("WebhookChannelConfigSchema headers", () => {});});- 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("sends people to Authentication for the Authorization header", () => {+ const result = withHeaders([{ key: "authorization", value: "Bearer abc" }]);+ expect(result.error?.issues[0].message).toBe("Use Authentication to set the 'Authorization' header");});- test("limits the combined length of header names and values", () => {- const value = "a".repeat(WEBHOOK_MAX_HEADERS_LENGTH - "Authorization".length);- expect(withHeaders([{ key: "Authorization", value }]).success).toBe(true);-+ test("rejects duplicate names regardless of case", () => {const result = withHeaders([- { key: "Authorization", value },- { key: "X-Env", value: "prod" }+ { key: "X-Env", value: "a" },+ { key: "x-env", value: "b" }]);expect(result.success).toBe(false);- expect(result.error?.issues[0].message).toBe(- `Webhook header names and values can add up to at most ${WEBHOOK_MAX_HEADERS_LENGTH} characters`- );+ expect(result.error?.issues[0].message).toBe("Header names must be unique");});test("rejects names that are not HTTP tokens", () => {@@ -296,96 +286,161 @@ describe("WebhookChannelConfigSchema headers", () => {});test("names the header whose value can't be sent", () => {- const result = withHeaders([{ key: "Authorization", value: "Bearer abc\u200b123" }]);+ const result = withHeaders([{ key: "X-Env", value: "prod\u200b" }]);expect(result.error?.issues[0].message).toBe(- "Header 'Authorization' has a character that can't be sent in an HTTP header, such as an emoji, a control character, or an invisible space. Re-enter the value"+ "Header 'X-Env' has a character that can't be sent in an HTTP header, such as an emoji, a control character, or an invisible space. Re-enter the value");});+});- 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("WebhookChannelConfigSchema authentication", () => {+ const parse = (config: Record<string, unknown>) =>+ WebhookChannelConfigSchema.safeParse({ url: "https://example.com/hook", ...config });++ test("requires the fields of the chosen type", () => {+ expect(parse({ authType: WebhookAuthType.BEARER }).error?.issues[0].message).toBe(+ "Enter a token for bearer authentication"+ );+ expect(parse({ authType: WebhookAuthType.BASIC, basicUsername: "ops" }).error?.issues[0].message).toBe(+ "Enter a password for basic authentication"+ );+ expect(parse({ authType: WebhookAuthType.HEADER, authHeaderValue: "k" }).error?.issues[0].message).toBe(+ "Enter a header name for API key authentication");});-});-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({+ test("drops the fields of authentication types that are not in use", () => {+ const result = parse({+ authType: WebhookAuthType.BASIC,+ basicUsername: "ops",+ basicPassword: "pw",+ authCredentials: "stale-token"+ });+ expect(result.data).toEqual({url: "https://example.com/hook",- headers: [{ key: "Authorization", value: ALERT_CHANNEL_REDACTED_VALUE }]+ authType: WebhookAuthType.BASIC,+ basicUsername: "ops",+ basicPassword: "pw"});+ expect(parse({ authCredentials: "stale-token" }).data).toEqual({ url: "https://example.com/hook" });});- test("leaves a config without headers alone", () => {- expect(redactWebhookHeaders({ url: "https://example.com/hook" })).toEqual({ url: "https://example.com/hook" });+ test("rejects a basic auth username with a colon", () => {+ expect(+ parse({ authType: WebhookAuthType.BASIC, basicUsername: "a:b", basicPassword: "pw" }).error?.issues[0].message+ ).toBe("The username cannot contain ':'");});- 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" }- ]- };+ test("rejects a custom header that repeats the API key header", () => {+ const result = parse({+ authType: WebhookAuthType.HEADER,+ authHeaderName: "X-API-Key",+ authHeaderValue: "k",+ headers: [{ key: "x-api-key", value: "other" }]+ });+ expect(result.error?.issues[0].message).toBe("Header 'X-API-Key' is already set by Authentication");+ });++ test("counts authentication toward the combined header length", () => {+ const authCredentials = "a".repeat(WEBHOOK_MAX_HEADERS_LENGTH - "X-Env".length - "prod".length);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" }- ]+ parse({ authType: WebhookAuthType.BEARER, authCredentials, headers: [{ key: "X-Env", value: "prod" }] }).success+ ).toBe(true);++ const result = parse({+ authType: WebhookAuthType.BEARER,+ authCredentials: `${authCredentials}a`,+ headers: [{ key: "X-Env", value: "prod" }]});+ expect(result.error?.issues[0].message).toBe(+ `Authentication and custom headers can add up to at most ${WEBHOOK_MAX_HEADERS_LENGTH} characters`+ );});+});- 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" }+describe("assertWebhookKeptSecretsAllowed", () => {+ const stored = {+ url: "https://api.example.com/sources/abc",+ authType: WebhookAuthType.BEARER,+ authCredentials: "abc"+ };++ test("refuses to keep saved credentials when the URL changed, even on the same host", () => {+ expect(() =>+ assertWebhookKeptSecretsAllowed(+ { url: "https://api.example.com/sources/attacker", authType: WebhookAuthType.BEARER },+ stored+ )+ ).toThrow(+ "Enter the authentication credentials again because the webhook URL changed. Saved credentials are only sent to the URL they were saved with");- expect(restored.headers).toEqual([{ key: "X-New", value: ALERT_CHANNEL_REDACTED_VALUE }]);- expect(WebhookChannelConfigSchema.safeParse(restored).success).toBe(false);+ });++ test("allows a changed URL when the credentials are entered again", () => {+ expect(() =>+ assertWebhookKeptSecretsAllowed(+ { url: "https://other.example.com/hook", authType: WebhookAuthType.BEARER, authCredentials: "new" },+ stored+ )+ ).not.toThrow();+ });++ test("keeps saved credentials when only the host case differs", () => {+ expect(() =>+ assertWebhookKeptSecretsAllowed(+ { url: "https://API.example.com/sources/abc", authType: WebhookAuthType.BEARER },+ stored+ )+ ).not.toThrow();+ });++ test("keeps the signing secret on a URL change, since it is never sent", () => {+ expect(() =>+ assertWebhookKeptSecretsAllowed(+ { url: "https://other.example.com/hook" },+ { url: "https://example.com/hook", signingSecret: "s3cr3t" }+ )+ ).not.toThrow();});});describe("sendWebhookNotification", () => {- test("sends the custom headers next to the ones Infisical sets", async () => {+ const send = async (config: Record<string, unknown>) => {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" }]- }- });-+ await sendWebhookNotification({ ...baseCtx(), config: { url: "https://example.com/hook", ...config } });expect(post).toHaveBeenCalledTimes(1);- const [url, , options] = post.mock.calls[0];+ return post.mock.calls[0];+ };++ test("sends the custom headers next to the ones Infisical sets", async () => {+ const [url, , options] = await send({ signingSecret: "s3cr3t", headers: [{ key: "X-Env", value: "prod" }] });expect(url).toBe("https://example.com/hook");- expect(options?.headers).toMatchObject({ Authorization: "Bearer abc", "Content-Type": "application/json" });+ expect(options?.headers).toMatchObject({ "X-Env": "prod", "Content-Type": "application/json" });expect(options?.headers?.["x-infisical-signature"]).toMatch(/^t=\d+,v1=[0-9a-f]{64}$/);});++ test("sends each authentication type", async () => {+ const [, , bearer] = await send({ authType: WebhookAuthType.BEARER, authCredentials: "abc" });+ expect(bearer?.headers).toMatchObject({ Authorization: "Bearer abc" });++ const [, , basic] = await send({ authType: WebhookAuthType.BASIC, basicUsername: "ops", basicPassword: "pw" });+ expect(basic?.headers).toMatchObject({ Authorization: `Basic ${Buffer.from("ops:pw").toString("base64")}` });++ const [, , header] = await send({+ authType: WebhookAuthType.HEADER,+ authHeaderName: "X-API-Key",+ authHeaderValue: "k"+ });+ expect(header?.headers).toMatchObject({ "X-API-Key": "k" });++ const [, , otherScheme] = await send({+ authType: WebhookAuthType.HEADER,+ authHeaderName: "Authorization",+ authHeaderValue: "GenieKey k"+ });+ expect(otherScheme?.headers).toMatchObject({ Authorization: "GenieKey k" });+ });});describe("SlackChannelConfigSchema webhook allowlist", () => {diff --git a/docs/documentation/platform/identities/machine-identities.mdx b/docs/documentation/platform/identities/machine-identities.mdxindex 8c1c37acd5..9ba7fd11e0 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) 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** | An HTTPS URL, with an optional [signing secret](#verify-webhook-signatures), optional authentication (a bearer token, basic auth, or an API key header), and optional custom headers. Infisical only sends saved credentials to the URL they were saved with, so enter them again if you change the URL. |### Webhook payloaddiff --git a/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdx b/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdxindex c29f183c20..514a65fb88 100644--- a/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdx+++ b/docs/documentation/platform/pki/applications/alerting/webhook-alerts.mdx@@ -16,10 +16,13 @@ A webhook channel on a certificate [alert](/documentation/platform/pki/applicatiSelect **Add Channel** > **Webhook** and enter the **URL** of your endpoint. The URL must use HTTPS.</Step><Step>- Optionally, enter a **Signing Secret** so your endpoint can [verify the signature](#verify-the-signature) of each request.+ Optionally, select **Add signing secret** and enter a 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.+ Optionally, select **Add authentication** and enter the credentials your endpoint expects. See [Authentication](#authentication) for the types you can choose.+ </Step>+ <Step>+ Optionally, select **Add header** to send [custom headers](#custom-headers) with each request.</Step><Step>Optionally, select **Send test** to send a test notification to the channel.@@ -29,13 +32,31 @@ A webhook channel on a certificate [alert](/documentation/platform/pki/applicati</Step></Steps>-## Custom headers+## Authentication++If your endpoint only accepts authenticated requests, add one authentication method to the channel. Infisical sends the credentials in a header on each request:++| Type | What you enter | Header that Infisical sends |+|------|----------------|-----------------------------|+| **Bearer token** | A token | `Authorization: Bearer <token>` |+| **Basic auth** | A username and a password | `Authorization: Basic <base64 of username:password>` |+| **API key header** | A header name, such as `X-API-Key`, and the key | `<header name>: <key>` |-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.+If your endpoint expects a scheme other than `Bearer` in the `Authorization` header, such as `GenieKey <key>`, select **API key header**, enter `Authorization` as the header name, and enter the full value, including the scheme.++After you save the channel, Infisical doesn't show the token, password, or key again:++- To keep the saved value when you edit the channel, leave the field blank+- If you change the channel's URL, enter the value again, because Infisical only sends saved credentials to the URL they were saved with++## Custom headers-A channel can have up to 20 headers, and their names and values can add up to 4,096 characters. 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.+Infisical sends every custom header you add on the channel with each request, such as an `x-env` header that your endpoint uses to route alerts:-You can't set the `Content-Type`, `Content-Length`, `Transfer-Encoding`, `Connection`, `Host`, and `x-infisical-signature` headers, because Infisical sets them on every request.+- Anyone who can view the alert can see custom header values, so put credentials in [authentication](#authentication) instead+- A channel can have up to 20 custom headers, with up to 4,096 characters for all header names, values, and authentication credentials together+- You can't add `Content-Type`, `Content-Length`, `Transfer-Encoding`, `Connection`, `Host`, or `x-infisical-signature` as custom headers, because Infisical sets them on every request+- To send an `Authorization` header, use [authentication](#authentication) instead of a custom header## Webhook event typesdiff --git a/frontend/src/hooks/api/alerts/types.ts b/frontend/src/hooks/api/alerts/types.tsindex a75972922d..efc78def18 100644--- a/frontend/src/hooks/api/alerts/types.ts+++ b/frontend/src/hooks/api/alerts/types.ts@@ -19,6 +19,18 @@ export enum AlertChannelType {PagerDuty = "pagerduty"}+export enum WebhookAuthType {+ Bearer = "bearer",+ Basic = "basic",+ Header = "header"+}++export const WEBHOOK_AUTH_TYPE_LABELS: Record<WebhookAuthType, string> = {+ [WebhookAuthType.Bearer]: "Bearer token",+ [WebhookAuthType.Basic]: "Basic auth",+ [WebhookAuthType.Header]: "API key header"+};+export enum AlertPrincipalType {User = "user",Group = "group",@@ -183,6 +195,17 @@ export type TUpdateAlertDTO = {channels?: TAlertChannelInput[];};+export const normalizeWebhookUrl = (url?: string) => {+ try {+ return new URL(url ?? "").href;+ } catch {+ return url ?? "";+ }+};++export const isWebhookUrlChanged = (channel: { id?: string; url?: string; savedUrl?: string }) =>+ Boolean(channel.id) && normalizeWebhookUrl(channel.url) !== normalizeWebhookUrl(channel.savedUrl);+export const channelFormSchema = z.object({id: z.string().optional(),@@ -192,6 +215,13 @@ export const channelFormSchema = zwebhookUrl: z.string().optional(),url: z.string().optional(),signingSecret: z.string().optional(),+ signingSecretEnabled: z.boolean().optional(),+ authType: z.nativeEnum(WebhookAuthType).optional(),+ authCredentials: z.string().optional(),+ basicUsername: z.string().optional(),+ basicPassword: z.string().optional(),+ authHeaderName: z.string().optional(),+ authHeaderValue: z.string().optional(),headers: z.array(z.object({@@ -211,7 +241,11 @@ export const channelFormSchema = z.default([]),hasWebhookUrl: z.boolean().optional(),hasSigningSecret: z.boolean().optional(),- hasIntegrationKey: z.boolean().optional()+ hasAuthCredentials: z.boolean().optional(),+ hasBasicPassword: z.boolean().optional(),+ hasAuthHeaderValue: z.boolean().optional(),+ hasIntegrationKey: z.boolean().optional(),+ savedUrl: z.string().optional()}).superRefine((channel, ctx) => {const isNew = !channel.id;@@ -238,6 +272,39 @@ export const channelFormSchema = zif (!channel.url) {ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["url"], message: "URL is required" });}+ {+ const require = (field: keyof typeof channel, message: string, isSaved?: boolean) => {+ if (channel[field] || (isSaved && !isNew)) return;+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: [field], message });+ };+ const isSentSecretSaved = (hasValue?: boolean) =>+ hasValue && !isWebhookUrlChanged(channel);++ if (channel.signingSecretEnabled) {+ require("signingSecret", "Signing secret is required", channel.hasSigningSecret);+ }+ switch (channel.authType) {+ case WebhookAuthType.Bearer:+ require("authCredentials", "Token is required", isSentSecretSaved(+ channel.hasAuthCredentials+ ));+ break;+ case WebhookAuthType.Basic:+ require("basicUsername", "Username is required");+ require("basicPassword", "Password is required", isSentSecretSaved(+ channel.hasBasicPassword+ ));+ break;+ case WebhookAuthType.Header:+ require("authHeaderName", "Header name is required");+ require("authHeaderValue", "API key is required", isSentSecretSaved(+ channel.hasAuthHeaderValue+ ));+ break;+ default:+ break;+ }+ }break;case AlertChannelType.PagerDuty:if ((isNew || !channel.hasIntegrationKey) && !channel.integrationKey) {diff --git a/frontend/src/hooks/api/alerts/utils.ts b/frontend/src/hooks/api/alerts/utils.tsindex d384216907..21e229623a 100644--- a/frontend/src/hooks/api/alerts/utils.ts+++ b/frontend/src/hooks/api/alerts/utils.ts@@ -1,6 +1,10 @@-import { AlertChannelType, TAlert, TAlertChannelInput, TChannelForm } from "./types";--export const ALERT_CHANNEL_REDACTED_VALUE = "******";+import {+ AlertChannelType,+ TAlert,+ TAlertChannelInput,+ TChannelForm,+ WebhookAuthType+} from "./types";export const toChannelForm = (channel: TAlert["channels"][number]): TChannelForm => ({id: channel.id,@@ -11,13 +15,53 @@ export const toChannelForm = (channel: TAlert["channels"][number]): TChannelFormwebhookUrl: "",url: (channel.config.url as string) ?? "",signingSecret: "",+ signingSecretEnabled: Boolean(channel.config.hasSigningSecret),+ authType: channel.config.authType as WebhookAuthType | undefined,+ authCredentials: "",+ basicUsername: (channel.config.basicUsername as string) ?? "",+ basicPassword: "",+ authHeaderName: (channel.config.authHeaderName as string) ?? "",+ authHeaderValue: "",headers: (channel.config.headers as TChannelForm["headers"]) ?? [],integrationKey: "",hasWebhookUrl: Boolean(channel.config.hasWebhookUrl),hasSigningSecret: Boolean(channel.config.hasSigningSecret),- hasIntegrationKey: Boolean(channel.config.hasIntegrationKey)+ hasAuthCredentials: Boolean(channel.config.hasAuthCredentials),+ hasBasicPassword: Boolean(channel.config.hasBasicPassword),+ hasAuthHeaderValue: Boolean(channel.config.hasAuthHeaderValue),+ hasIntegrationKey: Boolean(channel.config.hasIntegrationKey),+ savedUrl: channel.config.url as string | undefined});+const filled = (fields: Record<string, string | undefined>) =>+ Object.fromEntries(Object.entries(fields).filter(([, value]) => value));++const toWebhookAuthConfig = (channel: TChannelForm) => {+ switch (channel.authType) {+ case WebhookAuthType.Bearer:+ return filled({ authType: channel.authType, authCredentials: channel.authCredentials });+ case WebhookAuthType.Basic:+ return filled({+ authType: channel.authType,+ basicUsername: channel.basicUsername,+ basicPassword: channel.basicPassword+ });+ case WebhookAuthType.Header:+ return filled({+ authType: channel.authType,+ authHeaderName: channel.authHeaderName?.trim(),+ authHeaderValue: channel.authHeaderValue+ });+ default:+ return {};+ }+};++const toWebhookSigningSecretConfig = (channel: TChannelForm) => {+ if (channel.signingSecretEnabled) return filled({ signingSecret: channel.signingSecret });+ return channel.hasSigningSecret ? { signingSecret: null } : {};+};+export const toChannelInput = (channel: TChannelForm): TAlertChannelInput => {const base: TAlertChannelInput = {...(channel.id ? { id: channel.id } : {}),@@ -36,7 +80,8 @@ export const toChannelInput = (channel: TChannelForm): TAlertChannelInput => {...base,config: {url: channel.url,- ...(channel.signingSecret ? { signingSecret: channel.signingSecret } : {}),+ ...toWebhookSigningSecretConfig(channel),+ ...toWebhookAuthConfig(channel),...(channel.headers.length ? { headers: channel.headers } : {})}};diff --git a/frontend/src/views/Alerts/ChannelCard.tsx b/frontend/src/views/Alerts/ChannelCard.tsxindex ea8b23d13e..bc12531936 100644--- a/frontend/src/views/Alerts/ChannelCard.tsx+++ b/frontend/src/views/Alerts/ChannelCard.tsx@@ -26,8 +26,10 @@ import {import { getChannelIcon } from "./channelIcons";import { ChannelRecipientsField } from "./ChannelRecipientsField";-import { ChannelSecretInput } from "./ChannelSecretInput";+import { ChannelSecretInput, KEEP_PLACEHOLDER } from "./ChannelSecretInput";+import { WebhookAuthenticationField } from "./WebhookAuthenticationField";import { WebhookHeadersField } from "./WebhookHeadersField";+import { WebhookSigningSecretField } from "./WebhookSigningSecretField";export type TChannelRecipientsRenderProps = {value: TAlertChannelRecipient[];@@ -46,8 +48,6 @@ type Props = {renderRecipients?: (props: TChannelRecipientsRenderProps) => ReactElement;};-const KEEP_PLACEHOLDER = "•••••••• (leave blank to keep)";-export const ChannelCard = ({index,projectId,@@ -223,21 +223,9 @@ export const ChannelCard = ({<FieldError errors={[channelErrors?.url]} /></FieldContent></Field>- <Field>- <FieldLabel htmlFor={`channel-${index}-signingSecret`}>- Signing secret <span className="text-muted">(optional)</span>- </FieldLabel>- <FieldContent>- <ChannelSecretInput- id={`channel-${index}-signingSecret`}- placeholder={isExisting && channel?.hasSigningSecret ? KEEP_PLACEHOLDER : ""}- isError={Boolean(channelErrors?.signingSecret)}- registration={register(`channels.${index}.signingSecret`)}- />- <FieldError errors={[channelErrors?.signingSecret]} />- </FieldContent>- </Field>- <WebhookHeadersField index={index} isExisting={isExisting} />+ <WebhookSigningSecretField index={index} />+ <WebhookAuthenticationField index={index} />+ <WebhookHeadersField index={index} /></>)}diff --git a/frontend/src/views/Alerts/ChannelSecretInput.tsx b/frontend/src/views/Alerts/ChannelSecretInput.tsxindex bce2a798b1..22cc7546a0 100644--- a/frontend/src/views/Alerts/ChannelSecretInput.tsx+++ b/frontend/src/views/Alerts/ChannelSecretInput.tsx@@ -1,17 +1,17 @@-import { FocusEventHandler, useState } from "react";+import { useState } from "react";import { UseFormRegisterReturn } from "react-hook-form";import { EyeIcon, EyeOffIcon } from "lucide-react";import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@app/components/v3";+export const KEEP_PLACEHOLDER = "•••••••• (leave blank to keep)";+type Props = {id: string;placeholder?: string;isError?: boolean;registration: UseFormRegisterReturn;ariaLabel?: string;- onFocus?: FocusEventHandler<HTMLInputElement>;- onBlur?: FocusEventHandler<HTMLInputElement>;};export const ChannelSecretInput = ({@@ -19,9 +19,7 @@ export const ChannelSecretInput = ({placeholder,isError,registration,- ariaLabel,- onFocus,- onBlur+ ariaLabel}: Props) => {const [isRevealed, setIsRevealed] = useState(false);@@ -35,11 +33,6 @@ export const ChannelSecretInput = ({autoComplete="off"aria-label={ariaLabel}aria-invalid={Boolean(isError)}- onFocus={onFocus}- onBlur={(event) => {- registration.onBlur(event);- onBlur?.(event);- }}/><InputGroupAddon align="inline-end"><InputGroupButtondiff --git a/frontend/src/views/Alerts/WebhookAuthenticationField.tsx b/frontend/src/views/Alerts/WebhookAuthenticationField.tsxnew file mode 100644index 0000000000..20076b1ab1--- /dev/null+++ b/frontend/src/views/Alerts/WebhookAuthenticationField.tsx@@ -0,0 +1,175 @@+import { Controller, useFormContext, useWatch } from "react-hook-form";+import { PlusIcon, TrashIcon } from "lucide-react";++import { FieldLabelWithTooltip } from "@app/components/secret-rotations-v2/forms/shared";+import {+ Button,+ Field,+ FieldContent,+ FieldError,+ IconButton,+ Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@app/components/v3";+import {+ isWebhookUrlChanged,+ TChannelsForm,+ WEBHOOK_AUTH_TYPE_LABELS,+ WebhookAuthType+} from "@app/hooks/api/alerts";++import { ChannelSecretInput, KEEP_PLACEHOLDER } from "./ChannelSecretInput";++type Props = {+ index: number;+};++type TAuthFields = {+ name?: {+ field: "basicUsername" | "authHeaderName";+ label: string;+ placeholder: string;+ };+ secret: "authCredentials" | "basicPassword" | "authHeaderValue";+ secretLabel: string;+ hasSecret: "hasAuthCredentials" | "hasBasicPassword" | "hasAuthHeaderValue";+};++const AUTH_FIELDS: Record<WebhookAuthType, TAuthFields> = {+ [WebhookAuthType.Bearer]: {+ secret: "authCredentials",+ secretLabel: "Token",+ hasSecret: "hasAuthCredentials"+ },+ [WebhookAuthType.Basic]: {+ name: { field: "basicUsername", label: "Username", placeholder: "Username" },+ secret: "basicPassword",+ secretLabel: "Password",+ hasSecret: "hasBasicPassword"+ },+ [WebhookAuthType.Header]: {+ name: { field: "authHeaderName", label: "Header name", placeholder: "X-API-Key" },+ secret: "authHeaderValue",+ secretLabel: "API key",+ hasSecret: "hasAuthHeaderValue"+ }+};++export const WebhookAuthenticationField = ({ index }: Props) => {+ const {+ control,+ register,+ setValue,+ formState: { errors }+ } = useFormContext<TChannelsForm>();+ const channel = useWatch({ control, name: `channels.${index}` });+ const channelErrors = errors.channels?.[index];+ const authType = channel?.authType;++ const setAuthType = (type?: WebhookAuthType) =>+ setValue(`channels.${index}.authType`, type, { shouldDirty: true });++ const label = (+ <FieldLabelWithTooltip tooltip="Credentials sent with each request, for endpoints that require a token, password, or API key.">+ Authentication <span className="text-muted">(optional)</span>+ </FieldLabelWithTooltip>+ );++ if (!authType) {+ return (+ <Field>+ {label}+ <FieldContent>+ <Button+ type="button"+ variant="outline"+ size="xs"+ className="self-start"+ onClick={() => setAuthType(WebhookAuthType.Bearer)}+ >+ <PlusIcon className="size-3.5" />+ Add authentication+ </Button>+ </FieldContent>+ </Field>+ );+ }++ const fields = AUTH_FIELDS[authType];+ const isUrlChanged = isWebhookUrlChanged(channel);+ const hasSavedSecret = Boolean(channel.id && channel[fields.hasSecret]);++ return (+ <Field>+ {label}+ <FieldContent>+ <div className="flex flex-col gap-2">+ <div className="flex items-start gap-2">+ <Controller+ control={control}+ name={`channels.${index}.authType`}+ render={({ field }) => (+ <Select value={field.value} onValueChange={field.onChange}>+ <SelectTrigger className="w-full" aria-label="Authentication type">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ {Object.values(WebhookAuthType).map((type) => (+ <SelectItem key={type} value={type}>+ {WEBHOOK_AUTH_TYPE_LABELS[type]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ />+ <IconButton+ aria-label="Remove authentication"+ variant="outline"+ onClick={() => setAuthType(undefined)}+ >+ <TrashIcon className="size-4" />+ </IconButton>+ </div>+ <div className="flex items-start gap-2">+ {fields.name && (+ <Field className="w-2/5">+ <Input+ key={fields.name.field}+ aria-label={fields.name.label}+ placeholder={fields.name.placeholder}+ isError={Boolean(channelErrors?.[fields.name.field])}+ {...register(`channels.${index}.${fields.name.field}`)}+ />+ <FieldError errors={[channelErrors?.[fields.name.field]]} />+ </Field>+ )}+ <Field className="grow">+ <ChannelSecretInput+ key={fields.secret}+ id={`channel-${index}-${fields.secret}`}+ ariaLabel={fields.secretLabel}+ placeholder={+ hasSavedSecret && !isUrlChanged ? KEEP_PLACEHOLDER : fields.secretLabel+ }+ isError={Boolean(channelErrors?.[fields.secret])}+ registration={register(`channels.${index}.${fields.secret}`)}+ />+ <FieldError errors={[channelErrors?.[fields.secret]]} />+ </Field>+ </div>+ {hasSavedSecret && isUrlChanged && (+ <p className="text-xs text-muted">+ The URL changed, so enter the {fields.secretLabel.toLowerCase()} again. Saved+ credentials are only sent to the URL they were saved with.+ </p>+ )}+ </div>+ </FieldContent>+ </Field>+ );+};diff --git a/frontend/src/views/Alerts/WebhookHeadersField.tsx b/frontend/src/views/Alerts/WebhookHeadersField.tsxindex c906b5d957..5d05c836fd 100644--- a/frontend/src/views/Alerts/WebhookHeadersField.tsx+++ b/frontend/src/views/Alerts/WebhookHeadersField.tsx@@ -10,21 +10,16 @@ import {IconButton,Input} from "@app/components/v3";-import { ALERT_CHANNEL_REDACTED_VALUE, TChannelsForm } from "@app/hooks/api/alerts";--import { ChannelSecretInput } from "./ChannelSecretInput";+import { TChannelsForm } from "@app/hooks/api/alerts";type Props = {index: number;- isExisting: boolean;};-export const WebhookHeadersField = ({ index, isExisting }: Props) => {+export const WebhookHeadersField = ({ index }: Props) => {const {control,register,- getValues,- setValue,formState: { errors }} = useFormContext<TChannelsForm>();const { fields, append, remove } = useFieldArray({ control, name: `channels.${index}.headers` });@@ -33,51 +28,35 @@ export const WebhookHeadersField = ({ index, isExisting }: Props) => {return (<Field><FieldLabel>- Headers <span className="text-muted">(optional)</span>+ Custom 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, "");- }}- onBlur={() => {- if (- field.value !== ALERT_CHANNEL_REDACTED_VALUE ||- 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>- );- })}+ {fields.map((field, i) => (+ <div key={field.id} className="flex items-start gap-2">+ <Field className="w-2/5">+ <Input+ aria-label="Header name"+ placeholder="x-env"+ isError={Boolean(headerErrors?.[i]?.key)}+ {...register(`channels.${index}.headers.${i}.key`)}+ />+ <FieldError errors={[headerErrors?.[i]?.key]} />+ </Field>+ <Field className="grow">+ <Input+ aria-label="Header value"+ placeholder="production"+ isError={Boolean(headerErrors?.[i]?.value)}+ {...register(`channels.${index}.headers.${i}.value`)}+ />+ <FieldError errors={[headerErrors?.[i]?.value]} />+ </Field>+ <IconButton aria-label="Remove header" variant="outline" onClick={() => remove(i)}>+ <TrashIcon className="size-4" />+ </IconButton>+ </div>+ ))}<Buttontype="button"variant="outline"@@ -88,11 +67,6 @@ export const WebhookHeadersField = ({ index, isExisting }: Props) => {<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>diff --git a/frontend/src/views/Alerts/WebhookSigningSecretField.tsx b/frontend/src/views/Alerts/WebhookSigningSecretField.tsxnew file mode 100644index 0000000000..10c8e62976--- /dev/null+++ b/frontend/src/views/Alerts/WebhookSigningSecretField.tsx@@ -0,0 +1,80 @@+import { useFormContext, useWatch } from "react-hook-form";+import { PlusIcon, TrashIcon } from "lucide-react";++import { FieldLabelWithTooltip } from "@app/components/secret-rotations-v2/forms/shared";+import { Button, Field, FieldContent, FieldError, IconButton } from "@app/components/v3";+import { TChannelsForm } from "@app/hooks/api/alerts";++import { ChannelSecretInput, KEEP_PLACEHOLDER } from "./ChannelSecretInput";++type Props = {+ index: number;+};++export const WebhookSigningSecretField = ({ index }: Props) => {+ const {+ control,+ register,+ setValue,+ formState: { errors }+ } = useFormContext<TChannelsForm>();+ const [isEnabled, hasSigningSecret, channelId] = useWatch({+ control,+ name: [+ `channels.${index}.signingSecretEnabled`,+ `channels.${index}.hasSigningSecret`,+ `channels.${index}.id`+ ]+ });++ const setEnabled = (enabled: boolean) => {+ setValue(`channels.${index}.signingSecretEnabled`, enabled, { shouldDirty: true });+ setValue(`channels.${index}.signingSecret`, "");+ };++ return (+ <Field>+ <FieldLabelWithTooltip+ htmlFor={isEnabled ? `channel-${index}-signingSecret` : undefined}+ tooltip="Signs each request in the x-infisical-signature header so your endpoint can verify it came from Infisical."+ >+ Signing secret <span className="text-muted">(optional)</span>+ </FieldLabelWithTooltip>+ <FieldContent>+ {isEnabled ? (+ <>+ <div className="flex items-start gap-2">+ <div className="grow">+ <ChannelSecretInput+ id={`channel-${index}-signingSecret`}+ placeholder={channelId && hasSigningSecret ? KEEP_PLACEHOLDER : ""}+ isError={Boolean(errors.channels?.[index]?.signingSecret)}+ registration={register(`channels.${index}.signingSecret`)}+ />+ </div>+ <IconButton+ aria-label="Remove signing secret"+ variant="outline"+ onClick={() => setEnabled(false)}+ >+ <TrashIcon className="size-4" />+ </IconButton>+ </div>+ <FieldError errors={[errors.channels?.[index]?.signingSecret]} />+ </>+ ) : (+ <Button+ type="button"+ variant="outline"+ size="xs"+ className="self-start"+ onClick={() => setEnabled(true)}+ >+ <PlusIcon className="size-3.5" />+ Add signing secret+ </Button>+ )}+ </FieldContent>+ </Field>+ );+};