Skip to content

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

Greptile comments fixes

Carlos Monastyrski256e221558fa
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index bb7058a5ab..1823629bd1 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1083,7 +1083,8 @@ export const registerRoutes = async (
userDAL,
userGroupMembershipDAL,
orgDAL,
- projectDAL
+ projectDAL,
+ emailDomainDAL
});
const alertEngine = alertEngineFactory({
alertChannelDAL,
diff --git a/backend/src/server/routes/v1/alert-router.ts b/backend/src/server/routes/v1/alert-router.ts
index fadc63925c..1d922b4096 100644
--- a/backend/src/server/routes/v1/alert-router.ts
+++ b/backend/src/server/routes/v1/alert-router.ts
@@ -156,7 +156,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
handler: async (req) => {
- const result = await server.services.alertChannelTest.testChannel({
+ const { projectId, ...result } = await server.services.alertChannelTest.testChannel({
...req.body,
actor: req.permission.type,
actorId: req.permission.id,
@@ -166,7 +166,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- ...(req.body.projectId ? { projectId: req.body.projectId } : { orgId: req.permission.orgId }),
+ ...(projectId ? { projectId } : { orgId: req.permission.orgId }),
event: {
type: EventType.TEST_ALERT_CHANNEL,
metadata: {
diff --git a/backend/src/services/alert/alert-channel-service.ts b/backend/src/services/alert/alert-channel-service.ts
index 0acd6815ed..a56d38e0e2 100644
--- a/backend/src/services/alert/alert-channel-service.ts
+++ b/backend/src/services/alert/alert-channel-service.ts
@@ -3,7 +3,6 @@ import { z } from "zod";
import { TAlertChannels } from "@app/db/schemas";
import { TEmailDomainDALFactory } from "@app/ee/services/email-domain/email-domain-dal";
-import { EmailDomainStatus } from "@app/ee/services/email-domain/email-domain-types";
import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
import { BadRequestError } from "@app/lib/errors";
import { TOrgDALFactory } from "@app/services/org/org-dal";
@@ -24,7 +23,7 @@ import { TAlertChannelDALFactory } from "./alert-channel-dal";
import { TAlertChannelRecipientDALFactory } from "./alert-channel-recipient-dal";
import { TAlertChannelEmbedded, TChannelRecipientInput } from "./alert-channel-service-types";
import { AlertChannelType } from "./alert-channel-types";
-import { resolvePrincipalsInScope } from "./alert-principal-scope-fns";
+import { findVerifiedEmailDomains, isOnVerifiedDomain, resolvePrincipalsInScope } from "./alert-principal-scope-fns";
import { AlertPrincipalType } from "./alert-types";
import { ALERT_CHANNEL_REGISTRY } from "./channels/alert-channel-registry";
@@ -100,12 +99,8 @@ export const alertChannelServiceFactory = ({
throw new BadRequestError({ message: `Invalid email recipients: ${malformed.join(", ")}` });
}
- const verifiedDomains = new Set(
- (await emailDomainDAL.find({ orgId, status: EmailDomainStatus.Verified }, { tx })).map((domain) =>
- domain.domain.toLowerCase()
- )
- );
- const unverified = emails.filter((email) => !verifiedDomains.has(email.split("@")[1]));
+ const verifiedDomains = await findVerifiedEmailDomains(emailDomainDAL, orgId, tx);
+ const unverified = emails.filter((email) => !isOnVerifiedDomain(email, verifiedDomains));
if (unverified.length) {
throw new BadRequestError({
message: `Email recipients must use one of your organization's verified domains (Organization Settings > SSO > Email Domains). Not on a verified domain: ${unverified.join(", ")}`
diff --git a/backend/src/services/alert/alert-channel-test-service.test.ts b/backend/src/services/alert/alert-channel-test-service.test.ts
index 276189c822..5c339eb6df 100644
--- a/backend/src/services/alert/alert-channel-test-service.test.ts
+++ b/backend/src/services/alert/alert-channel-test-service.test.ts
@@ -32,6 +32,7 @@ const actor = {
const buildProvider = (opts?: {
assertPermission?: (input: TAlertPermissionInput) => Promise<void>;
resolvedProjectId?: string;
+ blockedChannelTypes?: string[];
}) => {
const provider: IResourceAlertProvider = {
resourceType: RESOURCE_TYPE,
@@ -61,6 +62,10 @@ const buildProvider = (opts?: {
if (opts?.assertPermission) await opts.assertPermission(input);
},
assertResourceInScope: async () => {},
+ assertChannelTypesAllowed: async ({ channelTypes }) => {
+ const blocked = channelTypes.find((channelType) => opts?.blockedChannelTypes?.includes(channelType));
+ if (blocked) throw new Error(`plan does not include ${blocked}`);
+ },
...(opts?.resolvedProjectId ? { resolveProjectId: async () => opts.resolvedProjectId as string } : {})
};
@@ -156,7 +161,7 @@ describe("alertChannelTestService", () => {
config: { webhookUrl: "https://hooks.slack.com/services/T/B/x" }
});
- expect(result).toEqual({ success: true, deliveredTo: 1 });
+ expect(result).toEqual({ success: true, deliveredTo: 1, projectId: null });
expect(sent).toHaveLength(1);
expect(sent[0].config).toEqual({ webhookUrl: "https://hooks.slack.com/services/T/B/x" });
// A test must never page an on-call rotation at the severity a real firing would carry.
@@ -186,7 +191,7 @@ describe("alertChannelTestService", () => {
});
const service = alertChannelTestServiceFactory(deps);
- await service.testChannel({
+ const result = await service.testChannel({
...actor,
resourceType: RESOURCE_TYPE,
resourceId: "resource-1",
@@ -195,6 +200,26 @@ describe("alertChannelTestService", () => {
});
expect(permissionInputs[0]?.projectId).toBe("proj-resolved");
+ expect(result.projectId).toBe("proj-resolved");
+ } finally {
+ restore();
+ }
+ });
+
+ test("applies the provider's plan gate to a new channel config", async () => {
+ const restore = stubSend("slack", async () => ({ success: true }));
+ try {
+ const { deps } = buildDeps({ registry: buildProvider({ blockedChannelTypes: ["slack"] }) });
+ const service = alertChannelTestServiceFactory(deps);
+
+ await expect(
+ service.testChannel({
+ ...actor,
+ resourceType: RESOURCE_TYPE,
+ channelType: "slack" as never,
+ config: { webhookUrl: "https://hooks.slack.com/services/T/B/x" }
+ })
+ ).rejects.toThrow("plan does not include slack");
} finally {
restore();
}
@@ -348,7 +373,7 @@ describe("alertChannelTestService", () => {
config: { webhookUrl: "https://hooks.slack.com/services/T/B/x" }
};
- await expect(service.testChannel(dto)).resolves.toEqual({ success: true, deliveredTo: 1 });
+ await expect(service.testChannel(dto)).resolves.toEqual({ success: true, deliveredTo: 1, projectId: null });
await expect(service.testChannel(dto)).rejects.toThrow(/Try again in 60s/);
} finally {
restore();
@@ -378,7 +403,7 @@ describe("alertChannelTestService", () => {
config: {},
recipients: [{ principalType: "user" as never, principalId: "user-1" }]
})
- ).resolves.toEqual({ success: true, deliveredTo: 1 });
+ ).resolves.toEqual({ success: true, deliveredTo: 1, projectId: null });
} finally {
restoreSlack();
restoreEmail();
@@ -401,7 +426,7 @@ describe("alertChannelTestService", () => {
config: { webhookUrl: "https://hooks.slack.com/services/T/B/x" }
});
- expect(result).toEqual({ success: false, error: "connect ECONNREFUSED" });
+ expect(result).toEqual({ success: false, error: "connect ECONNREFUSED", projectId: null });
} finally {
restore();
}
diff --git a/backend/src/services/alert/alert-channel-test-service.ts b/backend/src/services/alert/alert-channel-test-service.ts
index efe307f894..f990e1bb1a 100644
--- a/backend/src/services/alert/alert-channel-test-service.ts
+++ b/backend/src/services/alert/alert-channel-test-service.ts
@@ -16,7 +16,7 @@ import { TAlertChannelDeps, TAlertRecipient } from "./alert-channel-types";
import { TAlertDALFactory } from "./alert-dal";
import { TAlertProviderRegistry } from "./alert-provider-registry";
import { TAlertRecipientResolver } from "./alert-recipient-resolver";
-import { TTestAlertChannelDTO, TTestAlertChannelResponse } from "./alert-service-types";
+import { TTestAlertChannelDTO, TTestAlertChannelResponse, TTestAlertChannelResult } from "./alert-service-types";
import { buildTestAlertPayload } from "./alert-test-payload-fns";
import { AlertPermissionAction, resolveAlertProjectId, toAlertActor } from "./alert-types";
@@ -141,31 +141,8 @@ export const alertChannelTestServiceFactory = ({
return message.slice(0, MAX_ERROR_LENGTH);
};
- const testChannel = async (dto: TTestAlertChannelDTO): Promise<TTestAlertChannelResponse> => {
+ const $sendTest = async (dto: TTestAlertChannelDTO, projectId: string | null): Promise<TTestAlertChannelResponse> => {
const definition = getChannelDefinition(dto.channelType);
-
- const provider = alertProviderRegistry.get(dto.resourceType);
- if (!provider) {
- throw new BadRequestError({
- message: `No alert provider is registered for resource type '${dto.resourceType}'`
- });
- }
-
- const projectId = await resolveAlertProjectId(provider, {
- orgId: dto.actorOrgId,
- projectId: dto.projectId,
- resourceId: dto.resourceId
- });
-
- await provider.assertPermission({
- action: AlertPermissionAction.Create,
- orgId: dto.actorOrgId,
- projectId,
- resourceId: dto.resourceId,
- actor: toAlertActor(dto)
- });
- await provider.assertResourceInScope({ orgId: dto.actorOrgId, projectId, resourceId: dto.resourceId });
-
const config = await $resolveConfig(dto, projectId);
const recipients = definition.directed ? await $resolveRecipients(dto, projectId) : [];
if (definition.directed && recipients.length === 0) {
@@ -203,5 +180,35 @@ export const alertChannelTestServiceFactory = ({
}
};
+ const testChannel = async (dto: TTestAlertChannelDTO): Promise<TTestAlertChannelResult> => {
+ const provider = alertProviderRegistry.get(dto.resourceType);
+ if (!provider) {
+ throw new BadRequestError({
+ message: `No alert provider is registered for resource type '${dto.resourceType}'`
+ });
+ }
+
+ const projectId = await resolveAlertProjectId(provider, {
+ orgId: dto.actorOrgId,
+ projectId: dto.projectId,
+ resourceId: dto.resourceId
+ });
+
+ await provider.assertPermission({
+ action: AlertPermissionAction.Create,
+ orgId: dto.actorOrgId,
+ projectId,
+ resourceId: dto.resourceId,
+ actor: toAlertActor(dto)
+ });
+ await provider.assertResourceInScope({ orgId: dto.actorOrgId, projectId, resourceId: dto.resourceId });
+
+ if (!dto.channelId) {
+ await provider.assertChannelTypesAllowed?.({ orgId: dto.actorOrgId, channelTypes: [dto.channelType] });
+ }
+
+ return { ...(await $sendTest(dto, projectId)), projectId };
+ };
+
return { testChannel };
};
diff --git a/backend/src/services/alert/alert-engine.ts b/backend/src/services/alert/alert-engine.ts
index 001b2657ab..bbe75752c8 100644
--- a/backend/src/services/alert/alert-engine.ts
+++ b/backend/src/services/alert/alert-engine.ts
@@ -10,7 +10,7 @@ import { decryptChannelConfig, getAlertChannelCipher } from "./alert-channel-cry
import { TAlertChannelDALFactory } from "./alert-channel-dal";
import { TAlertChannelRecipientDALFactory } from "./alert-channel-recipient-dal";
import { AlertChannelType, TAlertChannelDeps, TAlertRecipient, TChannelTargetResult } from "./alert-channel-types";
-import { TAlertHistoryDALFactory } from "./alert-history-dal";
+import { getDedupCutoff, TAlertHistoryDALFactory } from "./alert-history-dal";
import { TAlertProviderRegistry } from "./alert-provider-registry";
import { TAlertRecipientResolver } from "./alert-recipient-resolver";
import { AlertRunStatus, DEFAULT_DEDUP_WINDOW_HOURS, IResourceAlertProvider, TAlertContext } from "./alert-types";
@@ -267,19 +267,24 @@ export const alertEngineFactory = ({
const channels = await alertChannelDAL.findByAlertId(alert.id, { enabled: true });
if (channels.length === 0) return AlertDispatchOutcome.NoChannels;
+ const window = provider.dedupWindowHours?.(alert.condition) ?? DEFAULT_DEDUP_WINDOW_HOURS;
const dueTargets = await provider.findDueTargets({
orgId: alert.orgId,
projectId: alert.projectId,
resourceId: alert.resourceId,
eventType: alert.eventType,
condition: alert.condition,
- asOf: opts?.asOf ?? new Date()
+ asOf: opts?.asOf ?? new Date(),
+ alreadyAlerted: {
+ alertId: alert.id,
+ channelIds: channels.map((channel) => channel.id),
+ since: getDedupCutoff(window)
+ }
});
if (dueTargets.length === 0) return AlertDispatchOutcome.NoDueTargets;
const targets = dueTargets.map((target) => ({ target, id: provider.targetId(target) }));
- const window = provider.dedupWindowHours?.(alert.condition) ?? DEFAULT_DEDUP_WINDOW_HOURS;
const recentlyAlerted = await alertHistoryDAL.findRecentlyAlertedTargets(
alert.id,
targets.map((target) => target.id),
diff --git a/backend/src/services/alert/alert-history-dal.ts b/backend/src/services/alert/alert-history-dal.ts
index d7c528bb75..cdf70ded3b 100644
--- a/backend/src/services/alert/alert-history-dal.ts
+++ b/backend/src/services/alert/alert-history-dal.ts
@@ -22,6 +22,15 @@ const ALERT_HISTORY_PRUNE_BATCH_SIZE = 5_000;
const ALERT_HISTORY_PRUNE_MAX_BATCHES = 20;
const ALERT_HISTORY_PRUNE_TIMEOUT_MS = 30_000;
+const DEDUP_DRIFT_BUFFER_MINUTES = 15;
+
+export const getDedupCutoff = (withinHours: number): Date => {
+ const cutoffDate = new Date();
+ cutoffDate.setHours(cutoffDate.getHours() - withinHours);
+ cutoffDate.setMinutes(cutoffDate.getMinutes() - DEDUP_DRIFT_BUFFER_MINUTES);
+ return cutoffDate;
+};
+
export const alertHistoryDALFactory = (db: TDbClient) => {
const alertHistoryOrm = ormify(db, TableName.AlertHistory);
@@ -64,10 +73,7 @@ export const alertHistoryDALFactory = (db: TDbClient) => {
try {
if (targetIds.length === 0) return [];
- const DEDUP_DRIFT_BUFFER_MINUTES = 15;
- const cutoffDate = new Date();
- cutoffDate.setHours(cutoffDate.getHours() - withinHours);
- cutoffDate.setMinutes(cutoffDate.getMinutes() - DEDUP_DRIFT_BUFFER_MINUTES);
+ const cutoffDate = getDedupCutoff(withinHours);
const rows = (await (tx || db)(`${TableName.AlertHistory} as hist`)
.join(`${TableName.AlertHistoryTarget} as tgt`, "hist.id", "tgt.alertHistoryId")
diff --git a/backend/src/services/alert/alert-principal-scope-fns.ts b/backend/src/services/alert/alert-principal-scope-fns.ts
index 1e58683241..c03577d67e 100644
--- a/backend/src/services/alert/alert-principal-scope-fns.ts
+++ b/backend/src/services/alert/alert-principal-scope-fns.ts
@@ -1,6 +1,8 @@
import { Knex } from "knex";
import { OrgMembershipStatus } from "@app/db/schemas";
+import { TEmailDomainDALFactory } from "@app/ee/services/email-domain/email-domain-dal";
+import { EmailDomainStatus } from "@app/ee/services/email-domain/email-domain-types";
import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -16,6 +18,20 @@ export type TPrincipalScope = { orgId: string; projectId?: string | null };
export type TInScopePrincipals = { userIds: Set<string>; groupIds: Set<string> };
+export const isOnVerifiedDomain = (email: string, verifiedDomains: Set<string>) =>
+ verifiedDomains.has(email.split("@")[1]?.toLowerCase() ?? "");
+
+export const findVerifiedEmailDomains = async (
+ emailDomainDAL: Pick<TEmailDomainDALFactory, "find">,
+ orgId: string,
+ tx?: Knex
+): Promise<Set<string>> =>
+ new Set(
+ (await emailDomainDAL.find({ orgId, status: EmailDomainStatus.Verified }, { tx })).map((domain) =>
+ domain.domain.toLowerCase()
+ )
+ );
+
/**
* Narrows a set of user/group ids down to the ones that are actually in the alert's scope. Shared by
* the write path (validating an alert channel's recipients) and the send path (re-checking recipients
diff --git a/backend/src/services/alert/alert-recipient-resolver.test.ts b/backend/src/services/alert/alert-recipient-resolver.test.ts
index 643169a334..5598e13883 100644
--- a/backend/src/services/alert/alert-recipient-resolver.test.ts
+++ b/backend/src/services/alert/alert-recipient-resolver.test.ts
@@ -13,6 +13,7 @@ const buildResolver = (opts: {
invitedUserIds?: string[]; // users invited to the org who never accepted
effectiveProjectUserIds?: string[]; // users currently effective in the project
effectiveProjectGroupIds?: string[]; // groups currently holding a project membership
+ verifiedDomains?: string[];
}) => {
const usersById = new Map(opts.users.map((u) => [u.id, u]));
return alertRecipientResolverFactory({
@@ -55,6 +56,9 @@ const buildResolver = (opts: {
effectiveUserIds: userIds.filter((id) => (opts.effectiveProjectUserIds ?? []).includes(id)),
effectiveGroupIds: groupIds.filter((id) => (opts.effectiveProjectGroupIds ?? []).includes(id))
})
+ } as never,
+ emailDomainDAL: {
+ find: async () => (opts.verifiedDomains ?? []).map((domain) => ({ domain }))
} as never
});
};
@@ -226,4 +230,23 @@ describe("alert recipient resolver — send-time scope re-check", () => {
const emails = (result.get("c1") ?? []).map((r) => r.email);
expect(emails).toEqual(["[email protected]"]);
});
+
+ test("drops a plain email whose domain is no longer verified", async () => {
+ const resolver = buildResolver({ users: [], verifiedDomains: ["verified.example.com"] });
+
+ const result = await resolver.resolveMany(
+ new Map([
+ [
+ "c1",
+ [
+ { principalType: AlertPrincipalType.EMAIL, principalId: "[email protected]" },
+ { principalType: AlertPrincipalType.EMAIL, principalId: "[email protected]" }
+ ]
+ ]
+ ]),
+ { orgId: "org-1", projectId: null }
+ );
+
+ expect((result.get("c1") ?? []).map((r) => r.email)).toEqual(["[email protected]"]);
+ });
});
diff --git a/backend/src/services/alert/alert-recipient-resolver.ts b/backend/src/services/alert/alert-recipient-resolver.ts
index 6cc01b1e89..9e2a871f18 100644
--- a/backend/src/services/alert/alert-recipient-resolver.ts
+++ b/backend/src/services/alert/alert-recipient-resolver.ts
@@ -1,3 +1,4 @@
+import { TEmailDomainDALFactory } from "@app/ee/services/email-domain/email-domain-dal";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
import { logger } from "@app/lib/logger";
import { TOrgDALFactory } from "@app/services/org/org-dal";
@@ -5,7 +6,7 @@ import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TUserDALFactory } from "@app/services/user/user-dal";
import { TAlertRecipient } from "./alert-channel-types";
-import { resolvePrincipalsInScope } from "./alert-principal-scope-fns";
+import { findVerifiedEmailDomains, isOnVerifiedDomain, resolvePrincipalsInScope } from "./alert-principal-scope-fns";
import { AlertPrincipalType } from "./alert-types";
type TAlertRecipientResolverDep = {
@@ -13,6 +14,7 @@ type TAlertRecipientResolverDep = {
userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;
orgDAL: Pick<TOrgDALFactory, "findMembership">;
projectDAL: Pick<TProjectDALFactory, "findEffectiveProjectSubjectsMembership">;
+ emailDomainDAL: Pick<TEmailDomainDALFactory, "find">;
};
type TResolvableRecipient = { principalType: string; principalId: string };
@@ -25,7 +27,8 @@ export const alertRecipientResolverFactory = ({
userDAL,
userGroupMembershipDAL,
orgDAL,
- projectDAL
+ projectDAL,
+ emailDomainDAL
}: TAlertRecipientResolverDep) => {
const resolveMany = async (
rowsByChannel: Map<string, TResolvableRecipient[]>,
@@ -33,12 +36,17 @@ export const alertRecipientResolverFactory = ({
): Promise<Map<string, TAlertRecipient[]>> => {
const allGroupIds = new Set<string>();
const allUserIds = new Set<string>();
+ let hasEmailRecipients = false;
for (const rows of rowsByChannel.values()) {
for (const recipient of rows) {
if (recipient.principalType === AlertPrincipalType.GROUP) allGroupIds.add(recipient.principalId);
else if (recipient.principalType === AlertPrincipalType.USER) allUserIds.add(recipient.principalId);
+ else if (recipient.principalType === AlertPrincipalType.EMAIL) hasEmailRecipients = true;
}
}
+ const verifiedDomains = hasEmailRecipients
+ ? await findVerifiedEmailDomains(emailDomainDAL, scope.orgId)
+ : new Set<string>();
const groupMembers = new Map<string, string[]>();
if (allGroupIds.size > 0) {
@@ -94,7 +102,7 @@ export const alertRecipientResolverFactory = ({
});
const userEmails = new Set(resolved.map((recipient) => recipient.email.toLowerCase()));
emails.forEach((email) => {
- if (!userEmails.has(email)) resolved.push({ email });
+ if (!userEmails.has(email) && isOnVerifiedDomain(email, verifiedDomains)) resolved.push({ email });
});
result.set(channelId, resolved);
diff --git a/backend/src/services/alert/alert-service-types.ts b/backend/src/services/alert/alert-service-types.ts
index acc1f55c5c..1b5b76cac4 100644
--- a/backend/src/services/alert/alert-service-types.ts
+++ b/backend/src/services/alert/alert-service-types.ts
@@ -54,6 +54,8 @@ export type TTestAlertChannelResponse = {
error?: string;
};
+export type TTestAlertChannelResult = TTestAlertChannelResponse & { projectId: string | null };
+
export type TAlertResponse = {
id: string;
name: string;
diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.ts
index 0546ddc77c..e4c31a3136 100644
--- a/backend/src/services/alert/alert-types.ts
+++ b/backend/src/services/alert/alert-types.ts
@@ -101,6 +101,7 @@ export type TFindDueTargetsInput = {
eventType: string;
condition: unknown;
asOf: Date;
+ alreadyAlerted?: { alertId: string; channelIds: string[]; since: Date };
};
// Lets a provider factory declare which discovery method it guarantees.
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 16473a4ba9..39dabd184b 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
@@ -13,14 +13,13 @@ const buildDAL = () => {
const reader = ((table: string) => {
const query = builder(table);
- Object.assign(query, {
+ return Object.assign(query, {
then: (resolve: (rows: unknown[]) => void) => {
const { sql, bindings } = query.toSQL();
queries.push({ sql, bindings });
resolve([]);
}
});
- return query;
}) as unknown as Knex;
const db = Object.assign(reader, { replicaNode: () => reader }) as unknown as TDbClient;
@@ -53,6 +52,26 @@ describe("cert manager application alert DAL", () => {
);
});
+ test("findExpiringCertificates skips certificates already delivered on every channel before the cap", async () => {
+ const { dal, queries } = buildDAL();
+ const since = new Date("2026-01-01T00:00:00Z");
+
+ await dal.findExpiringCertificates({
+ projectId: PROJECT_ID,
+ applicationId: APPLICATION_ID,
+ alertBeforeInterval: "30 days",
+ leadInterval: "1 day",
+ asOf: new Date("2026-01-02T00:00:00Z"),
+ alreadyAlerted: { alertId: "alert-1", channelIds: ["channel-1", "channel-2"], since }
+ });
+
+ const [{ sql, bindings }] = queries;
+ 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(bindings).toEqual(expect.arrayContaining(["alert-1", since, "success", "channel-1", "channel-2", 2]));
+ });
+
test("findCertificatesByIds keeps event targets inside the alert's project and application", async () => {
const { dal, queries } = buildDAL();
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 a11f4fd055..10f88f7016 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
@@ -3,6 +3,7 @@ import { Knex } from "knex";
import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
+import { AlertRunStatus } from "@app/services/alert/alert-types";
import { CertStatus } from "@app/services/certificate/certificate-types";
export type TCertManagerApplicationAlertDALFactory = ReturnType<typeof certManagerApplicationAlertDALFactory>;
@@ -44,11 +45,31 @@ export const certManagerApplicationAlertDALFactory = (db: TDbClient) => {
);
const findExpiringCertificates = async (
- scope: TCertificateScope & { alertBeforeInterval: string; leadInterval: string; asOf: Date },
+ scope: TCertificateScope & {
+ alertBeforeInterval: string;
+ leadInterval: string;
+ asOf: Date;
+ alreadyAlerted?: { alertId: string; channelIds: string[]; since: Date };
+ },
tx?: Knex
): Promise<TApplicationAlertCertificate[]> => {
try {
- const certificates = (await $selectCertificates(tx || db.replicaNode(), scope)
+ const reader = tx || db.replicaNode();
+ const query = $selectCertificates(reader, scope);
+ const { alreadyAlerted } = scope;
+ if (alreadyAlerted?.channelIds.length) {
+ const deliveredChannelCount = reader(`${TableName.AlertHistory} as hist`)
+ .join(`${TableName.AlertHistoryTarget} as tgt`, "hist.id", "tgt.alertHistoryId")
+ .where("hist.alertId", alreadyAlerted.alertId)
+ .where("hist.triggeredAt", ">=", alreadyAlerted.since)
+ .where("tgt.status", AlertRunStatus.SUCCESS)
+ .whereIn("tgt.channelId", alreadyAlerted.channelIds)
+ .whereRaw(`"tgt"."targetId" = "${TableName.Certificate}".id::text`)
+ .countDistinct("tgt.channelId");
+ void query.whereRaw("(?) < ?", [deliveredChannelCount, alreadyAlerted.channelIds.length]);
+ }
+
+ const certificates = (await query
.whereNot(`${TableName.Certificate}.status`, CertStatus.REVOKED)
.whereNull(`${TableName.Certificate}.renewedByCertificateId`)
.whereRaw(`"${TableName.Certificate}"."notAfter" > ?::timestamptz`, [scope.asOf])
diff --git a/backend/src/services/alert/providers/cert-manager-application-alert-provider.ts b/backend/src/services/alert/providers/cert-manager-application-alert-provider.ts
index 45a8ef9795..2819a46390 100644
--- a/backend/src/services/alert/providers/cert-manager-application-alert-provider.ts
+++ b/backend/src/services/alert/providers/cert-manager-application-alert-provider.ts
@@ -169,7 +169,8 @@ export const certManagerApplicationAlertProviderFactory = ({
applicationId: input.resourceId,
alertBeforeInterval: `${durationToDays(alertBefore)} days`,
leadInterval: ALERT_SCAN_LEAD_INTERVAL,
- asOf: input.asOf
+ asOf: input.asOf,
+ alreadyAlerted: input.alreadyAlerted
});
};
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 d30d4fc9b3..68031fc72b 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
@@ -812,4 +812,11 @@ describe("identity credential alert provider", () => {
provider.assertResourceInScope({ orgId: "org-1", projectId: "proj-1", resourceId: "ident-1" })
).resolves.toBeUndefined();
});
+
+ test("getResourceNames returns the identity's name for audit events", async () => {
+ const provider = buildProvider();
+ const names = await provider.getResourceNames?.({ orgId: "org-1", resourceIds: ["ident-1", "unknown"] });
+ expect(names?.get("ident-1")).toBe("ci-runner");
+ expect(names?.has("unknown")).toBe(false);
+ });
});
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 c92265b84b..927886dfc1 100644
--- a/backend/src/services/alert/providers/identity-credential-alert-provider.ts
+++ b/backend/src/services/alert/providers/identity-credential-alert-provider.ts
@@ -526,6 +526,13 @@ export const identityCredentialAlertProviderFactory = ({
);
},
assertPermission,
- assertResourceInScope
+ assertResourceInScope,
+ getResourceNames: async ({ orgId, resourceIds }) =>
+ new Map(
+ (await identityCredentialAlertDAL.findIdentitiesByIds(resourceIds, orgId)).map((identity) => [
+ identity.id,
+ identity.name
+ ])
+ )
};
};
diff --git a/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.ts b/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.ts
index c69dc1f47b..54d3c8eb27 100644
--- a/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.ts
+++ b/backend/src/services/certificate-authority/digicert/digicert-revocation-sync-queue.ts
@@ -34,12 +34,12 @@ const HANDLER_TIMEOUT_MS = 30 * 60 * 1000;
type TDigiCertRevocationSyncQueueFactoryDep = {
cronJob: TCronJobFactory;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findWithAssociatedCa">;
- certificateDAL: Pick<TCertificateDALFactory, "findActiveDigiCertCertsByOrderIds" | "updateById">;
+ certificateDAL: Pick<TCertificateDALFactory, "findActiveDigiCertCertsByOrderIds" | "updateById" | "transaction">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;
- certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "notify">;
+ certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "emit">;
};
export type TDigiCertRevocationSyncQueueFactory = ReturnType<typeof digicertRevocationSyncQueueFactory>;
@@ -63,10 +63,25 @@ export const digicertRevocationSyncQueueFactory = ({
projectId: string;
applicationId?: string | null;
}) => {
- await certificateDAL.updateById(cert.id, {
- status: CertStatus.REVOKED,
- revokedAt: new Date(),
- revocationReason: revocationReasonToCrlCode(CrlReason.UNSPECIFIED)
+ await certificateDAL.transaction(async (tx) => {
+ await certificateDAL.updateById(
+ cert.id,
+ {
+ status: CertStatus.REVOKED,
+ revokedAt: new Date(),
+ revocationReason: revocationReasonToCrlCode(CrlReason.UNSPECIFIED)
+ },
+ tx
+ );
+ await certificateAlertEventEmitter.emit(
+ {
+ certificateId: cert.id,
+ projectId: cert.projectId,
+ eventType: CertificateAlertEvent.Revocation,
+ applicationId: cert.applicationId ?? null
+ },
+ tx
+ );
});
await auditLogService.createAuditLog({
@@ -93,13 +108,6 @@ export const digicertRevocationSyncQueueFactory = ({
} catch {
logger.debug(`digicert-revocation-sync: failed to queue PKI revocation alert event [certId=${cert.id}]`);
}
-
- await certificateAlertEventEmitter.notify({
- certificateId: cert.id,
- projectId: cert.projectId,
- eventType: CertificateAlertEvent.Revocation,
- applicationId: cert.applicationId ?? null
- });
};
const syncRevocationsForCertificateAuthority = async (
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx
index ccdfeafe25..5561c54e6b 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/CertificateAlertSheet.tsx
@@ -146,7 +146,7 @@ const CertificateAlertWizard = ({
</div>
<div>
<div className="text-label">{title}</div>
- <SheetDescription className="leading-4 text-muted">
+ <SheetDescription>
Get notified about certificate events in {applicationName}.
</SheetDescription>
</div>
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/LegacyApplicationAlertsCard.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/LegacyApplicationAlertsCard.tsx
index f7d2da24ec..f5e5357873 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/LegacyApplicationAlertsCard.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationAlerts/LegacyApplicationAlertsCard.tsx
@@ -135,9 +135,7 @@ export const LegacyApplicationAlertsCard = ({ applicationId, canDelete }: Props)
Legacy Alerting
<Tooltip>
<TooltipTrigger asChild>
- <span className="rounded bg-surface-active px-2 py-0.5 text-[10px] tracking-wide text-foreground-secondary uppercase">
- Legacy
- </span>
+ <Badge variant="neutral">Legacy</Badge>
</TooltipTrigger>
<TooltipContent side="right" className="max-w-xs">
Legacy alerts are deprecated. They still send notifications but can no longer be