Skip to content

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

Greptile comment fixes

Carlos Monastyrski7b5cb3859e8d
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 30f1a4603e..ccc8bceb7e 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -710,7 +710,7 @@ Invariants worth knowing before extending it:
- **One alert per `(scope, resource, event)` for resource-bound alerts**, enforced by the partial `alert_unique_scope_resource_event_bound` index. A provider that sets `supportsScopeWideAlerts` also accepts alerts with no `resourceId`: such an alert watches every resource of its type in scope (`findEnabledForEvent` matches it for any `resourceId`), several can watch the same event because they differ by condition, and `assertConditionInScope` is where the provider checks the IDs inside a condition, on create and on update (newly added IDs only). Certificate Manager-wide alerts are `cert-manager.application` alerts with no `resourceId`, narrowed by `applicationIds` and `profileIds`; creating or editing one requires unconditional certificate read, since it sends details from every application. **Every provider hook is opt-in, and its absence must reproduce the behaviour identity alerts had before any other provider existed.** `recipientPolicy` decides who can receive: `atOrgScope` validates and resolves user and group recipients against the org instead of the alert's project, and `allowEmailAddresses` accepts plain `EMAIL` recipients and makes test sends validate recipients like create and update do, instead of silently dropping out-of-scope ones (application alerts set both). `includeLastRun` adds `lastRun` to alert responses, and `resourceName` is only returned by providers that implement `getResourceNames`, and `filters` (read-only `{ id, name }` lists for the IDs inside a condition, keyed by kind, such as `applications` and `profiles` on a Certificate Manager-wide alert, with a null name for deleted IDs, matching how approval policies return approvers) only by providers that implement `getFilters`. Resolve such names there rather than adding ID filters to another domain's list endpoint. `assertChannelTypesAllowed` is where a provider gates paid channel types on create and on update (new, retyped, or re-enabled channels only, so a downgraded org can still edit the alert). `getResourceNames` (batched) supplies the resource's display name for alert responses and for a provider's own audit events. `resolveProjectId` lets create, list and test sends omit `projectId` when the resource already belongs to one project (`resolveAlertProjectId` in `alert-provider-registry.ts`). `getTelemetryEvent` lets a provider map alert create, update and delete to its own PostHog event, so the shared router never branches on a resource type. `getAuditEvent` does the same for audit logs: a provider that needs distinct event types (application alerts log `create-pki-application-alert` and its siblings, with the application's ID and name) returns its own event, and every other provider falls back to the generic `create-alert` family via `buildGenericAlertAuditEvent`. Add a provider's own event interfaces next to the generic ones; never widen the generic ones. The deprecated `pki/alerts` and `applications/:applicationId/alerts` routes only serve legacy PKI Alerts V2 rows. Add features to `/api/v1/alerts`, not to them.
- **Email channels accept plain addresses as `EMAIL` recipients when the provider opts in** (`recipientPolicy.allowEmailAddresses`), with the address as `principalId`, besides users and groups. Every address must be on one of the org's verified email domains, checked on create, update and test sends (`alert-channel-service.ts`), and again at send time, so an address on a domain the org has since removed stops receiving alerts. The resolver sends to them directly and skips an address that a user recipient on the same channel already covers.
- **`findScheduledTargets` must return most-urgent-first.** The engine's per-channel `maxTargetsPerRun` cap keeps the head of the list and defers the tail, so ordering is what guarantees the closest-to-expiry targets are never the dropped ones.
-- **A `findScheduledTargets` that caps its own row count must honour `alreadyAlerted`.** The engine passes `{ alertId, channelIds, since }` (the alert's enabled channels and its dedup cutoff), and the provider drops targets every one of those channels already delivered since then, in SQL before the limit. Dedup otherwise runs after the fetch, so once more targets are due than the cap, the same head of the list comes back every run, is deduped, and nothing past it is ever alerted. The certificate alert DAL does this in `findExpiringCertificates`.
+- **A `findScheduledTargets` that caps its own row count must honour `alreadyAlerted`.** The engine passes `{ alertId, channelIds, since }` (the alert's enabled channels and its dedup cutoff), and the provider drops targets every one of those channels already delivered since then, in SQL before the limit. Dedup otherwise runs after the fetch, so once more targets are due than the cap, the same head of the list comes back every run, is deduped, and nothing past it is ever alerted. That filter alone is not enough when the dedup window is shorter than the scan interval (a daily reminder), because yesterday's head is due again, so such a provider also orders the targets this alert notified least recently first, then by expiry. The certificate alert DAL does both in `findExpiringCertificates`.
- **Deleting an alertable resource does NOT delete its alerts. You have to reap them yourself.** `alerts.resourceId` is a plain string column with **no foreign key** to the resource's table (a provider's `resourceType` can point at anything), so nothing cascades. Skip the reap and the row survives as a dangling alert whose `findScheduledTargets` matches nothing and whose "view" link 404s. Two helpers on `alertService`, and picking the wrong one is the bug:
- **`deleteAlertsForDeletedResource({ resourceType, resourceId })`** when the resource **row is gone**. It has **no scope filter** and reaps across every org and project. This is required, not just tidier: the same resource can be watched from another org (a root-org identity invited into a child org), so an `orgId`-filtered reap leaves those rows orphaned.
- **`deleteAlertsForResource({ orgId, projectId?, resourceType, resourceId })`** when the resource merely **left a scope** (removed from a project, removed from an org) but still exists. Narrow on purpose: leaving one project must not drop the org-level alert, and leaving one org must not touch another org's alerts. Omitting `projectId` reaps the whole org, which is what org-membership removal wants since it cascades the project memberships.
diff --git a/backend/src/server/routes/v1/alert-router.ts b/backend/src/server/routes/v1/alert-router.ts
index b20b9c4aa3..5ae83a53d2 100644
--- a/backend/src/server/routes/v1/alert-router.ts
+++ b/backend/src/server/routes/v1/alert-router.ts
@@ -99,7 +99,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
name: z.string().min(1).max(255).describe(ALERTING.name),
description: z.string().max(1000).optional().describe(ALERTING.description),
resourceType: z.string().min(1).describe(ALERTING.resourceType),
- resourceId: z.string().nullable().optional().describe(ALERTING.resourceId),
+ resourceId: z.string().uuid().nullable().optional().describe(ALERTING.resourceId),
eventType: z.string().min(1).describe(ALERTING.eventType),
condition: z.unknown().optional().describe(ALERTING.condition),
enabled: z.boolean().optional().describe(ALERTING.enabled),
@@ -139,7 +139,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
description: ALERTING.ROUTES.testChannel,
body: z.object({
resourceType: z.string().min(1).describe(ALERTING.resourceType),
- resourceId: z.string().nullable().optional().describe(ALERTING.resourceId),
+ resourceId: z.string().uuid().nullable().optional().describe(ALERTING.resourceId),
projectId: z.string().nullable().optional().describe(ALERTING.projectId),
alertId: z.string().uuid().optional().describe(ALERTING.alertId),
channelId: z.string().uuid().optional().describe(ALERTING.channelId),
@@ -200,7 +200,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
description: ALERTING.ROUTES.list,
querystring: z.object({
resourceType: z.string().min(1).describe(ALERTING.resourceType),
- resourceId: z.string().optional().describe(ALERTING.listResourceId),
+ resourceId: z.string().uuid().optional().describe(ALERTING.listResourceId),
projectId: z.string().optional().describe(ALERTING.projectId),
enabled: z
.enum(["true", "false"])
diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.ts
index 13f659f804..4399b13169 100644
--- a/backend/src/services/alert/alert-types.ts
+++ b/backend/src/services/alert/alert-types.ts
@@ -190,7 +190,9 @@ export interface IResourceAlertProvider<TTarget = unknown> {
// afterwards, so this returns all current matches in the window (not minus already-alerted).
// Must be ordered most-urgent-first (soonest expiry): the engine's per-channel maxTargetsPerRun cap
// keeps the head of this list and defers the tail, so urgency ordering ensures the targets closest
- // to expiry are never the ones dropped.
+ // to expiry are never the ones dropped. A provider that caps its own row count puts the targets this
+ // alert notified least recently ahead of that, so a cap below the due count rotates instead of
+ // re-sending the same head every run.
// Required for any Scheduled event; the registry enforces that at boot.
findScheduledTargets?(input: TFindScheduledTargetsInput): Promise<TTarget[]>;
diff --git a/backend/src/services/alert/providers/cert-manager-application-alert-dal.test.ts b/backend/src/services/alert/providers/cert-manager-application-alert-dal.test.ts
index 9b47491ec4..60900b1546 100644
--- a/backend/src/services/alert/providers/cert-manager-application-alert-dal.test.ts
+++ b/backend/src/services/alert/providers/cert-manager-application-alert-dal.test.ts
@@ -69,6 +69,8 @@ describe("cert manager certificate alert DAL", () => {
expect(sql).toContain('count(distinct "tgt"."channelId")');
expect(sql).toContain('"tgt"."targetId" = "certificates".id::text');
expect(sql.indexOf("count(distinct")).toBeLessThan(sql.indexOf("limit"));
+ expect(sql).toContain('max("lastHist"."triggeredAt")');
+ expect(sql.indexOf("asc nulls first")).toBeLessThan(sql.indexOf('"certificates"."notAfter" asc'));
expect(bindings).toEqual(expect.arrayContaining(["alert-1", since, "success", "channel-1", "channel-2", 2]));
});
diff --git a/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts b/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts
index 79788b6d78..0a58d9546c 100644
--- a/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts
+++ b/backend/src/services/alert/providers/cert-manager-application-alert-dal.ts
@@ -93,6 +93,14 @@ export const certManagerApplicationAlertDALFactory = (db: TDbClient) => {
.whereRaw(`"tgt"."targetId" = "${TableName.Certificate}".id::text`)
.countDistinct("tgt.channelId");
void query.whereRaw("(?) < ?", [deliveredChannelCount, alreadyAlerted.channelIds.length]);
+
+ const lastDeliveredAt = reader(`${TableName.AlertHistory} as lastHist`)
+ .join(`${TableName.AlertHistoryTarget} as lastTgt`, "lastHist.id", "lastTgt.alertHistoryId")
+ .where("lastHist.alertId", alreadyAlerted.alertId)
+ .where("lastTgt.status", AlertRunStatus.SUCCESS)
+ .whereRaw(`"lastTgt"."targetId" = "${TableName.Certificate}".id::text`)
+ .max("lastHist.triggeredAt");
+ void query.orderByRaw("(?) asc nulls first", [lastDeliveredAt]);
}
const certificates = (await query