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
simplify condition UI
Thiago Araujo da Silva0f0f4bbcc55c
diff --git a/backend/src/services/alert/providers/identity-credential-alert-provider.test.ts b/backend/src/services/alert/providers/identity-credential-alert-provider.test.tsindex b809d63e2e..0422bf5d9f 100644--- a/backend/src/services/alert/providers/identity-credential-alert-provider.test.ts+++ b/backend/src/services/alert/providers/identity-credential-alert-provider.test.ts@@ -85,10 +85,23 @@ const buildProvider = (opts?: {const actor = { actor: "user", actorId: "u1", actorAuthMethod: null, actorOrgId: "org-1" } as never;describe("identity credential alert provider", () => {- test("condition schema accepts alertBefore formats and rejects junk", () => {+ test("condition schema accepts 1d-90d and rejects everything else", () => {const provider = buildProvider();+ expect(provider.conditionSchema.safeParse({ alertBefore: "1d" }).success).toBe(true);expect(provider.conditionSchema.safeParse({ alertBefore: "30d" }).success).toBe(true);- expect(provider.conditionSchema.safeParse({ alertBefore: "2w" }).success).toBe(true);+ expect(provider.conditionSchema.safeParse({ alertBefore: "90d" }).success).toBe(true);++ // Out of range.+ expect(provider.conditionSchema.safeParse({ alertBefore: "0d" }).success).toBe(false);+ expect(provider.conditionSchema.safeParse({ alertBefore: "91d" }).success).toBe(false);+ expect(provider.conditionSchema.safeParse({ alertBefore: "3650d" }).success).toBe(false);++ // Units other than days are no longer accepted.+ expect(provider.conditionSchema.safeParse({ alertBefore: "2w" }).success).toBe(false);+ expect(provider.conditionSchema.safeParse({ alertBefore: "3m" }).success).toBe(false);+ expect(provider.conditionSchema.safeParse({ alertBefore: "1y" }).success).toBe(false);++ expect(provider.conditionSchema.safeParse({ alertBefore: "30" }).success).toBe(false);expect(provider.conditionSchema.safeParse({ alertBefore: "nope" }).success).toBe(false);expect(provider.conditionSchema.safeParse({}).success).toBe(false);});@@ -206,8 +219,11 @@ describe("identity credential alert provider", () => {test("dedup window spans alertBefore + the scan lead (30d -> 744h, 1d -> 48h) with a 24h floor", () => {const provider = buildProvider();expect(provider.dedupWindowHours?.({ alertBefore: "30d" })).toBe(744);+ expect(provider.dedupWindowHours?.({ alertBefore: "90d" })).toBe(2184);expect(provider.dedupWindowHours?.({ alertBefore: "1d" })).toBe(48);+ // Falls back to the default when the condition can't be parsed.expect(provider.dedupWindowHours?.({ alertBefore: "bad" })).toBe(24);+ expect(provider.dedupWindowHours?.({ alertBefore: "91d" })).toBe(24);});test("assertPermission allows read but denies create when only read is granted (org scope)", async () => {diff --git a/backend/src/services/alert/providers/identity-credential-alert-provider.ts b/backend/src/services/alert/providers/identity-credential-alert-provider.tsindex 72ef30a84d..8b5a4bc80e 100644--- a/backend/src/services/alert/providers/identity-credential-alert-provider.ts+++ b/backend/src/services/alert/providers/identity-credential-alert-provider.ts@@ -25,10 +25,25 @@ import { TExpiringUaClientSecret, TIdentityCredentialAlertDALFactory } from "./iexport const IDENTITY_AUTHENTICATION_RESOURCE_TYPE = "identity.authentication";export const IDENTITY_AUTHENTICATION_EXPIRY_EVENT = "identity.authentication.expiry";-const alertBeforeRegex = new RE2("^\\d+[dwmy]$");+const alertBeforeRegex = new RE2("^\\d+d$");+export const MIN_ALERT_BEFORE_DAYS = 1;+export const MAX_ALERT_BEFORE_DAYS = 90;++const alertBeforeDays = (alertBefore: string): number => parseInt(alertBefore.slice(0, -1), 10);++const isValidAlertBefore = (alertBefore: string): boolean => {+ if (!alertBeforeRegex.test(alertBefore)) return false;+ const days = alertBeforeDays(alertBefore);+ return days >= MIN_ALERT_BEFORE_DAYS && days <= MAX_ALERT_BEFORE_DAYS;+};const IdentityCredentialConditionSchema = z.object({- alertBefore: z.string().refine((v) => alertBeforeRegex.test(v), "Must be in format like '30d', '1w', '3m', '1y'"),+ alertBefore: z+ .string()+ .refine(+ isValidAlertBefore,+ `Must be a whole number of days from ${MIN_ALERT_BEFORE_DAYS}d to ${MAX_ALERT_BEFORE_DAYS}d, e.g. '30d'`+ ),dailyReminder: z.boolean().optional()});@@ -36,25 +51,10 @@ const DAILY_REPEAT_DEDUP_WINDOW_HOURS = 20;type TIdentityCredentialTarget = { credentialType: "ua-client-secret" } & TExpiringUaClientSecret;-const UNIT_TO_INTERVAL_WORD: Record<string, string> = { d: "days", w: "weeks", m: "months", y: "years" };-const UNIT_TO_UNIT_WORD: Record<string, string> = { d: "day", w: "week", m: "month", y: "year" };-const UNIT_TO_DAYS: Record<string, number> = { d: 1, w: 7, m: 30, y: 365 };--const parseAlertBefore = (alertBefore: string) => {- const amount = parseInt(alertBefore.slice(0, -1), 10);- const unit = alertBefore.slice(-1);- return {- intervalSql: `${amount} ${UNIT_TO_INTERVAL_WORD[unit]}`,- days: amount * (UNIT_TO_DAYS[unit] ?? 1)- };-};--// "1d" -> "1 day", "30d" -> "30 days", "1w" -> "1 week"+// "1d" -> "1 day", "30d" -> "30 days"const humanizeAlertBefore = (alertBefore: string): string => {- const amount = parseInt(alertBefore.slice(0, -1), 10);- const unit = alertBefore.slice(-1);- const word = UNIT_TO_UNIT_WORD[unit] ?? unit;- return `${amount} ${word}${amount === 1 ? "" : "s"}`;+ const days = alertBeforeDays(alertBefore);+ return `${days} day${days === 1 ? "" : "s"}`;};const daysUntil = (date: Date): number => Math.ceil((new Date(date).getTime() - Date.now()) / (1000 * 60 * 60 * 24));@@ -128,13 +128,12 @@ export const identityCredentialAlertProviderFactory = ({const findDueTargets = async (input: TFindDueTargetsInput): Promise<TIdentityCredentialTarget[]> => {const { alertBefore } = IdentityCredentialConditionSchema.parse(input.condition);- const { intervalSql } = parseAlertBefore(alertBefore);const uaSecrets = await identityCredentialAlertDAL.findExpiringUaClientSecrets({orgId: input.orgId,projectId: input.projectId,identityId: input.resourceId,- alertBeforeInterval: intervalSql,+ alertBeforeInterval: `${alertBeforeDays(alertBefore)} days`,leadInterval: ALERT_SCAN_LEAD_INTERVAL,asOf: input.asOf});@@ -277,7 +276,7 @@ export const identityCredentialAlertProviderFactory = ({// Span the widened scan window (alertBefore + the scan lead) so a target still fires only once.return Math.max(DEFAULT_DEDUP_WINDOW_HOURS,- (parseAlertBefore(parsed.data.alertBefore).days + ALERT_SCAN_LEAD_DAYS) * 24+ (alertBeforeDays(parsed.data.alertBefore) + ALERT_SCAN_LEAD_DAYS) * 24);},assertPermission,diff --git a/frontend/src/hooks/api/alerts/types.ts b/frontend/src/hooks/api/alerts/types.tsindex 5dad773f04..3b80403be3 100644--- a/frontend/src/hooks/api/alerts/types.ts+++ b/frontend/src/hooks/api/alerts/types.ts@@ -20,19 +20,8 @@ export enum AlertPrincipalType {Group = "group"}-export enum AlertTimeUnit {- Days = "d",- Weeks = "w",- Months = "m",- Years = "y"-}--export const ALERT_TIME_UNIT_LABELS: Record<AlertTimeUnit, string> = {- [AlertTimeUnit.Days]: "days",- [AlertTimeUnit.Weeks]: "weeks",- [AlertTimeUnit.Months]: "months",- [AlertTimeUnit.Years]: "years"-};+export const MIN_ALERT_BEFORE_DAYS = 1;+export const MAX_ALERT_BEFORE_DAYS = 90;export const ALERT_RESOURCE_TYPE_LABELS: Record<AlertResourceType, string> = {[AlertResourceType.IdentityAuthentication]: "Machine Identity Authentication"@@ -184,12 +173,11 @@ export const alertFormSchema = z.object({description: z.string().max(1000).optional(),resourceType: z.nativeEnum(AlertResourceType),eventType: z.nativeEnum(AlertEventType),- alertBeforeValue: z+ alertBeforeDays: z.number({ invalid_type_error: "Enter a number" }).int("Must be a whole number")- .min(1, "Must be at least 1")- .max(3650, "Too large"),- alertBeforeUnit: z.nativeEnum(AlertTimeUnit),+ .min(MIN_ALERT_BEFORE_DAYS, `Must be at least ${MIN_ALERT_BEFORE_DAYS} day`)+ .max(MAX_ALERT_BEFORE_DAYS, `Must be at most ${MAX_ALERT_BEFORE_DAYS} days`),dailyReminder: z.boolean().default(false),enabled: z.boolean().default(true),channels: z.array(channelFormSchema).min(1, "At least one channel is required")diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityAlertDetail.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityAlertDetail.tsxindex 576ea47713..1aafa34976 100644--- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityAlertDetail.tsx+++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityAlertDetail.tsx@@ -32,14 +32,11 @@ type Props = {identityName: string;};-const TIME_UNIT_WORD: Record<string, string> = { d: "day", w: "week", m: "month", y: "year" };-const formatCondition = (alertBefore?: string): string => {- const match = alertBefore?.match(/^(\d+)([dwmy])$/);+ const match = alertBefore?.match(/^(\d+)d$/);if (!match) return "";- const amount = parseInt(match[1], 10);- const word = TIME_UNIT_WORD[match[2]] ?? match[2];- return `alert ${amount} ${word}${amount === 1 ? "" : "s"} before`;+ const days = parseInt(match[1], 10);+ return `alert ${days} day${days === 1 ? "" : "s"} before`;};export const IdentityAlertDetail = ({ identityId, identityName }: Props) => {diff --git a/frontend/src/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityAlertDetail.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityAlertDetail.tsxindex 4418bb9cac..8a83e1a21c 100644--- a/frontend/src/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityAlertDetail.tsx+++ b/frontend/src/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityAlertDetail.tsx@@ -36,14 +36,11 @@ type Props = {readOnly?: boolean;};-const TIME_UNIT_WORD: Record<string, string> = { d: "day", w: "week", m: "month", y: "year" };-const formatCondition = (alertBefore?: string): string => {- const match = alertBefore?.match(/^(\d+)([dwmy])$/);+ const match = alertBefore?.match(/^(\d+)d$/);if (!match) return "";- const amount = parseInt(match[1], 10);- const word = TIME_UNIT_WORD[match[2]] ?? match[2];- return `alert ${amount} ${word}${amount === 1 ? "" : "s"} before`;+ const days = parseInt(match[1], 10);+ return `alert ${days} day${days === 1 ? "" : "s"} before`;};export const ProjectIdentityAlertDetail = ({diff --git a/frontend/src/views/AlertsPage/components/AlertForm.tsx b/frontend/src/views/AlertsPage/components/AlertForm.tsxindex 1dc4c7939b..a3356bd4ee 100644--- a/frontend/src/views/AlertsPage/components/AlertForm.tsx+++ b/frontend/src/views/AlertsPage/components/AlertForm.tsx@@ -32,12 +32,12 @@ import { useScopeVariant } from "@app/hooks";import {ALERT_EVENT_TYPE_LABELS,ALERT_RESOURCE_TYPE_LABELS,- ALERT_TIME_UNIT_LABELS,AlertChannelType,AlertEventType,alertFormSchema,AlertResourceType,- AlertTimeUnit,+ MAX_ALERT_BEFORE_DAYS,+ MIN_ALERT_BEFORE_DAYS,TAlert,TAlertChannelInput,TAlertForm,@@ -71,10 +71,11 @@ const FixedField = ({ label, children }: { label: string; children: ReactNode })</div>);-const parseAlertBefore = (alertBefore?: string): { value: number; unit: AlertTimeUnit } => {- const match = alertBefore?.match(/^(\d+)([dwmy])$/);- if (match) return { value: parseInt(match[1], 10), unit: match[2] as AlertTimeUnit };- return { value: 7, unit: AlertTimeUnit.Days };+const DEFAULT_ALERT_BEFORE_DAYS = 7;++const parseAlertBeforeDays = (alertBefore?: string): number => {+ const match = alertBefore?.match(/^(\d+)d$/);+ return match ? parseInt(match[1], 10) : DEFAULT_ALERT_BEFORE_DAYS;};const toChannelForm = (channel: TAlert["channels"][number]): TChannelForm => ({@@ -99,24 +100,20 @@ const buildFormDefaults = (alert?: TAlert): TAlertForm => {description: "",resourceType: AlertResourceType.IdentityAuthentication,eventType: AlertEventType.IdentityAuthenticationExpiry,- alertBeforeValue: 7,- alertBeforeUnit: AlertTimeUnit.Days,+ alertBeforeDays: DEFAULT_ALERT_BEFORE_DAYS,dailyReminder: false,enabled: true,channels: []};}- const { value, unit } = parseAlertBefore(alert.condition?.alertBefore);-return {name: alert.name,description: alert.description ?? "",resourceType:(alert.resourceType as AlertResourceType) ?? AlertResourceType.IdentityAuthentication,eventType: (alert.eventType as AlertEventType) ?? AlertEventType.IdentityAuthenticationExpiry,- alertBeforeValue: value,- alertBeforeUnit: unit,+ alertBeforeDays: parseAlertBeforeDays(alert.condition?.alertBefore),dailyReminder: alert.condition?.dailyReminder ?? false,enabled: alert.enabled,channels: alert.channels.map(toChannelForm)@@ -209,8 +206,10 @@ export const AlertForm = ({: "Watches every machine identity authentication in this organization";const onSubmit = async (data: TAlertForm) => {- const alertBefore = `${data.alertBeforeValue}${data.alertBeforeUnit}`;- const condition = { alertBefore, dailyReminder: data.dailyReminder };+ const condition = {+ alertBefore: `${data.alertBeforeDays}d`,+ dailyReminder: data.dailyReminder+ };const channels = data.channels.map(toChannelInput);try {if (isEditing && alert) {@@ -250,6 +249,7 @@ export const AlertForm = ({<FormProvider {...formMethods}><formonSubmit={handleSubmit(onSubmit)}+ noValidateclassName="flex min-h-0 flex-1 flex-col overflow-y-auto"><div className="flex flex-col gap-8 p-4">@@ -261,7 +261,7 @@ export const AlertForm = ({<Inputid="alert-name"autoFocus- placeholder="ci-bot-secret-expiry"+ placeholder="Secret Expiration Alert"isError={Boolean(errors.name)}{...register("name")}/>@@ -354,37 +354,27 @@ export const AlertForm = ({/><div className="flex flex-col gap-1.5">- <FieldLabel>Alert before</FieldLabel>- <div className="flex flex-col gap-1">- <div className="flex items-center gap-3">- <Input- id="alert-alert-before"- type="number"- min={1}- className="w-24"- isError={Boolean(errors.alertBeforeValue)}- {...register("alertBeforeValue", { valueAsNumber: true })}- />- <Controller- control={control}- name="alertBeforeUnit"- render={({ field: { value, onChange } }) => (- <Select value={value} onValueChange={onChange}>- <SelectTrigger className="w-32">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- {Object.values(AlertTimeUnit).map((unit) => (- <SelectItem key={unit} value={unit}>- {ALERT_TIME_UNIT_LABELS[unit]}- </SelectItem>- ))}- </SelectContent>- </Select>- )}- />- </div>- <FieldError errors={[errors.alertBeforeValue, errors.alertBeforeUnit]} />+ <FieldLabel htmlFor="alert-alert-before">Condition</FieldLabel>+ <div className="grid grid-cols-[auto_auto_1fr] items-center gap-x-3 gap-y-1 text-sm text-muted">+ <span>Alert me</span>+ <Input+ id="alert-alert-before"+ type="number"+ min={MIN_ALERT_BEFORE_DAYS}+ max={MAX_ALERT_BEFORE_DAYS}+ className="w-20 text-center"+ isError={Boolean(errors.alertBeforeDays)}+ {...register("alertBeforeDays", { valueAsNumber: true })}+ />+ <span>days before the credential expires. (1-90)</span>+ {errors.alertBeforeDays && (+ <div className="col-start-2 flex w-0 justify-self-center">+ <FieldError+ errors={[errors.alertBeforeDays]}+ className="shrink-0 -translate-x-1/2 whitespace-nowrap"+ />+ </div>+ )}</div></div>