Skip to content

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

fix review comments

Thiago Araujo da Silva2f817fde49ec
diff --git a/backend/src/server/routes/v1/alert-router.ts b/backend/src/server/routes/v1/alert-router.ts
index 0eea80ddac..72200c3986 100644
--- a/backend/src/server/routes/v1/alert-router.ts
+++ b/backend/src/server/routes/v1/alert-router.ts
@@ -3,7 +3,11 @@ import { z } from "zod";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AlertChannelType } from "@app/services/alert/alert-channel-types";
-import { AlertPrincipalType } from "@app/services/alert/alert-types";
+import {
+ AlertPrincipalType,
+ MAX_CHANNELS_PER_ALERT,
+ MAX_RECIPIENTS_PER_CHANNEL
+} from "@app/services/alert/alert-types";
import { AuthMode } from "@app/services/auth/auth-type";
const ChannelRecipientSchema = z.object({
@@ -16,7 +20,7 @@ const CreateChannelInputSchema = z.object({
channelType: z.nativeEnum(AlertChannelType),
config: z.record(z.unknown()).default({}),
enabled: z.boolean().optional(),
- recipients: z.array(ChannelRecipientSchema).optional()
+ recipients: z.array(ChannelRecipientSchema).max(MAX_RECIPIENTS_PER_CHANNEL).optional()
});
const UpdateChannelInputSchema = z.object({
@@ -25,7 +29,7 @@ const UpdateChannelInputSchema = z.object({
channelType: z.nativeEnum(AlertChannelType),
config: z.record(z.unknown()).optional(),
enabled: z.boolean().optional(),
- recipients: z.array(ChannelRecipientSchema).optional()
+ recipients: z.array(ChannelRecipientSchema).max(MAX_RECIPIENTS_PER_CHANNEL).optional()
});
const AlertResponseSchema = z.object({
@@ -70,7 +74,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
condition: z.unknown().optional(),
enabled: z.boolean().optional(),
projectId: z.string().nullable().optional(),
- channels: z.array(CreateChannelInputSchema).min(1)
+ channels: z.array(CreateChannelInputSchema).min(1).max(MAX_CHANNELS_PER_ALERT)
}),
response: { 200: z.object({ alert: AlertResponseSchema }) }
},
@@ -151,7 +155,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
description: z.string().max(1000).nullable().optional(),
condition: z.unknown().optional(),
enabled: z.boolean().optional(),
- channels: z.array(UpdateChannelInputSchema).min(1).optional()
+ channels: z.array(UpdateChannelInputSchema).min(1).max(MAX_CHANNELS_PER_ALERT).optional()
}),
response: { 200: z.object({ alert: AlertResponseSchema }) }
},
diff --git a/backend/src/services/alert/alert-engine.test.ts b/backend/src/services/alert/alert-engine.test.ts
index 1aebdb8a2f..08b7bea7d8 100644
--- a/backend/src/services/alert/alert-engine.test.ts
+++ b/backend/src/services/alert/alert-engine.test.ts
@@ -91,6 +91,11 @@ const buildEngine = (opts: {
const sentMail: Array<{ recipients: string[] }> = [];
const historyWrites: Array<{ deliveries: TDelivery[]; status: string }> = [];
+ // Tracks the peak number of overlapping sendMail calls so a test can assert the
+ // run-wide delivery concurrency stays bounded. sendMail yields a macrotask before
+ // resolving so concurrent sends genuinely overlap.
+ let inFlightSends = 0;
+ let peakConcurrentSends = 0;
const engine = alertEngineFactory({
alertChannelDAL: {
@@ -126,14 +131,23 @@ const buildEngine = (opts: {
kmsService: kmsServiceMock,
smtpService: {
sendMail: async (opt: { recipients: string[] }) => {
- if (opts.failEmail) throw new Error("smtp down");
- if (opts.failEmailFor && opt.recipients.includes(opts.failEmailFor)) throw new Error("mailbox unavailable");
- sentMail.push({ recipients: opt.recipients });
+ inFlightSends += 1;
+ peakConcurrentSends = Math.max(peakConcurrentSends, inFlightSends);
+ try {
+ await new Promise((resolve) => {
+ setTimeout(resolve, 2);
+ });
+ if (opts.failEmail) throw new Error("smtp down");
+ if (opts.failEmailFor && opt.recipients.includes(opts.failEmailFor)) throw new Error("mailbox unavailable");
+ sentMail.push({ recipients: opt.recipients });
+ } finally {
+ inFlightSends -= 1;
+ }
}
}
} as unknown as TAlertEngineDep);
- return { engine, sentMail, historyWrites };
+ return { engine, sentMail, historyWrites, getPeakConcurrentSends: () => peakConcurrentSends };
};
describe("alert engine", () => {
@@ -303,6 +317,26 @@ describe("alert engine", () => {
expect(historyWrites).toHaveLength(0);
});
+ test("bounds concurrent deliveries across the whole run with one shared limiter, not per channel", async () => {
+ // 5 directed channels x 20 recipients = 100 sends. A per-channel limiter would allow
+ // up to 5 x 10 = 50 in flight; the shared run-wide limiter must keep the peak <= 10.
+ const channels = Array.from({ length: 5 }, (_, i) => ({
+ id: `c-email-${i}`,
+ channelType: "email",
+ encryptedConfig: encConfig({}),
+ enabled: true
+ }));
+ const recipients = Array.from({ length: 20 }, (_, i) => ({ userId: `u${i}`, email: `u${i}@example.com` }));
+ const { engine, sentMail, getPeakConcurrentSends } = buildEngine({ targets: [{ id: "t1" }], channels, recipients });
+
+ await engine.runAlert(makeAlert());
+
+ expect(sentMail).toHaveLength(100);
+ expect(getPeakConcurrentSends()).toBeLessThanOrEqual(10);
+ // Sanity: sends actually overlapped, so the assertion above is meaningful.
+ expect(getPeakConcurrentSends()).toBeGreaterThan(1);
+ });
+
test("writes no history when there are no enabled channels", async () => {
const { engine, historyWrites } = buildEngine({
targets: [{ id: "t1" }],
diff --git a/backend/src/services/alert/alert-engine.ts b/backend/src/services/alert/alert-engine.ts
index a05725a736..44e2441f8d 100644
--- a/backend/src/services/alert/alert-engine.ts
+++ b/backend/src/services/alert/alert-engine.ts
@@ -15,7 +15,7 @@ import { TAlertRecipientResolver } from "./alert-recipient-resolver";
import { AlertRunStatus, DEFAULT_DEDUP_WINDOW_HOURS, TAlertContext } from "./alert-types";
import { ALERT_CHANNEL_REGISTRY } from "./channels/alert-channel-registry";
-const RECIPIENT_SEND_CONCURRENCY = 10;
+const ALERT_DELIVERY_CONCURRENCY = 10;
export type TAlertEngineDep = {
alertChannelDAL: Pick<TAlertChannelDALFactory, "findByAlertId">;
@@ -115,6 +115,8 @@ export const alertEngineFactory = ({
const deps: TAlertChannelDeps = { smtpService };
+ const sendLimit = pLimit(ALERT_DELIVERY_CONCURRENCY);
+
const channelResults = await Promise.all(
channelWork.map(async ({ channel, dueTargets }) => {
const targetIds = dueTargets.map((target) => provider.targetId(target));
@@ -138,7 +140,6 @@ export const alertEngineFactory = ({
if (recipients.length === 0) {
return { ...base, success: false, error: "No recipients could be resolved for this channel" };
}
- const sendLimit = pLimit(RECIPIENT_SEND_CONCURRENCY);
const results = await Promise.all(
recipients.map((recipient) =>
sendLimit(() => definition.send({ channelId: channel.id, config, payload, recipient, deps }))
@@ -158,7 +159,7 @@ export const alertEngineFactory = ({
return { ...base, success: true };
}
- const result = await definition.send({ channelId: channel.id, config, payload, deps });
+ const result = await sendLimit(() => definition.send({ channelId: channel.id, config, payload, deps }));
return { ...base, ...result };
} catch (err) {
const error = err instanceof Error ? err.message : "Unknown error";
diff --git a/backend/src/services/alert/alert-history-dal.test.ts b/backend/src/services/alert/alert-history-dal.test.ts
index 7937709e5b..33360ff6fd 100644
--- a/backend/src/services/alert/alert-history-dal.test.ts
+++ b/backend/src/services/alert/alert-history-dal.test.ts
@@ -18,7 +18,9 @@ const buildDAL = () => {
select: async () => [] as Array<{ channelId: string; targetId: string }>
};
const queryBuilder = () => chain;
- const db = { replicaNode: () => queryBuilder } as never;
+ // The dedup read runs against the primary (see alert-history-dal.ts), so `db`
+ // itself must be callable; replicaNode is kept for completeness.
+ const db = Object.assign(queryBuilder, { replicaNode: () => queryBuilder }) as never;
return { dal: alertHistoryDALFactory(db), whereCalls };
};
diff --git a/backend/src/services/alert/alert-history-dal.ts b/backend/src/services/alert/alert-history-dal.ts
index e55ade2024..479e2bc7f5 100644
--- a/backend/src/services/alert/alert-history-dal.ts
+++ b/backend/src/services/alert/alert-history-dal.ts
@@ -65,7 +65,7 @@ export const alertHistoryDALFactory = (db: TDbClient) => {
cutoffDate.setHours(cutoffDate.getHours() - withinHours);
cutoffDate.setMinutes(cutoffDate.getMinutes() - DEDUP_DRIFT_BUFFER_MINUTES);
- const rows = (await (tx || db.replicaNode())(`${TableName.AlertHistory} as hist`)
+ const rows = (await (tx || db)(`${TableName.AlertHistory} as hist`)
.join(`${TableName.AlertHistoryTarget} as tgt`, "hist.id", "tgt.alertHistoryId")
.where("hist.alertId", alertId)
.where("hist.triggeredAt", ">=", cutoffDate)
diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.ts
index 7a8f481ac2..1069016ee9 100644
--- a/backend/src/services/alert/alert-types.ts
+++ b/backend/src/services/alert/alert-types.ts
@@ -36,6 +36,9 @@ export type TAlertPermissionInput = {
export const DEFAULT_DEDUP_WINDOW_HOURS = 24;
+export const MAX_CHANNELS_PER_ALERT = 10;
+export const MAX_RECIPIENTS_PER_CHANNEL = 20;
+
export type TAlertContext = {
id: string;
name: string;
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.ts
index cb708091d7..176f872cf4 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
@@ -45,7 +45,7 @@ const buildProvider = (opts?: {
identityId?: string | null;
alertBeforeInterval: string;
}) => void;
- abilityRules?: { action: string; subject: string }[];
+ abilityRules?: { action: string; subject: string; conditions?: Record<string, unknown> }[];
inOrg?: boolean;
inProject?: boolean;
projectType?: string | null;
@@ -210,6 +210,53 @@ describe("identity credential alert provider", () => {
).rejects.toThrow();
});
+ test("assertPermission passes identityId into the subject for resource-bound project alerts", async () => {
+ // Custom role / additional privilege scoped to a single identity. The check must
+ // supply the identity id so CASL can match the conditioned rule; a bare subject
+ // would be rejected.
+ const provider = buildProvider({
+ abilityRules: [{ action: "edit", subject: "identity", conditions: { identityId: "ident-1" } }]
+ });
+ await expect(
+ provider.assertPermission({
+ action: AlertPermissionAction.Edit,
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceId: "ident-1",
+ actor
+ })
+ ).resolves.toBeUndefined();
+ // A different identity must not satisfy the identity-scoped rule.
+ await expect(
+ provider.assertPermission({
+ action: AlertPermissionAction.Edit,
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceId: "ident-2",
+ actor
+ })
+ ).rejects.toThrow();
+ });
+
+ test("assertPermission rejects a filter-based project alert when the actor only has a conditional identity grant", async () => {
+ // The actor can edit exactly one identity. A filter-based alert (no resourceId) fans
+ // out data for every matching identity, so a conditional grant must NOT authorize it
+ // even though the bare subject check would otherwise pass.
+ const provider = buildProvider({
+ abilityRules: [{ action: "edit", subject: "identity", conditions: { identityId: "ident-1" } }]
+ });
+ await expect(
+ provider.assertPermission({ action: AlertPermissionAction.Edit, orgId: "org-1", projectId: "proj-1", actor })
+ ).rejects.toThrow();
+ });
+
+ test("assertPermission allows a filter-based project alert with an unconditional project-wide identity grant", async () => {
+ const provider = buildProvider({ abilityRules: [{ action: "edit", subject: "identity" }] });
+ await expect(
+ provider.assertPermission({ action: AlertPermissionAction.Edit, orgId: "org-1", projectId: "proj-1", actor })
+ ).resolves.toBeUndefined();
+ });
+
test("assertResourceInScope no-ops when there is no resource (filter-based alert)", async () => {
const provider = buildProvider({ inOrg: false });
// inOrg=false would reject if checked, but with no resourceId it must return without checking.
diff --git a/backend/src/services/alert/providers/identity-credential-alert-provider.ts b/backend/src/services/alert/providers/identity-credential-alert-provider.ts
index ff14aad5b7..fbe34d0c2e 100644
--- a/backend/src/services/alert/providers/identity-credential-alert-provider.ts
+++ b/backend/src/services/alert/providers/identity-credential-alert-provider.ts
@@ -1,4 +1,4 @@
-import { ForbiddenError } from "@casl/ability";
+import { ForbiddenError, subject } from "@casl/ability";
import RE2 from "re2";
import { z } from "zod";
@@ -7,7 +7,7 @@ import { OrgPermissionIdentityActions, OrgPermissionSubjects } from "@app/ee/ser
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
import { getConfig } from "@app/lib/config/env";
-import { NotFoundError } from "@app/lib/errors";
+import { ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { TAlertPayload, TAlertSeverity } from "../alert-channel-types";
import {
@@ -199,10 +199,26 @@ export const identityCredentialAlertProviderFactory = ({
actorOrgId: input.actor.actorOrgId,
actionProjectType: ActionProjectType.Any
});
- ForbiddenError.from(permission).throwUnlessCan(
- isRead ? ProjectPermissionIdentityActions.Read : ProjectPermissionIdentityActions.Edit,
- ProjectPermissionSub.Identity
- );
+ const action = isRead ? ProjectPermissionIdentityActions.Read : ProjectPermissionIdentityActions.Edit;
+
+ if (input.resourceId) {
+ ForbiddenError.from(permission).throwUnlessCan(
+ action,
+ subject(ProjectPermissionSub.Identity, { identityId: input.resourceId })
+ );
+ return;
+ }
+
+ ForbiddenError.from(permission).throwUnlessCan(action, ProjectPermissionSub.Identity);
+ const hasProjectWideGrant = permission
+ .rulesFor(action, ProjectPermissionSub.Identity)
+ .some((rule) => !rule.inverted && !rule.conditions);
+ if (!hasProjectWideGrant) {
+ throw new ForbiddenRequestError({
+ message:
+ "Project-wide identity permission is required to manage an alert that is not bound to a specific identity"
+ });
+ }
return;
}