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
import { createMongoAbility } from "@casl/ability";
import { vi } from "vitest";
import { PkiAlertScope, PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { AlertChannelType } from "../alert-channel-types";
import { AlertPermissionAction, AlertTelemetryAction, TAlertContext } from "../alert-types";
import {
certManagerApplicationAlertProviderFactory,
TCertManagerApplicationAlertProviderDep
} from "./cert-manager-application-alert-provider";
import { TAlertCertificate } from "./cert-manager-certificate-alert-dal";
vi.mock("@app/lib/config/env", () => ({
getConfig: () => ({ SITE_URL: "https://app.infisical.com" })
}));
const RESOURCE_TYPE = "cert-manager.application";
const EXPIRY_EVENT = "cert-manager.application.certificate.expiry";
const ISSUANCE_EVENT = "cert-manager.application.certificate.issuance";
const REVOCATION_EVENT = "cert-manager.application.certificate.revocation";
const APPLICATION_ID = "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90";
const PROFILE_ID = "7d9f5b2a-0c3e-4a4d-9f8b-3c4d5e6f7081";
const futureDate = (days: number) => new Date(Date.now() + days * 24 * 60 * 60 * 1000);
const sampleCertificate = (overrides: Partial<TAlertCertificate> = {}): TAlertCertificate => ({
id: "cert-1",
serialNumber: "105d3b4c",
commonName: "api.example.com",
altNames: "api.example.com, www.api.example.com",
profileId: "profile-1",
profileName: "tls-server",
status: "active",
notBefore: new Date("2026-09-01T00:00:00.000Z"),
notAfter: futureDate(5),
revokedAt: null,
revocationReason: null,
applicationId: "app-1",
applicationName: "payments-api",
...overrides
});
const alertContext = (overrides: Partial<TAlertContext> = {}): TAlertContext => ({
id: "alert-1",
name: "tls-expiry",
orgId: "org-1",
projectId: "proj-1",
resourceType: RESOURCE_TYPE,
resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",
eventType: EXPIRY_EVENT,
condition: { alertBefore: "30d" },
...overrides
});
const buildProvider = (opts?: {
application?: { id: string; name: string; projectId: string; orgId: string };
certificates?: TAlertCertificate[];
onFindExpiring?: (args: Record<string, unknown>) => void;
onFindByIds?: (args: Record<string, unknown>) => void;
onFindNames?: (ids: string[], orgId: string) => void;
abilityRules?: { action: string; subject: string; inverted?: boolean; conditions?: unknown }[];
pkiEnterpriseAlerting?: boolean;
}) => {
const application = opts?.application ?? {
id: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",
name: "payments-api",
projectId: "proj-1",
orgId: "org-1"
};
const dal = {
findApplicationById: async (id: string) => (id === application.id ? application : undefined),
findApplicationNamesByIds: async (ids: string[], orgId: string) => {
opts?.onFindNames?.(ids, orgId);
return ids.some((id) => id.toLowerCase() === application.id) && orgId === application.orgId
? [{ id: application.id, name: application.name }]
: [];
},
findExpiringCertificates: async (args: Record<string, unknown>) => {
opts?.onFindExpiring?.(args);
return opts?.certificates ?? [];
},
findCertificatesByIds: async (args: Record<string, unknown>) => {
opts?.onFindByIds?.(args);
return opts?.certificates ?? [];
}
};
const ability = () =>
createMongoAbility((opts?.abilityRules ?? [{ action: "read", subject: "pki-alerts" }]) as never);
const permissionService = {
getResourcePermission: vi.fn(async () => ({ permission: ability() }))
};
const licenseService = {
getPlan: async () => ({ pkiEnterpriseAlerting: opts?.pkiEnterpriseAlerting ?? false })
};
const provider = certManagerApplicationAlertProviderFactory({
certManagerCertificateAlertDAL: dal,
permissionService,
licenseService
} as unknown as TCertManagerApplicationAlertProviderDep);
return { provider, permissionService };
};
const actor = { actor: "user", actorId: "u1", actorAuthMethod: null, actorOrgId: "org-1" } as never;
const expiryConditionSchema = (provider: ReturnType<typeof buildProvider>["provider"]) =>
provider.events.find((event) => event.key === EXPIRY_EVENT)!.conditionSchema;
describe("cert manager application alert provider", () => {
test("expiry condition accepts 1 to 365 days in any unit and rejects everything else", () => {
const schema = expiryConditionSchema(buildProvider().provider);
["1d", "30d", "2w", "12m", "1y", "365d"].forEach((alertBefore) =>
expect(schema.safeParse({ alertBefore }).success).toBe(true)
);
["0d", "366d", "2y", "13m", "30", "d", "30h", "12345d"].forEach((alertBefore) =>
expect(schema.safeParse({ alertBefore }).success).toBe(false)
);
expect(schema.safeParse({ alertBefore: "30d", filters: [] }).success).toBe(false);
});
test("findScheduledTargets scans nothing when the alert has no channel to deliver to", async () => {
let scanned = false;
const { provider } = buildProvider({
onFindExpiring: () => {
scanned = true;
}
});
const targets = await provider.findScheduledTargets({
orgId: "org-1",
projectId: "proj-1",
resourceId: null,
eventType: EXPIRY_EVENT,
condition: { alertBefore: "2w" },
asOf: new Date(),
alreadyAlerted: { alertId: "alert-1", channelIds: [], since: new Date() }
});
expect(targets).toEqual([]);
expect(scanned).toBe(false);
});
test("findScheduledTargets converts alertBefore to days and scopes the scan to the alert's application", async () => {
let args: Record<string, unknown> | undefined;
const { provider } = buildProvider({
onFindExpiring: (value) => {
args = value;
}
});
await provider.findScheduledTargets({
orgId: "org-1",
projectId: "proj-1",
resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",
eventType: EXPIRY_EVENT,
condition: { alertBefore: "2w" },
asOf: new Date(),
alreadyAlerted: { alertId: "alert-1", channelIds: ["channel-1"], since: new Date() }
});
expect(args).toMatchObject({
projectId: "proj-1",
applicationId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",
alertBeforeInterval: "14 days"
});
});
test("dedup window tightens as the lead time shrinks and a daily reminder forces 24h", () => {
const { provider } = buildProvider();
expect(provider.dedupWindowHours?.({ alertBefore: "7d" })).toBe(20);
expect(provider.dedupWindowHours?.({ alertBefore: "30d" })).toBe(44);
expect(provider.dedupWindowHours?.({ alertBefore: "12w" })).toBe(164);
expect(provider.dedupWindowHours?.({ alertBefore: "1y" })).toBe(716);
expect(provider.dedupWindowHours?.({ alertBefore: "1y", dailyReminder: true })).toBe(20);
});
test("buildPayload summarises expiring certificates with the lead time and singular wording", async () => {
const { provider } = buildProvider();
const payload = provider.buildPayload(
alertContext({ condition: { alertBefore: "1d" } }),
[sampleCertificate()],
"https://app.infisical.com/view"
);
expect(payload.summary).toBe("1 certificate in application 'payments-api' expiring within 1 day");
expect(payload.alert.condition).toBe("1d");
expect(payload.webhookType).toBe(`com.infisical.${EXPIRY_EVENT}`);
expect(payload.eventKey).toBe(EXPIRY_EVENT);
expect(payload.webhookSource).toBe(`/applications/${alertContext().resourceId}/alerts/alert-1`);
expect(payload.alert.resourceType).toBe(RESOURCE_TYPE);
expect(payload.alert.resourceId).toBe(alertContext().resourceId);
expect(payload.severity).toBe("critical");
expect(payload.items[0]).toMatchObject({ id: "cert-1", title: "api.example.com" });
expect(payload.items[0].fields?.map((field) => field.label)).toEqual([
"Serial Number",
"SANs",
"Profile",
"Expires"
]);
expect(payload.items[0].resource).toEqual({
id: "cert-1",
serialNumber: "105d3b4c",
commonName: "api.example.com",
altNames: ["api.example.com", "www.api.example.com"],
status: "active",
notBefore: "2026-09-01T00:00:00.000Z",
notAfter: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T/) as string,
revokedAt: null,
revocationReason: null,
profileId: "profile-1",
profileName: "tls-server",
applicationId: "app-1",
applicationName: "payments-api"
});
});
test("buildPayload names a certificate without a common name by its first SAN, then its serial", async () => {
const { provider } = buildProvider();
const issuance = alertContext({ eventType: ISSUANCE_EVENT, condition: null });
const bySan = provider.buildPayload(issuance, [sampleCertificate({ commonName: "" })], "https://x");
expect(bySan.summary).toBe("Certificate 'api.example.com' was issued in application 'payments-api'");
expect(bySan.items[0].title).toBe("api.example.com");
const bySerial = provider.buildPayload(
issuance,
[sampleCertificate({ commonName: "", altNames: null })],
"https://x"
);
expect(bySerial.items[0].title).toBe("105d3b4c");
});
test("buildPayload for a revocation names the certificate and adds the revocation reason", async () => {
const { provider } = buildProvider();
const payload = provider.buildPayload(
alertContext({ eventType: REVOCATION_EVENT, condition: null }),
[sampleCertificate({ revocationReason: 1, altNames: null, profileName: null })],
"https://app.infisical.com/view"
);
expect(payload.summary).toBe("Certificate 'api.example.com' was revoked in application 'payments-api'");
expect(payload.severity).toBe("warning");
expect(payload.alert.condition).toBeUndefined();
expect(payload.items[0].fields).toEqual([
{ label: "Serial Number", value: "105d3b4c" },
{ label: "Expires", value: expect.any(String) as string },
{ label: "Revocation Reason", value: "Key Compromise" }
]);
});
test("buildViewUrl deep-links to the application and falls back to the applications list", async () => {
const { provider } = buildProvider();
await expect(provider.buildViewUrl(alertContext())).resolves.toBe(
"https://app.infisical.com/organizations/org-1/cert-manager/applications/payments-api"
);
await expect(provider.buildViewUrl(alertContext({ resourceId: "missing" }))).resolves.toBe(
"https://app.infisical.com/organizations/org-1/cert-manager/applications"
);
});
test("assertPermission checks the application's resource permission when the alert is bound to one", async () => {
const { provider, permissionService } = buildProvider();
await expect(
provider.assertPermission({
action: AlertPermissionAction.Read,
orgId: "org-1",
projectId: "proj-1",
resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",
actor
})
).resolves.toBeUndefined();
await expect(
provider.assertPermission({
action: AlertPermissionAction.Create,
orgId: "org-1",
projectId: "proj-1",
resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",
actor
})
).rejects.toThrow();
expect(permissionService.getResourcePermission).toHaveBeenCalled();
});
test("assertPermission requires a project", async () => {
const { provider } = buildProvider();
await expect(
provider.assertPermission({ action: AlertPermissionAction.Read, orgId: "org-1", actor })
).rejects.toThrow("Certificate alerts must be created in Certificate Manager");
});
test("assertResourceInScope rejects an application from another project or org", async () => {
const { provider } = buildProvider();
await expect(
provider.assertResourceInScope({
orgId: "org-1",
projectId: "proj-1",
resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90"
})
).resolves.toBeUndefined();
await expect(
provider.assertResourceInScope({
orgId: "org-1",
projectId: "proj-2",
resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90"
})
).rejects.toThrow("Application with ID '7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90' not found in Certificate Manager");
await expect(
provider.assertResourceInScope({
orgId: "org-2",
projectId: "proj-1",
resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90"
})
).rejects.toThrow();
await expect(provider.assertResourceInScope({ orgId: "org-1", projectId: "proj-1" })).resolves.toBeUndefined();
});
test("resolveProjectId returns the application's project and hides applications from other orgs", async () => {
const { provider } = buildProvider();
await expect(
provider.resolveProjectId?.({ orgId: "org-1", resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90" })
).resolves.toBe("proj-1");
await expect(
provider.resolveProjectId?.({ orgId: "org-2", resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90" })
).rejects.toThrow("Application with ID '7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90' not found");
});
test("rejects a malformed application ID with a bad request before any lookup", async () => {
const { provider, permissionService } = buildProvider();
const expected = "Invalid application ID 'not-a-uuid': must be a UUID";
await expect(
provider.assertPermission({
action: AlertPermissionAction.Read,
orgId: "org-1",
projectId: "proj-1",
resourceId: "not-a-uuid",
actor
})
).rejects.toThrow(expected);
await expect(
provider.assertResourceInScope({ orgId: "org-1", projectId: "proj-1", resourceId: "not-a-uuid" })
).rejects.toThrow(expected);
await expect(provider.resolveProjectId?.({ orgId: "org-1", resourceId: "not-a-uuid" })).rejects.toThrow(expected);
expect(permissionService.getResourcePermission).not.toHaveBeenCalled();
});
test("assertChannelTypesAllowed lets email through and gates other channels on the plan", async () => {
await expect(
buildProvider().provider.assertChannelTypesAllowed?.({ orgId: "org-1", channelTypes: [AlertChannelType.EMAIL] })
).resolves.toBeUndefined();
await expect(
buildProvider().provider.assertChannelTypesAllowed?.({
orgId: "org-1",
channelTypes: [AlertChannelType.EMAIL, AlertChannelType.SLACK]
})
).rejects.toThrow("plan restriction");
await expect(
buildProvider({ pkiEnterpriseAlerting: true }).provider.assertChannelTypesAllowed?.({
orgId: "org-1",
channelTypes: [AlertChannelType.SLACK]
})
).resolves.toBeUndefined();
});
test("getResourceNames scopes the lookup to the caller's org", async () => {
let lookup: { ids: string[]; orgId: string } | undefined;
const { provider } = buildProvider({
onFindNames: (ids, orgId) => {
lookup = { ids, orgId };
}
});
const names = await provider.getResourceNames?.({
orgId: "org-1",
resourceIds: ["7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90"]
});
expect(lookup).toEqual({ ids: ["7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90"], orgId: "org-1" });
expect(names?.get("7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90")).toBe("payments-api");
const foreign = await provider.getResourceNames?.({
orgId: "org-2",
resourceIds: ["7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90"]
});
expect(foreign?.size).toBe(0);
});
test("telemetry reports the same alertType values as the deprecated application routes", () => {
const { provider } = buildProvider();
expect(
provider.getTelemetryEvent?.({
action: AlertTelemetryAction.Create,
orgId: "org-1",
projectId: "proj-1",
resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",
eventType: EXPIRY_EVENT
})
).toEqual({
event: PostHogEventTypes.PkiAlertCreated,
properties: {
orgId: "org-1",
projectId: "proj-1",
applicationId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",
alertScope: PkiAlertScope.Application,
alertType: "expiration"
}
});
expect(
provider.getTelemetryEvent?.({
action: AlertTelemetryAction.Delete,
orgId: "org-1",
projectId: "proj-1",
resourceId: "7b0a6b54-3c1e-4f3a-9d5e-2f1b8c4d6e90",
eventType: ISSUANCE_EVENT
})?.event
).toBe(PostHogEventTypes.PkiAlertDeleted);
});
test("only takes alerts bound to an application, with no filters", async () => {
const { provider } = buildProvider({ abilityRules: [{ action: "create", subject: "pki-alerts" }] });
expect(provider.supportsScopeWideAlerts).toBeUndefined();
await expect(
provider.assertPermission({
action: AlertPermissionAction.Create,
orgId: "org-1",
projectId: "proj-1",
resourceId: null,
actor
})
).rejects.toThrow("Application alerts require an application ID");
await expect(provider.resolveProjectId?.({ orgId: "org-1", resourceId: null })).rejects.toThrow(
"Application alerts require an application ID"
);
const eventSchema = provider.events.find((event) => event.key === ISSUANCE_EVENT)!.conditionSchema;
expect(eventSchema.safeParse({ applicationIds: [APPLICATION_ID] }).success).toBe(false);
expect(expiryConditionSchema(provider).safeParse({ alertBefore: "30d", profileIds: [PROFILE_ID] }).success).toBe(
false
);
});
});