Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

clean code

Thiago Araujo da Silvad90f0b0d4610
diff --git a/backend/src/services/alert/alert-channel-service.test.ts b/backend/src/services/alert/alert-channel-service.test.ts
index 666f1ee716..985be4d772 100644
--- a/backend/src/services/alert/alert-channel-service.test.ts
+++ b/backend/src/services/alert/alert-channel-service.test.ts
@@ -159,38 +159,6 @@ describe("alert channel service", () => {
expect(detail.recipients).toEqual([]);
});
- 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",
- authType: "bearer",
- authCredentials: "abc",
- headers: [{ key: "X-Env", value: "prod" }]
- },
- 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",
- authType: "bearer",
- headers: [{ key: "X-Env", value: "prod" }],
- hasSigningSecret: false,
- hasAuthCredentials: true,
- hasBasicPassword: false,
- hasAuthHeaderValue: false
- });
- });
-
describe("webhook authentication on update", () => {
const seedBearer = () =>
seedRow({
@@ -228,12 +196,6 @@ describe("alert channel service", () => {
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", async () => {
diff --git a/backend/src/services/alert/alert-channel-types.ts b/backend/src/services/alert/alert-channel-types.ts
index e8455eda2c..3757713d16 100644
--- a/backend/src/services/alert/alert-channel-types.ts
+++ b/backend/src/services/alert/alert-channel-types.ts
@@ -86,7 +86,7 @@ export type TAlertChannelDefinition = {
export const EmailChannelConfigSchema = z.object({}).strip();
-export const WEBHOOK_MAX_HEADERS = 20;
+const WEBHOOK_MAX_HEADERS = 20;
export const WEBHOOK_MAX_HEADERS_LENGTH = 4096;
@@ -102,6 +102,8 @@ const WEBHOOK_AUTH_FIELDS_BY_TYPE: Record<WebhookAuthType, string[]> = {
[WebhookAuthType.HEADER]: ["authHeaderName", "authHeaderValue"]
};
+const WEBHOOK_AUTH_FIELDS = Object.values(WEBHOOK_AUTH_FIELDS_BY_TYPE).flat();
+
export const WEBHOOK_AUTH_SECRET_FIELD_BY_TYPE: Record<WebhookAuthType, string> = {
[WebhookAuthType.BEARER]: "authCredentials",
[WebhookAuthType.BASIC]: "basicPassword",
@@ -149,7 +151,7 @@ const headerValueSchema = (label: string) =>
.max(4096, `${label} cannot be longer than 4096 characters`)
.refine((value) => httpHeaderValueRegex.test(value), `${label} ${UNSENDABLE_CHARACTER_MESSAGE}`);
-export const WebhookChannelHeaderSchema = z
+const WebhookChannelHeaderSchema = z
.object({
key: headerNameSchema([...WEBHOOK_RESERVED_HEADERS, "authorization"]),
value: z
@@ -162,8 +164,6 @@ export const WebhookChannelHeaderSchema = z
(header) => ({ message: `Header '${header.key}' ${UNSENDABLE_CHARACTER_MESSAGE}`, path: ["value"] })
);
-export type TWebhookChannelHeader = z.infer<typeof WebhookChannelHeaderSchema>;
-
export const WebhookChannelConfigSchema = z
.object({
url: z
@@ -243,9 +243,7 @@ export const WebhookChannelConfigSchema = z
.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)
- )
+ Object.entries(config).filter(([field]) => kept.has(field) || !WEBHOOK_AUTH_FIELDS.includes(field))
) as typeof config;
});
diff --git a/backend/src/services/alert/channels/alert-channel-registry.ts b/backend/src/services/alert/channels/alert-channel-registry.ts
index c486034611..5cb1e6034c 100644
--- a/backend/src/services/alert/channels/alert-channel-registry.ts
+++ b/backend/src/services/alert/channels/alert-channel-registry.ts
@@ -4,6 +4,7 @@ import {
PagerDutyChannelConfigSchema,
SlackChannelConfigSchema,
TAlertChannelDefinition,
+ WEBHOOK_AUTH_SECRET_FIELD_BY_TYPE,
WebhookChannelConfigSchema
} from "../alert-channel-types";
import { sendEmailNotification } from "./alert-channel-email-fns";
@@ -29,7 +30,7 @@ export const ALERT_CHANNEL_REGISTRY: Record<AlertChannelType, TAlertChannelDefin
[AlertChannelType.WEBHOOK]: {
type: AlertChannelType.WEBHOOK,
directed: false,
- secretFields: ["signingSecret", "authCredentials", "basicPassword", "authHeaderValue"],
+ secretFields: ["signingSecret", ...Object.values(WEBHOOK_AUTH_SECRET_FIELD_BY_TYPE)],
configSchema: WebhookChannelConfigSchema,
assertKeptSecretsAllowed: assertWebhookKeptSecretsAllowed,
send: sendWebhookNotification
diff --git a/backend/src/services/alert/channels/alert-channels.test.ts b/backend/src/services/alert/channels/alert-channels.test.ts
index 001645b7b2..419aeabf07 100644
--- a/backend/src/services/alert/channels/alert-channels.test.ts
+++ b/backend/src/services/alert/channels/alert-channels.test.ts
@@ -228,10 +228,6 @@ describe("WebhookChannelConfigSchema headers", () => {
const withHeaders = (headers: unknown) =>
WebhookChannelConfigSchema.safeParse({ url: "https://example.com/hook", headers });
- test("accepts well-formed headers", () => {
- expect(withHeaders([{ key: "X-Env", value: "prod" }]).success).toBe(true);
- });
-
test("rejects the headers Infisical sets itself", () => {
const result = withHeaders([{ key: "Content-Type", value: "text/plain" }]);
expect(result.success).toBe(false);
@@ -433,13 +429,6 @@ describe("sendWebhookNotification", () => {
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" });
});
});
diff --git a/frontend/src/hooks/api/alerts/types.ts b/frontend/src/hooks/api/alerts/types.ts
index efc78def18..a43f9e2bde 100644
--- a/frontend/src/hooks/api/alerts/types.ts
+++ b/frontend/src/hooks/api/alerts/types.ts
@@ -25,10 +25,32 @@ export enum WebhookAuthType {
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 const WEBHOOK_AUTH_FIELDS: Record<
+ WebhookAuthType,
+ {
+ label: string;
+ name?: { field: "basicUsername" | "authHeaderName"; label: string; placeholder: string };
+ secret: {
+ field: "authCredentials" | "basicPassword" | "authHeaderValue";
+ label: string;
+ hasSaved: "hasAuthCredentials" | "hasBasicPassword" | "hasAuthHeaderValue";
+ };
+ }
+> = {
+ [WebhookAuthType.Bearer]: {
+ label: "Bearer token",
+ secret: { field: "authCredentials", label: "Token", hasSaved: "hasAuthCredentials" }
+ },
+ [WebhookAuthType.Basic]: {
+ label: "Basic auth",
+ name: { field: "basicUsername", label: "Username", placeholder: "Username" },
+ secret: { field: "basicPassword", label: "Password", hasSaved: "hasBasicPassword" }
+ },
+ [WebhookAuthType.Header]: {
+ label: "API key header",
+ name: { field: "authHeaderName", label: "Header name", placeholder: "X-API-Key" },
+ secret: { field: "authHeaderValue", label: "API key", hasSaved: "hasAuthHeaderValue" }
+ }
};
export enum AlertPrincipalType {
@@ -195,7 +217,7 @@ export type TUpdateAlertDTO = {
channels?: TAlertChannelInput[];
};
-export const normalizeWebhookUrl = (url?: string) => {
+const normalizeWebhookUrl = (url?: string) => {
try {
return new URL(url ?? "").href;
} catch {
@@ -268,44 +290,27 @@ export const channelFormSchema = z
});
}
break;
- case AlertChannelType.Webhook:
- if (!channel.url) {
- ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["url"], message: "URL is required" });
+ case AlertChannelType.Webhook: {
+ const requireField = (field: keyof typeof channel, message: string, isSaved?: boolean) => {
+ if (channel[field] || (isSaved && !isNew)) return;
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: [field], message });
+ };
+
+ requireField("url", "URL is required");
+ if (channel.signingSecretEnabled) {
+ requireField("signingSecret", "Signing secret is required", channel.hasSigningSecret);
}
- {
- 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;
- }
+ if (channel.authType) {
+ const { name, secret } = WEBHOOK_AUTH_FIELDS[channel.authType];
+ if (name) requireField(name.field, `${name.label} is required`);
+ requireField(
+ secret.field,
+ `${secret.label} is required`,
+ channel[secret.hasSaved] && !isWebhookUrlChanged(channel)
+ );
}
break;
+ }
case AlertChannelType.PagerDuty:
if ((isNew || !channel.hasIntegrationKey) && !channel.integrationKey) {
ctx.addIssue({
diff --git a/frontend/src/hooks/api/alerts/utils.ts b/frontend/src/hooks/api/alerts/utils.ts
index 21e229623a..d50266813b 100644
--- a/frontend/src/hooks/api/alerts/utils.ts
+++ b/frontend/src/hooks/api/alerts/utils.ts
@@ -3,6 +3,7 @@ import {
TAlert,
TAlertChannelInput,
TChannelForm,
+ WEBHOOK_AUTH_FIELDS,
WebhookAuthType
} from "./types";
@@ -37,24 +38,13 @@ 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 {};
- }
+ if (!channel.authType) return {};
+ const { name, secret } = WEBHOOK_AUTH_FIELDS[channel.authType];
+ return filled({
+ authType: channel.authType,
+ ...(name ? { [name.field]: channel[name.field] } : {}),
+ [secret.field]: channel[secret.field]
+ });
};
const toWebhookSigningSecretConfig = (channel: TChannelForm) => {
diff --git a/frontend/src/views/Alerts/WebhookAuthenticationField.tsx b/frontend/src/views/Alerts/WebhookAuthenticationField.tsx
index 20076b1ab1..04a60f8999 100644
--- a/frontend/src/views/Alerts/WebhookAuthenticationField.tsx
+++ b/frontend/src/views/Alerts/WebhookAuthenticationField.tsx
@@ -18,7 +18,7 @@ import {
import {
isWebhookUrlChanged,
TChannelsForm,
- WEBHOOK_AUTH_TYPE_LABELS,
+ WEBHOOK_AUTH_FIELDS,
WebhookAuthType
} from "@app/hooks/api/alerts";
@@ -28,37 +28,6 @@ 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,
@@ -99,9 +68,9 @@ export const WebhookAuthenticationField = ({ index }: Props) => {
);
}
- const fields = AUTH_FIELDS[authType];
+ const { name, secret } = WEBHOOK_AUTH_FIELDS[authType];
const isUrlChanged = isWebhookUrlChanged(channel);
- const hasSavedSecret = Boolean(channel.id && channel[fields.hasSecret]);
+ const hasSavedSecret = Boolean(channel.id && channel[secret.hasSaved]);
return (
<Field>
@@ -120,7 +89,7 @@ export const WebhookAuthenticationField = ({ index }: Props) => {
<SelectContent position="popper">
{Object.values(WebhookAuthType).map((type) => (
<SelectItem key={type} value={type}>
- {WEBHOOK_AUTH_TYPE_LABELS[type]}
+ {WEBHOOK_AUTH_FIELDS[type].label}
</SelectItem>
))}
</SelectContent>
@@ -136,36 +105,34 @@ export const WebhookAuthenticationField = ({ index }: Props) => {
</IconButton>
</div>
<div className="flex items-start gap-2">
- {fields.name && (
+ {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}`)}
+ key={name.field}
+ aria-label={name.label}
+ placeholder={name.placeholder}
+ isError={Boolean(channelErrors?.[name.field])}
+ {...register(`channels.${index}.${name.field}`)}
/>
- <FieldError errors={[channelErrors?.[fields.name.field]]} />
+ <FieldError errors={[channelErrors?.[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}`)}
+ key={secret.field}
+ id={`channel-${index}-${secret.field}`}
+ ariaLabel={secret.label}
+ placeholder={hasSavedSecret && !isUrlChanged ? KEEP_PLACEHOLDER : secret.label}
+ isError={Boolean(channelErrors?.[secret.field])}
+ registration={register(`channels.${index}.${secret.field}`)}
/>
- <FieldError errors={[channelErrors?.[fields.secret]]} />
+ <FieldError errors={[channelErrors?.[secret.field]]} />
</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.
+ The URL changed, so enter the {secret.label.toLowerCase()} again. Saved credentials
+ are only sent to the URL they were saved with.
</p>
)}
</div>