Skip to content

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

add event alert for identity auth change

Thiago Araujo da Silva58f1d820d84d
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index af77e01f92..2518500dbd 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -610,15 +610,17 @@ See `src/services/health-alert/health-alert-queue.ts` for a minimal example, `sr
Adding a new alertable resource type:
-1. Implement `IResourceAlertProvider` (`alert-types.ts`) in `src/services/alert/providers/<name>-alert-provider.ts`, with its DAL alongside it. You supply: a dot-namespaced `resourceType` (e.g. `identity.authentication`), an `events` list, a `conditionSchema` for the "when", `buildViewUrl` / `buildPayload` / `targetId`, one discovery method per trigger type you declare (below), and the two authorization hooks `assertPermission` + `assertResourceInScope`. Test sends need nothing from you: they go through the generic `buildTestAlertPayload` (`alert-test-payload-fns.ts`).
+1. Implement `IResourceAlertProvider` (`alert-types.ts`) in `src/services/alert/providers/<name>-alert-provider.ts`, with its DAL alongside it. You supply: a dot-namespaced `resourceType` (e.g. `identity.authentication`), an `events` list (each event carries its own `conditionSchema` for the "when", so a scheduled expiry and an event-triggered change on the same resource type don't share one shape), `buildViewUrl` / `buildPayload` / `targetId`, one discovery method per trigger type you declare (below), and the two authorization hooks `assertPermission` + `assertResourceInScope`. Test sends need nothing from you: they go through the generic `buildTestAlertPayload` (`alert-test-payload-fns.ts`).
2. Register it on the singleton registry in `src/server/routes/index.ts` (`alertProviderRegistry.register(...)`).
-That's it — CRUD routes, channel creation/rotation, recipient resolution, KMS encryption, dedup, history, retention pruning, test sends, and dispatch metrics all come for free, because the cron tick enumerates `alertProviderRegistry.resourceTypes()`. See `src/services/alert/providers/identity-credential-alert-provider.ts` for a complete example.
+That's it — CRUD routes, channel creation/rotation, recipient resolution, KMS encryption, dedup, history, retention pruning, test sends, and dispatch metrics all come for free, because the cron tick enumerates `alertProviderRegistry.resourceTypes()`. See `src/services/alert/providers/identity-credential-alert-provider.ts` for a complete example that declares both trigger types (`identity.authentication.expiry` scheduled, `identity.authentication.auth-method-changed` event-triggered).
**Each event declares how it fires**, and the trigger decides which discovery method the provider owes:
- `AlertTriggerType.Scheduled` → **`findDueTargets`**. The daily cron asks what is currently due, and the engine dedups per `(channel, target)` so a target rediscovered tomorrow is not alerted on twice.
-- `AlertTriggerType.Event` → **`findTargetsByIds`**. The target is already known, so nothing is scanned for and **nothing is deduped**: an event that fired is one the customer asked to hear about, and unlike a daily scan it is never rediscovered. These reach the engine from the event outbox (below), never from the cron.
+- `AlertTriggerType.Event` → **`findTargetsByIds`**. The target is already known, so nothing is scanned for and **nothing is deduped**: an event that fired is one the customer asked to hear about, and unlike a daily scan it is never rediscovered. These reach the engine from the event outbox (below), never from the cron. The input carries the outbox row's whole `payload` next to `targetIds`: the module only reads `targetIds`, so an emitter can add the facts the notification needs (which auth method, who changed it) and the provider validates them with its own schema at delivery. Encoding facts into the target id is the wrong tool for that.
+
+**`findEnabledForEvent` with no `projectId` matches every alert bound to the resource, any scope.** A resource that has no project of its own (an org-level identity) can still be watched from a project it is a member of, and `assertResourceInScope` already checked that binding at create. Given a `projectId`, it matches that project's alerts plus org-scoped ones.
`alertProviderRegistry.register` asserts that pairing at boot, so a provider that declares an event trigger without `findTargetsByIds` fails the process rather than silently no-op'ing in production. `triggerType` is derived from the provider's event definition inside `createAlert` and is never accepted from a request.
@@ -707,9 +709,17 @@ new consumer gets them for free.
**Adding an event-triggered alert** needs no outbox code: declare the event with
`triggerType: AlertTriggerType.Event`, implement `findTargetsByIds`, and emit with the provider's
-`resourceType` and `payload: { targetIds }`. A `resourceType` that doesn't declare the `eventType` fails
+`resourceType` and `payload: { targetIds, ...facts }`. A `resourceType` that doesn't declare the `eventType` fails
the row terminally with both named, so a bad emit site shows up in the logs on its first event.
+**When several services fire the same event, they call `eventOutboxService.emit` directly and `satisfies`
+one exported payload type.** The identity auth method services (`attach*` / `update*` / `revoke*` in all 13, plus the Universal Auth
+client secret and Token Auth token create/update/revoke paths) each write the
+`identity.authentication.auth-method-changed` event inline, inside the write transaction, with the payload literal checked against `TIdentityAuthMethodChangeEventPayload` from the
+provider file. The provider's test parses a value of that type with its delivery schema, so the compiler
+holds the emit sites to the type and the test holds the type to the schema. A bare `updateById` had to
+become a short transaction for this; the cache invalidation that follows it stays outside, after commit.
+
The DAL is covered by `e2e-test/event-outbox.spec.ts` against real Postgres; the unit tests only check
query shape.
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 5ae1a122d3..e173a4b6ea 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -2632,6 +2632,7 @@ export const registerRoutes = async (
});
const identityTokenAuthService = identityTokenAuthServiceFactory({
+ eventOutboxService,
identityTokenAuthDAL,
identityAccessTokenDAL,
permissionService,
@@ -2643,6 +2644,7 @@ export const registerRoutes = async (
});
const identityUaService = identityUaServiceFactory({
+ eventOutboxService,
identityDAL,
permissionService,
identityUaClientSecretDAL,
@@ -2655,6 +2657,7 @@ export const registerRoutes = async (
});
const identityKubernetesAuthService = identityKubernetesAuthServiceFactory({
+ eventOutboxService,
identityDAL,
identityKubernetesAuthDAL,
identityAuthTemplateDAL,
@@ -2674,6 +2677,7 @@ export const registerRoutes = async (
identityAccessTokenService
});
const identityGcpAuthService = identityGcpAuthServiceFactory({
+ eventOutboxService,
identityDAL,
identityGcpAuthDAL,
orgDAL,
@@ -2686,6 +2690,7 @@ export const registerRoutes = async (
});
const identityAliCloudAuthService = identityAliCloudAuthServiceFactory({
+ eventOutboxService,
identityDAL,
identityAccessTokenDAL,
orgDAL,
@@ -2698,6 +2703,7 @@ export const registerRoutes = async (
});
const identityTlsCertAuthService = identityTlsCertAuthServiceFactory({
+ eventOutboxService,
identityDAL,
identityAccessTokenDAL,
identityTlsCertAuthDAL,
@@ -2711,6 +2717,7 @@ export const registerRoutes = async (
});
const identityAwsAuthService = identityAwsAuthServiceFactory({
+ eventOutboxService,
identityDAL,
identityAccessTokenDAL,
orgDAL,
@@ -2723,6 +2730,7 @@ export const registerRoutes = async (
});
const identityAzureAuthService = identityAzureAuthServiceFactory({
+ eventOutboxService,
identityDAL,
identityAzureAuthDAL,
orgDAL,
@@ -2735,6 +2743,7 @@ export const registerRoutes = async (
});
const identityOciAuthService = identityOciAuthServiceFactory({
+ eventOutboxService,
identityDAL,
identityAccessTokenDAL,
orgDAL,
@@ -2762,6 +2771,7 @@ export const registerRoutes = async (
});
const identityOidcAuthService = identityOidcAuthServiceFactory({
+ eventOutboxService,
identityDAL,
identityOidcAuthDAL,
identityAuthTemplateDAL,
@@ -2776,6 +2786,7 @@ export const registerRoutes = async (
});
const identityJwtAuthService = identityJwtAuthServiceFactory({
+ eventOutboxService,
identityDAL,
identityJwtAuthDAL,
orgDAL,
@@ -2789,6 +2800,7 @@ export const registerRoutes = async (
});
const identitySpiffeAuthService = identitySpiffeAuthServiceFactory({
+ eventOutboxService,
identityDAL,
identitySpiffeAuthDAL,
orgDAL,
@@ -2802,6 +2814,7 @@ export const registerRoutes = async (
});
const identityLdapAuthService = identityLdapAuthServiceFactory({
+ eventOutboxService,
identityLdapAuthDAL,
orgDAL,
permissionService,
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 e565cec672..b2a13ab0ee 100644
--- a/backend/src/services/alert/alert-channel-test-service.test.ts
+++ b/backend/src/services/alert/alert-channel-test-service.test.ts
@@ -32,8 +32,13 @@ const actor = {
const buildProvider = (opts?: { assertPermission?: (input: TAlertPermissionInput) => Promise<void> }) => {
const provider: IResourceAlertProvider = {
resourceType: RESOURCE_TYPE,
- events: [{ key: "test.resource.expiration", triggerType: AlertTriggerType.Scheduled }],
- conditionSchema: z.object({}).optional(),
+ events: [
+ {
+ key: "test.resource.expiration",
+ triggerType: AlertTriggerType.Scheduled,
+ conditionSchema: z.object({}).optional()
+ }
+ ],
findDueTargets: async () => [],
buildViewUrl: async () => "https://app.infisical.com/x",
buildPayload: (alert, targets, viewUrl) =>
diff --git a/backend/src/services/alert/alert-dal.test.ts b/backend/src/services/alert/alert-dal.test.ts
index 043a3c1d14..32af238c80 100644
--- a/backend/src/services/alert/alert-dal.test.ts
+++ b/backend/src/services/alert/alert-dal.test.ts
@@ -175,7 +175,9 @@ describe("alert dal", () => {
expect(calls.orWhereNull).toContainEqual(`${TableName.Alert}.projectId`);
});
- test("findEnabledForEvent matches only org-scoped alerts when given no project", async () => {
+ // An org-level identity can be watched from any project it belongs to, so an event with no project
+ // of its own has to reach those project-scoped alerts as well as the org-scoped one.
+ test("findEnabledForEvent matches every alert bound to the resource when given no project", async () => {
const { dal, calls } = buildDAL();
await dal.findEnabledForEvent({
@@ -185,7 +187,8 @@ describe("alert dal", () => {
eventType: "approval.workflow.request_opened"
});
- expect(calls.whereNull).toContainEqual(`${TableName.Alert}.projectId`);
+ expect(calls.whereNull).not.toContainEqual(`${TableName.Alert}.projectId`);
+ expect(calls.where).not.toContainEqual(expect.arrayContaining([`${TableName.Alert}.projectId`]));
expect(calls.orWhereNull).toHaveLength(0);
});
});
diff --git a/backend/src/services/alert/alert-dal.ts b/backend/src/services/alert/alert-dal.ts
index 4df5979a52..ec398e9079 100644
--- a/backend/src/services/alert/alert-dal.ts
+++ b/backend/src/services/alert/alert-dal.ts
@@ -78,7 +78,6 @@ export const alertDALFactory = (db: TDbClient) => {
.where(`${TableName.AlertChannel}.enabled`, true)
);
- // A project resource can be watched by a project-scoped alert and by an org-wide one.
if (filter.projectId) {
void query.where(
(builder) =>
@@ -86,8 +85,6 @@ export const alertDALFactory = (db: TDbClient) => {
.where(`${TableName.Alert}.projectId`, filter.projectId as string)
.orWhereNull(`${TableName.Alert}.projectId`)
);
- } else {
- void query.whereNull(`${TableName.Alert}.projectId`);
}
const alerts = await query
diff --git a/backend/src/services/alert/alert-engine.test.ts b/backend/src/services/alert/alert-engine.test.ts
index e8b7a87361..04ed96025d 100644
--- a/backend/src/services/alert/alert-engine.test.ts
+++ b/backend/src/services/alert/alert-engine.test.ts
@@ -59,20 +59,26 @@ const makeAlert = () => ({
updatedAt: new Date()
});
-const makeProvider = (targets: TTarget[], onFindDueTargets?: () => void): IResourceAlertProvider<TTarget> => ({
+const makeProvider = (
+ targets: TTarget[],
+ onFindDueTargets?: () => void,
+ onFindTargetsByIds?: (payload: Record<string, unknown>) => void
+): IResourceAlertProvider<TTarget> => ({
resourceType: RESOURCE_TYPE,
events: [
- { key: "test.resource.expiration", triggerType: AlertTriggerType.Scheduled },
- { key: "test.resource.opened", triggerType: AlertTriggerType.Event }
+ { key: "test.resource.expiration", triggerType: AlertTriggerType.Scheduled, conditionSchema: z.any() },
+ { key: "test.resource.opened", triggerType: AlertTriggerType.Event, conditionSchema: z.any() }
],
- conditionSchema: z.any(),
findDueTargets: async () => {
onFindDueTargets?.();
return targets;
},
// Mirrors a real provider: a target deleted between the event and its delivery drops out rather
// than coming back.
- findTargetsByIds: async ({ targetIds }) => targets.filter((target) => targetIds.includes(target.id)),
+ findTargetsByIds: async ({ targetIds, payload }) => {
+ onFindTargetsByIds?.(payload);
+ return targets.filter((target) => targetIds.includes(target.id));
+ },
assertPermission: async () => undefined,
assertResourceInScope: async () => undefined,
targetId: (target) => target.id,
@@ -120,10 +126,15 @@ const buildEngine = (opts: {
}) => {
const registry = alertProviderRegistryFactory();
let findDueTargetsCalls = 0;
+ const eventPayloads: Record<string, unknown>[] = [];
registry.register(
- makeProvider(opts.targets, () => {
- findDueTargetsCalls += 1;
- }) as IResourceAlertProvider
+ makeProvider(
+ opts.targets,
+ () => {
+ findDueTargetsCalls += 1;
+ },
+ (payload) => eventPayloads.push(payload)
+ ) as IResourceAlertProvider
);
const sentMail: Array<{ recipients: string[] }> = [];
@@ -199,6 +210,7 @@ const buildEngine = (opts: {
sentMail,
historyWrites,
channelLookups,
+ eventPayloads,
getHistoryAttempts: () => historyAttempts,
getPeakConcurrentSends: () => peakConcurrentSends,
getFindDueTargetsCalls: () => findDueTargetsCalls
@@ -507,10 +519,10 @@ describe("alert engine", () => {
describe("alert engine, event path", () => {
const eventAlert = () => ({ ...makeAlert(), triggerType: "event", eventType: "test.resource.opened" });
- const EVENT = { eventType: "test.resource.opened", targetIds: ["t1"] };
+ const EVENT = { eventType: "test.resource.opened", targetIds: ["t1"], payload: { targetIds: ["t1"], note: "x" } };
test("delivers the targets the event named", async () => {
- const { engine, sentMail, historyWrites } = buildEngine({
+ const { engine, sentMail, historyWrites, eventPayloads } = buildEngine({
targets: [{ id: "t1" }, { id: "t2" }],
channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }]
});
@@ -520,6 +532,8 @@ describe("alert engine, event path", () => {
expect(result.outcome).toBe(AlertDispatchOutcome.DeliverySuccess);
expect(result.deliveredChannelIds).toEqual(["c-email"]);
expect(sentMail).toHaveLength(1);
+ // The provider gets the emitter's whole payload, so an event can carry more than ids.
+ expect(eventPayloads).toEqual([EVENT.payload]);
// t2 exists but the event didn't name it.
expect(historyWrites[0].deliveries).toEqual([
{ targetId: "t1", channelId: "c-email", channelType: "email", status: AlertRunStatus.SUCCESS }
diff --git a/backend/src/services/alert/alert-engine.ts b/backend/src/services/alert/alert-engine.ts
index cda19715d3..ac8fcd5615 100644
--- a/backend/src/services/alert/alert-engine.ts
+++ b/backend/src/services/alert/alert-engine.ts
@@ -282,7 +282,7 @@ export const alertEngineFactory = ({
const runAlertForEvent = async (
alert: TAlerts,
- input: { eventType: string; targetIds: string[]; skipChannelIds?: string[] }
+ input: { eventType: string; targetIds: string[]; payload: Record<string, unknown>; skipChannelIds?: string[] }
): Promise<TDispatchResult> => {
const provider = alertProviderRegistry.get(alert.resourceType);
if (!provider) {
@@ -297,7 +297,6 @@ export const alertEngineFactory = ({
}
const skip = new Set(input.skipChannelIds ?? []);
- // Primary: an empty read here is terminal for the event, and a replica may not have the channel yet.
const channels = (await alertChannelDAL.findByAlertId(alert.id, { enabled: true, readFromPrimary: true })).filter(
(channel) => !skip.has(channel.id)
);
@@ -309,9 +308,9 @@ export const alertEngineFactory = ({
resourceId: alert.resourceId,
eventType: input.eventType,
condition: alert.condition,
- targetIds: input.targetIds
+ targetIds: input.targetIds,
+ payload: input.payload
});
- // Deleted between emit and dispatch, so nothing to say.
if (resolved.length === 0) return { outcome: AlertDispatchOutcome.NoDueTargets, deliveredChannelIds: [] };
const targets = resolved.map((target) => ({ target, id: provider.targetId(target) }));
@@ -320,8 +319,6 @@ export const alertEngineFactory = ({
const definition = ALERT_CHANNEL_REGISTRY[channel.channelType as AlertChannelType];
const cap = definition?.maxTargetsPerRun;
if (cap && targets.length > cap) {
- // Unlike the scheduled path there is no next run, so this is a real drop. MAX_TARGET_IDS_PER_EVENT
- // sits at or below every channel cap to keep it unreachable; the log names what was lost if not.
logger.warn(
`Alert ${channel.channelType} channel caps at ${cap} targets; dropping ${targets.length - cap} from this event [alertId=${alert.id}] [channelId=${channel.id}] [dropped=${targets
.slice(cap)
diff --git a/backend/src/services/alert/alert-event-consumer.test.ts b/backend/src/services/alert/alert-event-consumer.test.ts
index 9444fef149..5fc1e1bc06 100644
--- a/backend/src/services/alert/alert-event-consumer.test.ts
+++ b/backend/src/services/alert/alert-event-consumer.test.ts
@@ -37,7 +37,12 @@ const buildConsumer = (opts?: {
eventKeys?: string[];
findAlerts?: () => Promise<unknown[]>;
}) => {
- const runs: { alertId: string; targetIds: string[]; skipChannelIds?: string[] }[] = [];
+ const runs: {
+ alertId: string;
+ targetIds: string[];
+ payload?: Record<string, unknown>;
+ skipChannelIds?: string[];
+ }[] = [];
const results = opts?.results ?? [{ outcome: AlertDispatchOutcome.DeliverySuccess, deliveredChannelIds: ["c-1"] }];
let runIdx = 0;
let lookups = 0;
@@ -51,8 +56,16 @@ const buildConsumer = (opts?: {
}
},
alertEngine: {
- runAlertForEvent: async (alert: { id: string }, input: { targetIds: string[]; skipChannelIds?: string[] }) => {
- runs.push({ alertId: alert.id, targetIds: input.targetIds, skipChannelIds: input.skipChannelIds });
+ runAlertForEvent: async (
+ alert: { id: string },
+ input: { targetIds: string[]; payload: Record<string, unknown>; skipChannelIds?: string[] }
+ ) => {
+ runs.push({
+ alertId: alert.id,
+ targetIds: input.targetIds,
+ payload: input.payload,
+ skipChannelIds: input.skipChannelIds
+ });
const result = results[Math.min(runIdx, results.length - 1)];
runIdx += 1;
return result;
@@ -85,6 +98,8 @@ describe("alert outbox consumer", () => {
expect(result.status).toBe(EventOutboxStatus.Delivered);
expect(runs[0].targetIds).toEqual(["req-1"]);
+ // The provider sees everything the emitter wrote, not only the ids the consumer validated.
+ expect(runs[0].payload).toEqual({ targetIds: ["req-1"] });
expect(result.progress).toEqual({ deliveredChannelIds: ["c-1"] });
});
diff --git a/backend/src/services/alert/alert-event-consumer.ts b/backend/src/services/alert/alert-event-consumer.ts
index 39b59ab45a..32ac470790 100644
--- a/backend/src/services/alert/alert-event-consumer.ts
+++ b/backend/src/services/alert/alert-event-consumer.ts
@@ -95,6 +95,7 @@ export const alertEventConsumerFactory = ({
const result = await alertEngine.runAlertForEvent(alert, {
eventType: row.eventType,
targetIds: payload.data.targetIds,
+ payload: (row.payload ?? {}) as Record<string, unknown>,
skipChannelIds: [...delivered]
});
result.deliveredChannelIds.forEach((channelId) => delivered.add(channelId));
diff --git a/backend/src/services/alert/alert-provider-registry.test.ts b/backend/src/services/alert/alert-provider-registry.test.ts
index daecfdec3f..fa07b8c81d 100644
--- a/backend/src/services/alert/alert-provider-registry.test.ts
+++ b/backend/src/services/alert/alert-provider-registry.test.ts
@@ -7,7 +7,6 @@ const baseProvider = (overrides: Partial<IResourceAlertProvider>): IResourceAler
({
resourceType: "test.resource",
events: [],
- conditionSchema: z.any(),
targetId: (target: { id: string }) => target.id,
buildViewUrl: async () => "https://app.infisical.com/x",
buildPayload: () => ({}) as never,
@@ -31,7 +30,9 @@ describe("alert provider registry", () => {
expect(() =>
registry.register(
- baseProvider({ events: [{ key: "test.resource.expiry", triggerType: AlertTriggerType.Scheduled }] })
+ baseProvider({
+ events: [{ key: "test.resource.expiry", triggerType: AlertTriggerType.Scheduled, conditionSchema: z.any() }]
+ })
)
).toThrow("does not implement findDueTargets");
});
@@ -41,7 +42,9 @@ describe("alert provider registry", () => {
expect(() =>
registry.register(
- baseProvider({ events: [{ key: "test.resource.opened", triggerType: AlertTriggerType.Event }] })
+ baseProvider({
+ events: [{ key: "test.resource.opened", triggerType: AlertTriggerType.Event, conditionSchema: z.any() }]
+ })
)
).toThrow("does not implement findTargetsByIds");
});
@@ -53,8 +56,8 @@ describe("alert provider registry", () => {
registry.register(
baseProvider({
events: [
- { key: "test.resource.expiry", triggerType: AlertTriggerType.Scheduled },
- { key: "test.resource.opened", triggerType: AlertTriggerType.Event }
+ { key: "test.resource.expiry", triggerType: AlertTriggerType.Scheduled, conditionSchema: z.any() },
+ { key: "test.resource.opened", triggerType: AlertTriggerType.Event, conditionSchema: z.any() }
],
findDueTargets: async () => [],
findTargetsByIds: async () => []
@@ -68,8 +71,8 @@ describe("alert provider registry", () => {
registry.register(
baseProvider({
events: [
- { key: "test.resource.expiry", triggerType: AlertTriggerType.Scheduled },
- { key: "test.resource.opened", triggerType: AlertTriggerType.Event }
+ { key: "test.resource.expiry", triggerType: AlertTriggerType.Scheduled, conditionSchema: z.any() },
+ { key: "test.resource.opened", triggerType: AlertTriggerType.Event, conditionSchema: z.any() }
],
findDueTargets: async () => [],
findTargetsByIds: async () => []
diff --git a/backend/src/services/alert/alert-service.test.ts b/backend/src/services/alert/alert-service.test.ts
index d733795484..d344a80243 100644
--- a/backend/src/services/alert/alert-service.test.ts
+++ b/backend/src/services/alert/alert-service.test.ts
@@ -32,10 +32,17 @@ const buildService = (opts?: {
const provider: IResourceAlertProvider = {
resourceType: RESOURCE_TYPE,
events: [
- { key: "test.resource.expiration", triggerType: AlertTriggerType.Scheduled },
- { key: "test.resource.opened", triggerType: AlertTriggerType.Event }
+ {
+ key: "test.resource.expiration",
+ triggerType: AlertTriggerType.Scheduled,
+ conditionSchema: z.object({ alertBefore: z.string() })
+ },
+ {
+ key: "test.resource.opened",
+ triggerType: AlertTriggerType.Event,
+ conditionSchema: z.object({}).strict().nullish()
+ }
],
- conditionSchema: z.object({ alertBefore: z.string() }),
findDueTargets: async () => [],
findTargetsByIds: async () => [],
buildViewUrl: async () => "https://app.infisical.com/x",
@@ -276,7 +283,7 @@ describe("alert service", () => {
expect([...alerts.values()][0].triggerType).toBe("scheduled");
const { service: eventService, alerts: eventAlerts } = buildService();
- await eventService.createAlert({ ...validCreate, eventType: "test.resource.opened" });
+ await eventService.createAlert({ ...validCreate, eventType: "test.resource.opened", condition: null });
expect([...eventAlerts.values()][0].triggerType).toBe("event");
});
@@ -305,6 +312,33 @@ describe("alert service", () => {
);
});
+ test("validates the condition against the event's own schema, not a provider-wide one", async () => {
+ const { service } = buildService();
+ // The event-triggered event takes no condition, so the expiry shape is rejected for it and
+ // an empty one is accepted.
+ await expect(
+ service.createAlert({ ...validCreate, eventType: "test.resource.opened", condition: { alertBefore: "30d" } })
+ ).rejects.toThrow(/Invalid alert condition/);
+ const created = await service.createAlert({
+ ...validCreate,
+ resourceId: "resource-2",
+ eventType: "test.resource.opened",
+ condition: null
+ });
+ expect(created.condition).toBeNull();
+ });
+
+ test("update validates the condition against the stored event's schema", async () => {
+ const { service } = buildService();
+ await service.createAlert(validCreate);
+ await expect(service.updateAlert({ alertId: "alert-1", condition: { alertBefore: 5 }, ...actor })).rejects.toThrow(
+ /Invalid alert condition/
+ );
+ await expect(
+ service.updateAlert({ alertId: "alert-1", condition: { alertBefore: "5d" }, ...actor })
+ ).resolves.toBeDefined();
+ });
+
test("rejects an event type the provider does not support", async () => {
const { service } = buildService();
await expect(service.createAlert({ ...validCreate, eventType: "test.resource.renewal" })).rejects.toThrow();
diff --git a/backend/src/services/alert/alert-service.ts b/backend/src/services/alert/alert-service.ts
index fb5bcd53c2..4a3225935f 100644
--- a/backend/src/services/alert/alert-service.ts
+++ b/backend/src/services/alert/alert-service.ts
@@ -67,31 +67,23 @@ export const alertServiceFactory = ({
actor: toAlertActor(dto)
});
- const $validate = (
- provider: IResourceAlertProvider,
- input: { eventType?: string; condition?: unknown },
- opts: { alwaysValidateCondition?: boolean } = {}
- ): TAlertEventDefinition | undefined => {
- let event: TAlertEventDefinition | undefined;
- if (input.eventType) {
- event = provider.events.find((candidate) => candidate.key === input.eventType);
- if (!event) {
- throw new BadRequestError({
- message: `Event type '${input.eventType}' is not supported by resource type '${provider.resourceType}'`
- });
- }
+ const $getEvent = (provider: IResourceAlertProvider, eventType: string): TAlertEventDefinition => {
+ const event = provider.events.find((candidate) => candidate.key === eventType);
+ if (!event) {
+ throw new BadRequestError({
+ message: `Event type '${eventType}' is not supported by resource type '${provider.resourceType}'`
+ });
}
+ return event;
+ };
- if (opts.alwaysValidateCondition || input.condition !== undefined) {
- try {
- provider.conditionSchema.parse(input.condition);
- } catch (err) {
- const message = err instanceof z.ZodError ? err.issues.map((i) => i.message).join(", ") : "Invalid condition";
- throw new BadRequestError({ message: `Invalid alert condition: ${message}` });
- }
+ const $validateCondition = (event: TAlertEventDefinition, condition: unknown) => {
+ try {
+ event.conditionSchema.parse(condition);
+ } catch (err) {
+ const message = err instanceof z.ZodError ? err.issues.map((i) => i.message).join(", ") : "Invalid condition";
+ throw new BadRequestError({ message: `Invalid alert condition: ${message}` });
}
-
- return event;
};
const $assembleResponse = (alert: TAlerts, channels: TAlertChannelEmbedded[]): TAlertResponse => ({
@@ -120,7 +112,8 @@ export const alertServiceFactory = ({
}
const provider = $getProvider(dto.resourceType);
- const event = $validate(provider, dto, { alwaysValidateCondition: true }) as TAlertEventDefinition;
+ const event = $getEvent(provider, dto.eventType);
+ $validateCondition(event, dto.condition);
await $assertAlertPermission(
provider,
@@ -337,7 +330,7 @@ export const alertServiceFactory = ({
dto
);
- if (dto.condition !== undefined) $validate(provider, { condition: dto.condition });
+ if (dto.condition !== undefined) $validateCondition($getEvent(provider, alert.eventType), dto.condition);
if (dto.channels !== undefined && dto.channels.length === 0) {
throw new BadRequestError({ message: "At least one channel is required" });
}
diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.ts
index 1ac3764053..b730cee858 100644
--- a/backend/src/services/alert/alert-types.ts
+++ b/backend/src/services/alert/alert-types.ts
@@ -17,6 +17,7 @@ export enum AlertTriggerType {
export type TAlertEventDefinition = {
key: string;
triggerType: AlertTriggerType;
+ conditionSchema: z.ZodTypeAny;
};
export enum AlertRunStatus {
@@ -80,6 +81,7 @@ export type TFindTargetsByIdsInput = {
eventType: string;
condition: unknown;
targetIds: string[];
+ payload: Record<string, unknown>;
};
export type TFindDueTargetsInput = {
@@ -101,10 +103,8 @@ export type IEventAlertProvider<TTarget = unknown> = IResourceAlertProvider<TTar
export interface IResourceAlertProvider<TTarget = unknown> {
// Dot-namespaced, e.g. "pki.certificate", "identity.ua-secret".
resourceType: string;
- // Event keys this provider understands, each declaring how it fires.
+ // Event keys this provider understands, each declaring how it fires and what its condition looks like.
events: TAlertEventDefinition[];
- // Validates an alert's `condition` (the "when"), e.g. { alertBefore: "30d" }.
- conditionSchema: z.ZodTypeAny;
// Resources currently due to alert for this alert's scope + condition. The engine handles dedup
// afterwards, so this returns all current matches in the window (not minus already-alerted).
diff --git a/backend/src/services/alert/providers/identity-credential-alert-dal.ts b/backend/src/services/alert/providers/identity-credential-alert-dal.ts
index ffd8243369..c5bb3d5922 100644
--- a/backend/src/services/alert/providers/identity-credential-alert-dal.ts
+++ b/backend/src/services/alert/providers/identity-credential-alert-dal.ts
@@ -141,5 +141,36 @@ export const identityCredentialAlertDALFactory = (db: TDbClient) => {
}
};
- return { findExpiringUaClientSecrets, findIdentityInOrg, isIdentityInProject, getProjectType };
+ const findIdentitiesByIds = async (identityIds: string[]): Promise<{ id: string; name: string }[]> => {
+ if (identityIds.length === 0) return [];
+ try {
+ const rows = (await db(TableName.Identity).whereIn("id", identityIds).select("id", "name")) as {
+ id: string;
+ name: string;
+ }[];
+ return rows;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindIdentitiesByIds" });
+ }
+ };
+
+ const findUserLabelById = async (userId: string): Promise<string | undefined> => {
+ try {
+ const row = (await db(TableName.Users).where({ id: userId }).select("email", "username").first()) as
+ | { email: string | null; username: string }
+ | undefined;
+ return row ? (row.email ?? row.username) : undefined;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindUserLabelById" });
+ }
+ };
+
+ return {
+ findExpiringUaClientSecrets,
+ findIdentityInOrg,
+ isIdentityInProject,
+ getProjectType,
+ findIdentitiesByIds,
+ findUserLabelById
+ };
};
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 7b6a11a5f2..b37fd30104 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
@@ -1,6 +1,9 @@
import { createMongoAbility } from "@casl/ability";
import { vi } from "vitest";
+import { IdentityAuthMethod } from "@app/db/schemas";
+import { ActorType } from "@app/services/auth/auth-type";
+
import {
ALERT_HISTORY_RETENTION_DAYS,
AlertPermissionAction,
@@ -9,9 +12,13 @@ import {
} from "../alert-types";
import { TExpiringUaClientSecret } from "./identity-credential-alert-dal";
import {
+ IDENTITY_AUTH_METHOD_CHANGED_EVENT,
IDENTITY_AUTHENTICATION_EXPIRY_EVENT,
IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ IdentityAuthMethodChange,
+ IdentityAuthMethodChangePayloadSchema,
identityCredentialAlertProviderFactory,
+ TIdentityAuthMethodChangeEventPayload,
TIdentityCredentialAlertProviderDep
} from "./identity-credential-alert-provider";
@@ -59,8 +66,13 @@ const buildProvider = (opts?: {
// identity was created in project scope.
ownerProjectId?: string | null;
projectType?: string | null;
+ identities?: { id: string; name: string }[];
+ userLabel?: string;
}) => {
const dal = {
+ findIdentitiesByIds: async (ids: string[]) =>
+ (opts?.identities ?? [{ id: "ident-1", name: "ci-runner" }]).filter((identity) => ids.includes(identity.id)),
+ findUserLabelById: async () => opts?.userLabel,
findExpiringUaClientSecrets: async (args: {
orgId: string;
projectId?: string | null;
@@ -89,26 +101,266 @@ const buildProvider = (opts?: {
const actor = { actor: "user", actorId: "u1", actorAuthMethod: null, actorOrgId: "org-1" } as never;
+const eventSchema = (provider: ReturnType<typeof buildProvider>, key: string) =>
+ provider.events.find((event) => event.key === key)!.conditionSchema;
+
+const changePayload = (overrides: Record<string, unknown> = {}) => ({
+ targetIds: ["ident-1"],
+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actorType: ActorType.USER,
+ actorId: "u1",
+ changedAt: "2026-09-10T10:00:00.000Z",
+ ...overrides
+});
+
describe("identity credential alert provider", () => {
- 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: "90d" }).success).toBe(true);
+ test("expiry condition schema accepts 1d-90d and rejects everything else", () => {
+ const schema = eventSchema(buildProvider(), IDENTITY_AUTHENTICATION_EXPIRY_EVENT);
+ expect(schema.safeParse({ alertBefore: "1d" }).success).toBe(true);
+ expect(schema.safeParse({ alertBefore: "30d" }).success).toBe(true);
+ expect(schema.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);
+ expect(schema.safeParse({ alertBefore: "0d" }).success).toBe(false);
+ expect(schema.safeParse({ alertBefore: "91d" }).success).toBe(false);
+ expect(schema.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(schema.safeParse({ alertBefore: "2w" }).success).toBe(false);
+ expect(schema.safeParse({ alertBefore: "3m" }).success).toBe(false);
+ expect(schema.safeParse({ alertBefore: "1y" }).success).toBe(false);
+
+ expect(schema.safeParse({ alertBefore: "30" }).success).toBe(false);
+ expect(schema.safeParse({ alertBefore: "nope" }).success).toBe(false);
+ expect(schema.safeParse({}).success).toBe(false);
+ });
+
+ test("auth method change is event-triggered and takes no condition", () => {
+ const provider = buildProvider();
+ const event = provider.events.find((candidate) => candidate.key === IDENTITY_AUTH_METHOD_CHANGED_EVENT);
+ expect(event?.triggerType).toBe("event");
+ const schema = eventSchema(provider, IDENTITY_AUTH_METHOD_CHANGED_EVENT);
+ expect(schema.safeParse(null).success).toBe(true);
+ expect(schema.safeParse(undefined).success).toBe(true);
+ expect(schema.safeParse({}).success).toBe(true);
+ });
+
+ // The auth method services write this type at their emit sites and the provider parses the schema at
+ // delivery. This is the one place the two are checked against each other.
+ test("the emit-site payload type is accepted by the delivery schema", () => {
+ const payload = {
+ targetIds: ["ident-1"],
+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actorType: ActorType.USER,
+ actorId: "u1",
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload;
+ expect(IdentityAuthMethodChangePayloadSchema.safeParse(payload).success).toBe(true);
+
+ const withoutActorId = {
+ targetIds: ["ident-1"],
+ authMethod: IdentityAuthMethod.TOKEN_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actorType: ActorType.PLATFORM,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload;
+ expect(IdentityAuthMethodChangePayloadSchema.safeParse(withoutActorId).success).toBe(true);
+ });
+
+ test("findTargetsByIds rehydrates the identity and the change from the event payload", async () => {
+ const provider = buildProvider({ userLabel: "[email protected]" });
+
+ const targets = await provider.findTargetsByIds({
+ orgId: "org-1",
+ resourceId: "ident-1",
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ condition: null,
+ targetIds: ["ident-1"],
+ payload: changePayload()
+ });
- 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);
+ expect(targets).toHaveLength(1);
+ const [target] = targets;
+ expect(target.kind).toBe("auth-method-change");
+ if (target.kind !== "auth-method-change") throw new Error("unexpected target kind");
+ expect(target.identityName).toBe("ci-runner");
+ expect(target.authMethod).toBe(IdentityAuthMethod.UNIVERSAL_AUTH);
+ expect(target.change).toBe(IdentityAuthMethodChange.Added);
+ expect(target.actorLabel).toBe("[email protected] (user)");
+ expect(target.changedAt).toEqual(new Date("2026-09-10T10:00:00.000Z"));
+ expect(provider.targetId(target)).toBe("auth-method-change:ident-1:universal-auth:added");
+ });
+
+ test("findTargetsByIds drops an identity deleted between emit and delivery", async () => {
+ const provider = buildProvider({ identities: [] });
+ const targets = await provider.findTargetsByIds({
+ orgId: "org-1",
+ resourceId: "ident-1",
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ condition: null,
+ targetIds: ["ident-1"],
+ payload: changePayload()
+ });
+ expect(targets).toEqual([]);
+ });
+
+ test("findTargetsByIds names a machine identity actor and falls back to the actor type", async () => {
+ const provider = buildProvider({
+ identities: [
+ { id: "ident-1", name: "ci-runner" },
+ { id: "ident-admin", name: "terraform" }
+ ]
+ });
+ const byIdentity = await provider.findTargetsByIds({
+ orgId: "org-1",
+ resourceId: "ident-1",
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ condition: null,
+ targetIds: ["ident-1"],
+ payload: changePayload({ actorType: ActorType.IDENTITY, actorId: "ident-admin" })
+ });
+ expect(byIdentity[0].kind === "auth-method-change" && byIdentity[0].actorLabel).toBe(
+ "terraform (machine identity)"
+ );
+
+ const byPlatform = await provider.findTargetsByIds({
+ orgId: "org-1",
+ resourceId: "ident-1",
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ condition: null,
+ targetIds: ["ident-1"],
+ payload: changePayload({ actorType: ActorType.PLATFORM, actorId: undefined })
+ });
+ expect(byPlatform[0].kind === "auth-method-change" && byPlatform[0].actorLabel).toBe("Infisical");
+ });
+
+ // A drifted emit site must surface in the outbox error, not as a notification with blank fields.
+ test("findTargetsByIds rejects a payload the emitter contract does not describe", async () => {
+ const provider = buildProvider();
+ await expect(
+ provider.findTargetsByIds({
+ orgId: "org-1",
+ resourceId: "ident-1",
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ condition: null,
+ targetIds: ["ident-1"],
+ payload: { targetIds: ["ident-1"], authMethod: "carrier-pigeon" }
+ })
+ ).rejects.toThrow(/authMethod/);
+ });
+
+ test("a credential change carries the credential through the payload, the target id, and the fields", async () => {
+ const provider = buildProvider({ userLabel: "[email protected]" });
+ const [target] = await provider.findTargetsByIds({
+ orgId: "org-1",
+ resourceId: "ident-1",
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ condition: null,
+ targetIds: ["ident-1"],
+ payload: changePayload({
+ change: IdentityAuthMethodChange.CredentialAdded,
+ credentialId: "sec-9",
+ credentialName: "github-actions"
+ })
+ });
+ if (target.kind !== "auth-method-change") throw new Error("unexpected target kind");
+ expect(target.credentialId).toBe("sec-9");
+ expect(target.credentialName).toBe("github-actions");
+ // Two secrets added to the same method must not collapse into one PagerDuty incident.
+ expect(provider.targetId(target)).toBe("auth-method-change:ident-1:universal-auth:credential-added:sec-9");
+
+ const context = alertContext({
+ resourceId: "ident-1",
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ condition: null
+ });
+ const payload = provider.buildPayload(context, [target], "https://app.infisical.com/x");
+ expect(payload.summary).toBe(
+ "Universal Auth client secret 'github-actions' was added to machine identity 'ci-runner'"
+ );
+ const [item] = payload.items;
+ expect(item.fields?.find((f) => f.label === "Change")?.value).toBe("Credential Added");
+ expect(item.fields?.find((f) => f.label === "Credential")?.value).toBe("github-actions");
+ });
+
+ test("a token revocation reads as a Token Auth credential change", async () => {
+ const provider = buildProvider();
+ const context = alertContext({
+ resourceId: "ident-1",
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ condition: null
+ });
+ const payload = provider.buildPayload(
+ context,
+ [
+ {
+ kind: "auth-method-change" as const,
+ identityId: "ident-1",
+ identityName: "ci-runner",
+ authMethod: IdentityAuthMethod.TOKEN_AUTH,
+ change: IdentityAuthMethodChange.CredentialRevoked,
+ actorLabel: "Infisical",
+ changedAt: new Date("2026-09-10T10:00:00.000Z"),
+ credentialId: "tok-1",
+ credentialName: "deploy"
+ }
+ ],
+ "https://app.infisical.com/x"
+ );
+ expect(payload.summary).toBe("Token Auth token 'deploy' was revoked from machine identity 'ci-runner'");
+ // No credential field when the change is to the method itself.
+ const methodOnly = provider.buildPayload(
+ context,
+ [
+ {
+ kind: "auth-method-change" as const,
+ identityId: "ident-1",
+ identityName: "ci-runner",
+ authMethod: IdentityAuthMethod.TOKEN_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actorLabel: "Infisical",
+ changedAt: new Date("2026-09-10T10:00:00.000Z")
+ }
+ ],
+ "https://app.infisical.com/x"
+ );
+ expect(methodOnly.items[0].fields?.some((f) => f.label === "Credential")).toBe(false);
+ });
+
+ test("buildPayload for an auth method change names the method, the change, and who made it", async () => {
+ const provider = buildProvider();
+ const context = alertContext({
+ resourceId: "ident-1",
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ condition: null
+ });
+ const changedAt = new Date("2026-09-10T10:00:00.000Z");
+ const target = {
+ kind: "auth-method-change" as const,
+ identityId: "ident-1",
+ identityName: "ci-runner",
+ authMethod: IdentityAuthMethod.AWS_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actorLabel: "[email protected] (user)",
+ changedAt
+ };
+ const payload = provider.buildPayload(context, [target], "https://app.infisical.com/x");
+
+ expect(payload.eventKey).toBe(IDENTITY_AUTH_METHOD_CHANGED_EVENT);
+ expect(payload.webhookType).toBe("com.infisical.identity.authentication.auth-method-changed");
+ expect(payload.severity).toBe("warning");
+ expect(payload.summary).toBe("AWS Auth was removed from machine identity 'ci-runner'");
+ expect(payload.alert).not.toHaveProperty("condition");
+
+ const [item] = payload.items;
+ expect(item.id).toBe("auth-method-change:ident-1:aws-auth:removed");
+ expect(item.title).toBe("ci-runner");
+ expect(item.fields?.find((f) => f.label === "Auth Method")?.value).toBe("AWS Auth");
+ expect(item.fields?.find((f) => f.label === "Change")?.value).toBe("Removed");
+ expect(item.fields?.find((f) => f.label === "Changed By")?.value).toBe("[email protected] (user)");
+ expect(item.fields?.find((f) => f.label === "Changed At")?.value).toContain("2026");
});
test("findDueTargets converts alertBefore to a postgres interval and tags credential type", async () => {
@@ -168,7 +420,11 @@ describe("identity credential alert provider", () => {
test("buildPayload produces neutral items and severity", async () => {
const provider = buildProvider();
const expiresAt = futureDate(3);
- const target = { credentialType: "ua-client-secret" as const, ...sampleSecret({ expiresAt }) };
+ const target = {
+ kind: "expiring-credential" as const,
+ credentialType: "ua-client-secret" as const,
+ ...sampleSecret({ expiresAt })
+ };
const viewUrl = await provider.buildViewUrl(alertContext());
const payload = provider.buildPayload(alertContext(), [target], viewUrl);
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 3a96685429..5dd69581a7 100644
--- a/backend/src/services/alert/providers/identity-credential-alert-provider.ts
+++ b/backend/src/services/alert/providers/identity-credential-alert-provider.ts
@@ -2,12 +2,13 @@ import { ForbiddenError, subject } from "@casl/ability";
import RE2 from "re2";
import { z } from "zod";
-import { ActionProjectType, OrganizationActionScope, ProjectType } from "@app/db/schemas";
+import { ActionProjectType, IdentityAuthMethod, OrganizationActionScope, ProjectType } from "@app/db/schemas";
import { OrgPermissionIdentityActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
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 { ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { ActorType } from "@app/services/auth/auth-type";
import { TAlertPayload, TAlertSeverity } from "../alert-channel-types";
import {
@@ -16,16 +17,111 @@ import {
AlertPermissionAction,
AlertTriggerType,
DEFAULT_DEDUP_WINDOW_HOURS,
+ IEventAlertProvider,
IScheduledAlertProvider,
MAX_DEDUP_WINDOW_HOURS,
TAlertContext,
TAlertPermissionInput,
- TFindDueTargetsInput
+ TFindDueTargetsInput,
+ TFindTargetsByIdsInput
} from "../alert-types";
import { TExpiringUaClientSecret, TIdentityCredentialAlertDALFactory } from "./identity-credential-alert-dal";
export const IDENTITY_AUTHENTICATION_RESOURCE_TYPE = "identity.authentication";
export const IDENTITY_AUTHENTICATION_EXPIRY_EVENT = "identity.authentication.expiry";
+export const IDENTITY_AUTH_METHOD_CHANGED_EVENT = "identity.authentication.auth-method-changed";
+
+export enum IdentityAuthMethodChange {
+ Added = "added",
+ Updated = "updated",
+ Removed = "removed",
+ CredentialAdded = "credential-added",
+ CredentialUpdated = "credential-updated",
+ CredentialRevoked = "credential-revoked"
+}
+
+export const IdentityAuthMethodChangePayloadSchema = z.object({
+ authMethod: z.nativeEnum(IdentityAuthMethod),
+ change: z.nativeEnum(IdentityAuthMethodChange),
+ actorType: z.nativeEnum(ActorType),
+ actorId: z.string().optional(),
+ changedAt: z.coerce.date(),
+ credentialId: z.string().optional(),
+ credentialName: z.string().optional()
+});
+
+export type TIdentityAuthMethodChangePayload = z.infer<typeof IdentityAuthMethodChangePayloadSchema>;
+
+export type TIdentityAuthMethodChangeEventPayload = {
+ targetIds: string[];
+ authMethod: IdentityAuthMethod;
+ change: IdentityAuthMethodChange;
+ actorType: ActorType;
+ actorId?: string;
+ changedAt: string;
+ credentialId?: string;
+ credentialName?: string;
+};
+
+const IdentityAuthMethodChangeConditionSchema = z.object({}).nullish();
+
+export const IDENTITY_AUTH_METHOD_LABELS: Record<IdentityAuthMethod, string> = {
+ [IdentityAuthMethod.TOKEN_AUTH]: "Token Auth",
+ [IdentityAuthMethod.UNIVERSAL_AUTH]: "Universal Auth",
+ [IdentityAuthMethod.KUBERNETES_AUTH]: "Kubernetes Auth",
+ [IdentityAuthMethod.GCP_AUTH]: "GCP Auth",
+ [IdentityAuthMethod.ALICLOUD_AUTH]: "Alibaba Cloud Auth",
+ [IdentityAuthMethod.AWS_AUTH]: "AWS Auth",
+ [IdentityAuthMethod.AZURE_AUTH]: "Azure Auth",
+ [IdentityAuthMethod.TLS_CERT_AUTH]: "TLS Certificate Auth",
+ [IdentityAuthMethod.OCI_AUTH]: "OCI Auth",
+ [IdentityAuthMethod.OIDC_AUTH]: "OIDC Auth",
+ [IdentityAuthMethod.JWT_AUTH]: "JWT Auth",
+ [IdentityAuthMethod.LDAP_AUTH]: "LDAP Auth",
+ [IdentityAuthMethod.SPIFFE_AUTH]: "SPIFFE Auth"
+};
+
+const AUTH_METHOD_CHANGE_LABEL: Record<IdentityAuthMethodChange, string> = {
+ [IdentityAuthMethodChange.Added]: "Added",
+ [IdentityAuthMethodChange.Updated]: "Updated",
+ [IdentityAuthMethodChange.Removed]: "Removed",
+ [IdentityAuthMethodChange.CredentialAdded]: "Credential Added",
+ [IdentityAuthMethodChange.CredentialUpdated]: "Credential Updated",
+ [IdentityAuthMethodChange.CredentialRevoked]: "Credential Revoked"
+};
+
+const AUTH_METHOD_CHANGE_VERB: Record<IdentityAuthMethodChange, string> = {
+ [IdentityAuthMethodChange.Added]: "was added to",
+ [IdentityAuthMethodChange.Updated]: "was updated on",
+ [IdentityAuthMethodChange.Removed]: "was removed from",
+ [IdentityAuthMethodChange.CredentialAdded]: "was added to",
+ [IdentityAuthMethodChange.CredentialUpdated]: "was updated on",
+ [IdentityAuthMethodChange.CredentialRevoked]: "was revoked from"
+};
+
+const CREDENTIAL_KIND_LABEL: Partial<Record<IdentityAuthMethod, string>> = {
+ [IdentityAuthMethod.UNIVERSAL_AUTH]: "client secret",
+ [IdentityAuthMethod.TOKEN_AUTH]: "token"
+};
+
+const isCredentialChange = (change: IdentityAuthMethodChange): boolean =>
+ change === IdentityAuthMethodChange.CredentialAdded ||
+ change === IdentityAuthMethodChange.CredentialUpdated ||
+ change === IdentityAuthMethodChange.CredentialRevoked;
+
+const describeSubject = (target: TAuthMethodChangeTarget): string => {
+ const method = IDENTITY_AUTH_METHOD_LABELS[target.authMethod];
+ if (!isCredentialChange(target.change)) return method;
+ const kind = CREDENTIAL_KIND_LABEL[target.authMethod] ?? "credential";
+ return target.credentialName ? `${method} ${kind} '${target.credentialName}'` : `${method} ${kind}`;
+};
+
+const ACTOR_TYPE_LABEL: Partial<Record<ActorType, string>> = {
+ [ActorType.USER]: "user",
+ [ActorType.IDENTITY]: "machine identity",
+ [ActorType.PLATFORM]: "Infisical",
+ [ActorType.SCIM_CLIENT]: "SCIM client"
+};
const alertBeforeRegex = new RE2("^\\d+d$");
const MIN_ALERT_BEFORE_DAYS = 1;
@@ -51,7 +147,24 @@ const IdentityCredentialConditionSchema = z.object({
const DAILY_REPEAT_DEDUP_WINDOW_HOURS = 20;
-type TIdentityCredentialTarget = { credentialType: "ua-client-secret" } & TExpiringUaClientSecret;
+type TExpiringCredentialTarget = {
+ kind: "expiring-credential";
+ credentialType: "ua-client-secret";
+} & TExpiringUaClientSecret;
+
+type TAuthMethodChangeTarget = {
+ kind: "auth-method-change";
+ identityId: string;
+ identityName: string;
+ authMethod: IdentityAuthMethod;
+ change: IdentityAuthMethodChange;
+ actorLabel: string;
+ changedAt: Date;
+ credentialId?: string;
+ credentialName?: string;
+};
+
+type TIdentityCredentialTarget = TExpiringCredentialTarget | TAuthMethodChangeTarget;
// "1d" -> "1 day", "30d" -> "30 days"
const humanizeAlertBefore = (alertBefore: string): string => {
@@ -61,7 +174,7 @@ const humanizeAlertBefore = (alertBefore: string): string => {
const daysUntil = (date: Date): number => Math.ceil((new Date(date).getTime() - Date.now()) / (1000 * 60 * 60 * 24));
-const formatExpiry = (date: Date): string =>
+const formatUtcDate = (date: Date): string =>
new Date(date).toLocaleString("en-US", {
year: "numeric",
month: "long",
@@ -72,7 +185,7 @@ const formatExpiry = (date: Date): string =>
timeZoneName: "short"
});
-const severityFor = (targets: TIdentityCredentialTarget[]): TAlertSeverity => {
+const severityFor = (targets: TExpiringCredentialTarget[]): TAlertSeverity => {
const minDays = Math.min(...targets.map((t) => daysUntil(t.expiresAt)));
if (minDays <= 7) return "critical";
if (minDays <= 14) return "error";
@@ -80,7 +193,7 @@ const severityFor = (targets: TIdentityCredentialTarget[]): TAlertSeverity => {
return "info";
};
-const CREDENTIAL_TYPE_LABEL: Record<TIdentityCredentialTarget["credentialType"], string> = {
+const CREDENTIAL_TYPE_LABEL: Record<TExpiringCredentialTarget["credentialType"], string> = {
"ua-client-secret": "Universal Auth Client Secret"
};
@@ -89,12 +202,22 @@ export type TIdentityCredentialAlertProviderDep = {
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;
};
-const targetId = (target: TIdentityCredentialTarget): string => `${target.credentialType}:${target.id}`;
+const targetId = (target: TIdentityCredentialTarget): string =>
+ target.kind === "auth-method-change"
+ ? [
+ "auth-method-change",
+ target.identityId,
+ target.authMethod,
+ target.change,
+ ...(target.credentialId ? [target.credentialId] : [])
+ ].join(":")
+ : `${target.credentialType}:${target.id}`;
export const identityCredentialAlertProviderFactory = ({
identityCredentialAlertDAL,
permissionService
-}: TIdentityCredentialAlertProviderDep): IScheduledAlertProvider<TIdentityCredentialTarget> => {
+}: TIdentityCredentialAlertProviderDep): IScheduledAlertProvider<TIdentityCredentialTarget> &
+ IEventAlertProvider<TIdentityCredentialTarget> => {
const projectBaseUrl = (
siteUrl: string | undefined,
orgId: string,
@@ -142,22 +265,112 @@ export const identityCredentialAlertProviderFactory = ({
asOf: input.asOf
});
- return uaSecrets.map((secret) => ({ credentialType: "ua-client-secret" as const, ...secret }));
+ return uaSecrets.map((secret) => ({
+ kind: "expiring-credential" as const,
+ credentialType: "ua-client-secret" as const,
+ ...secret
+ }));
};
- const buildPayload = (alert: TAlertContext, targets: TIdentityCredentialTarget[], viewUrl: string): TAlertPayload => {
+ const resolveActorLabel = async (actorType: ActorType, actorId?: string): Promise<string> => {
+ const typeLabel = ACTOR_TYPE_LABEL[actorType] ?? actorType;
+ if (!actorId) return typeLabel;
+
+ if (actorType === ActorType.USER) {
+ const label = await identityCredentialAlertDAL.findUserLabelById(actorId);
+ return label ? `${label} (user)` : typeLabel;
+ }
+ if (actorType === ActorType.IDENTITY) {
+ const [identity] = await identityCredentialAlertDAL.findIdentitiesByIds([actorId]);
+ return identity ? `${identity.name} (machine identity)` : typeLabel;
+ }
+ return typeLabel;
+ };
+
+ const findTargetsByIds = async (input: TFindTargetsByIdsInput): Promise<TIdentityCredentialTarget[]> => {
+ if (input.eventType !== IDENTITY_AUTH_METHOD_CHANGED_EVENT) return [];
+
+ const parsed = IdentityAuthMethodChangePayloadSchema.safeParse(input.payload);
+ if (!parsed.success) {
+ throw new Error(
+ `Unreadable '${IDENTITY_AUTH_METHOD_CHANGED_EVENT}' payload: ${parsed.error.issues
+ .map((issue) => `${issue.path.join(".")} ${issue.message}`)
+ .join(", ")}`
+ );
+ }
+ const change = parsed.data;
+
+ const identities = await identityCredentialAlertDAL.findIdentitiesByIds(input.targetIds);
+ if (identities.length === 0) return [];
+
+ const actorLabel = await resolveActorLabel(change.actorType, change.actorId);
+
+ return identities.map((identity) => ({
+ kind: "auth-method-change" as const,
+ identityId: identity.id,
+ identityName: identity.name,
+ authMethod: change.authMethod,
+ change: change.change,
+ actorLabel,
+ changedAt: change.changedAt,
+ ...(change.credentialId ? { credentialId: change.credentialId } : {}),
+ ...(change.credentialName ? { credentialName: change.credentialName } : {})
+ }));
+ };
+
+ const buildAlertBlock = (alert: TAlertContext, viewUrl: string, condition?: string): TAlertPayload["alert"] => ({
+ id: alert.id,
+ name: alert.name,
+ orgId: alert.orgId,
+ ...(alert.projectId ? { projectId: alert.projectId } : {}),
+ resourceType: alert.resourceType,
+ ...(condition ? { condition } : {}),
+ viewUrl
+ });
+
+ const buildAuthMethodChangePayload = (
+ alert: TAlertContext,
+ targets: TAuthMethodChangeTarget[],
+ viewUrl: string
+ ): TAlertPayload => {
+ const [first] = targets;
+ const summary =
+ targets.length === 1
+ ? `${describeSubject(first)} ${AUTH_METHOD_CHANGE_VERB[first.change]} machine identity '${first.identityName}'`
+ : `${targets.length} machine identity auth method changes`;
+
+ return {
+ alert: buildAlertBlock(alert, viewUrl),
+ eventKey: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ eventLabel: "Auth Method Change",
+ webhookType: "com.infisical.identity.authentication.auth-method-changed",
+ resourceKind: "Machine Identity Authentication",
+ resourceOwnerKind: "Machine Identity",
+ severity: "warning",
+ summary,
+ items: targets.map((target) => ({
+ id: targetId(target),
+ title: target.identityName,
+ fields: [
+ { label: "Auth Method", value: IDENTITY_AUTH_METHOD_LABELS[target.authMethod] },
+ { label: "Change", value: AUTH_METHOD_CHANGE_LABEL[target.change] },
+ ...(target.credentialName ? [{ label: "Credential", value: target.credentialName }] : []),
+ { label: "Changed By", value: target.actorLabel },
+ { label: "Changed At", value: formatUtcDate(target.changedAt) }
+ ]
+ }))
+ };
+ };
+
+ const buildExpiryPayload = (
+ alert: TAlertContext,
+ targets: TExpiringCredentialTarget[],
+ viewUrl: string
+ ): TAlertPayload => {
const alertBefore = (alert.condition as { alertBefore?: string } | null)?.alertBefore;
return {
- alert: {
- id: alert.id,
- name: alert.name,
- orgId: alert.orgId,
- ...(alert.projectId ? { projectId: alert.projectId } : {}),
- resourceType: alert.resourceType,
- ...(alertBefore ? { condition: alertBefore } : {}),
- viewUrl
- },
+ alert: buildAlertBlock(alert, viewUrl, alertBefore),
eventKey: IDENTITY_AUTHENTICATION_EXPIRY_EVENT,
eventLabel: "Expiration",
webhookType: "com.infisical.identity.authentication.expiration",
@@ -173,12 +386,27 @@ export const identityCredentialAlertProviderFactory = ({
fields: [
{ label: "Secret Name", value: target.description || target.clientSecretPrefix },
{ label: "Secret Type", value: CREDENTIAL_TYPE_LABEL[target.credentialType] },
- { label: "Expires", value: formatExpiry(target.expiresAt) }
+ { label: "Expires", value: formatUtcDate(target.expiresAt) }
]
}))
};
};
+ const buildPayload = (alert: TAlertContext, targets: TIdentityCredentialTarget[], viewUrl: string): TAlertPayload => {
+ if (alert.eventType === IDENTITY_AUTH_METHOD_CHANGED_EVENT) {
+ return buildAuthMethodChangePayload(
+ alert,
+ targets.filter((target): target is TAuthMethodChangeTarget => target.kind === "auth-method-change"),
+ viewUrl
+ );
+ }
+ return buildExpiryPayload(
+ alert,
+ targets.filter((target): target is TExpiringCredentialTarget => target.kind === "expiring-credential"),
+ viewUrl
+ );
+ };
+
const assertResourceInScope = async (input: {
orgId: string;
projectId?: string | null;
@@ -266,9 +494,20 @@ export const identityCredentialAlertProviderFactory = ({
return {
resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
- events: [{ key: IDENTITY_AUTHENTICATION_EXPIRY_EVENT, triggerType: AlertTriggerType.Scheduled }],
- conditionSchema: IdentityCredentialConditionSchema,
+ events: [
+ {
+ key: IDENTITY_AUTHENTICATION_EXPIRY_EVENT,
+ triggerType: AlertTriggerType.Scheduled,
+ conditionSchema: IdentityCredentialConditionSchema
+ },
+ {
+ key: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ triggerType: AlertTriggerType.Event,
+ conditionSchema: IdentityAuthMethodChangeConditionSchema
+ }
+ ],
findDueTargets,
+ findTargetsByIds,
buildViewUrl,
buildPayload,
targetId,
diff --git a/backend/src/services/identity-alicloud-auth/identity-alicloud-auth-service.ts b/backend/src/services/identity-alicloud-auth/identity-alicloud-auth-service.ts
index 324e47601a..b7a4e8dcee 100644
--- a/backend/src/services/identity-alicloud-auth/identity-alicloud-auth-service.ts
+++ b/backend/src/services/identity-alicloud-auth/identity-alicloud-auth-service.ts
@@ -33,6 +33,13 @@ import {
authAttemptCounter,
recordAuthAttemptMetric
} from "@app/lib/telemetry/metrics";
+import {
+ IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ IdentityAuthMethodChange,
+ TIdentityAuthMethodChangeEventPayload
+} from "@app/services/alert/providers/identity-credential-alert-provider";
+import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -68,6 +75,7 @@ type TIdentityAliCloudAuthServiceFactoryDep = {
TIdentityAccessTokenServiceFactory,
"issueIdentityAccessToken" | "revokeTokensForIdentityAuthMethod" | "invalidateTrustedIpsCache"
>;
+ eventOutboxService: TEventOutboxEmitter;
};
export type TIdentityAliCloudAuthServiceFactory = ReturnType<typeof identityAliCloudAuthServiceFactory>;
@@ -81,7 +89,8 @@ export const identityAliCloudAuthServiceFactory = ({
licenseService,
permissionService,
orgDAL,
- identityAccessTokenService
+ identityAccessTokenService,
+ eventOutboxService
}: TIdentityAliCloudAuthServiceFactoryDep) => {
const login = async ({ identityId, organizationSlug, ...params }: TLoginAliCloudAuthDTO) => {
const authMetricStartTime = performance.now();
@@ -344,6 +353,24 @@ export const identityAliCloudAuthServiceFactory = ({
},
tx
);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.ALICLOUD_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.ALICLOUD_AUTH);
@@ -439,14 +466,39 @@ export const identityAliCloudAuthServiceFactory = ({
return extractIPDetails(accessTokenTrustedIp.ipAddress);
});
- const updatedAliCloudAuth = await identityAliCloudAuthDAL.updateById(identityAliCloudAuth.id, {
- allowedArns,
- accessTokenMaxTTL,
- accessTokenTTL,
- accessTokenNumUsesLimit,
- accessTokenTrustedIps: reformattedAccessTokenTrustedIps
- ? JSON.stringify(reformattedAccessTokenTrustedIps)
- : undefined
+ const updatedAliCloudAuth = await identityAliCloudAuthDAL.transaction(async (tx) => {
+ const doc = await identityAliCloudAuthDAL.updateById(
+ identityAliCloudAuth.id,
+ {
+ allowedArns,
+ accessTokenMaxTTL,
+ accessTokenTTL,
+ accessTokenNumUsesLimit,
+ accessTokenTrustedIps: reformattedAccessTokenTrustedIps
+ ? JSON.stringify(reformattedAccessTokenTrustedIps)
+ : undefined
+ },
+ tx
+ );
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.ALICLOUD_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.ALICLOUD_AUTH);
@@ -591,6 +643,24 @@ export const identityAliCloudAuthServiceFactory = ({
const deletedAliCloudAuth = await identityAliCloudAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.ALICLOUD_AUTH }, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.ALICLOUD_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return { ...deletedAliCloudAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };
});
diff --git a/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts b/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts
index 1512900334..13f3805014 100644
--- a/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts
+++ b/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts
@@ -34,6 +34,13 @@ import {
authAttemptCounter,
recordAuthAttemptMetric
} from "@app/lib/telemetry/metrics";
+import {
+ IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ IdentityAuthMethodChange,
+ TIdentityAuthMethodChangeEventPayload
+} from "@app/services/alert/providers/identity-credential-alert-provider";
+import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -68,6 +75,7 @@ type TIdentityAwsAuthServiceFactoryDep = {
TIdentityAccessTokenServiceFactory,
"issueIdentityAccessToken" | "revokeTokensForIdentityAuthMethod" | "invalidateTrustedIpsCache"
>;
+ eventOutboxService: TEventOutboxEmitter;
};
export type TIdentityAwsAuthServiceFactory = ReturnType<typeof identityAwsAuthServiceFactory>;
@@ -115,7 +123,8 @@ export const identityAwsAuthServiceFactory = ({
licenseService,
permissionService,
orgDAL,
- identityAccessTokenService
+ identityAccessTokenService,
+ eventOutboxService
}: TIdentityAwsAuthServiceFactoryDep) => {
const login = async ({
identityId,
@@ -444,6 +453,24 @@ export const identityAwsAuthServiceFactory = ({
},
tx
);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.AWS_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.AWS_AUTH);
@@ -540,16 +567,41 @@ export const identityAwsAuthServiceFactory = ({
return extractIPDetails(accessTokenTrustedIp.ipAddress);
});
- const updatedAwsAuth = await identityAwsAuthDAL.updateById(identityAwsAuth.id, {
- stsEndpoint,
- allowedPrincipalArns,
- allowedAccountIds,
- accessTokenMaxTTL,
- accessTokenTTL,
- accessTokenNumUsesLimit,
- accessTokenTrustedIps: reformattedAccessTokenTrustedIps
- ? JSON.stringify(reformattedAccessTokenTrustedIps)
- : undefined
+ const updatedAwsAuth = await identityAwsAuthDAL.transaction(async (tx) => {
+ const doc = await identityAwsAuthDAL.updateById(
+ identityAwsAuth.id,
+ {
+ stsEndpoint,
+ allowedPrincipalArns,
+ allowedAccountIds,
+ accessTokenMaxTTL,
+ accessTokenTTL,
+ accessTokenNumUsesLimit,
+ accessTokenTrustedIps: reformattedAccessTokenTrustedIps
+ ? JSON.stringify(reformattedAccessTokenTrustedIps)
+ : undefined
+ },
+ tx
+ );
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.AWS_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.AWS_AUTH);
@@ -693,6 +745,24 @@ export const identityAwsAuthServiceFactory = ({
const deletedAwsAuth = await identityAwsAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.AWS_AUTH }, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.AWS_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return { ...deletedAwsAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };
});
diff --git a/backend/src/services/identity-azure-auth/identity-azure-auth-service.ts b/backend/src/services/identity-azure-auth/identity-azure-auth-service.ts
index 059bb6b717..dcb93fe206 100644
--- a/backend/src/services/identity-azure-auth/identity-azure-auth-service.ts
+++ b/backend/src/services/identity-azure-auth/identity-azure-auth-service.ts
@@ -29,6 +29,13 @@ import {
authAttemptCounter,
recordAuthAttemptMetric
} from "@app/lib/telemetry/metrics";
+import {
+ IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ IdentityAuthMethodChange,
+ TIdentityAuthMethodChangeEventPayload
+} from "@app/services/alert/providers/identity-credential-alert-provider";
+import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -64,6 +71,7 @@ type TIdentityAzureAuthServiceFactoryDep = {
TIdentityAccessTokenServiceFactory,
"issueIdentityAccessToken" | "revokeTokensForIdentityAuthMethod" | "invalidateTrustedIpsCache"
>;
+ eventOutboxService: TEventOutboxEmitter;
};
export type TIdentityAzureAuthServiceFactory = ReturnType<typeof identityAzureAuthServiceFactory>;
@@ -77,7 +85,8 @@ export const identityAzureAuthServiceFactory = ({
permissionService,
licenseService,
orgDAL,
- identityAccessTokenService
+ identityAccessTokenService,
+ eventOutboxService
}: TIdentityAzureAuthServiceFactoryDep) => {
const login = async ({ identityId, jwt: azureJwt, organizationSlug }: TLoginAzureAuthDTO) => {
const authMetricStartTime = performance.now();
@@ -345,6 +354,24 @@ export const identityAzureAuthServiceFactory = ({
tx
);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.AZURE_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.AZURE_AUTH);
@@ -441,16 +468,41 @@ export const identityAzureAuthServiceFactory = ({
return extractIPDetails(accessTokenTrustedIp.ipAddress);
});
- const updatedAzureAuth = await identityAzureAuthDAL.updateById(identityGcpAuth.id, {
- tenantId,
- resource,
- allowedServicePrincipalIds,
- accessTokenMaxTTL,
- accessTokenTTL,
- accessTokenNumUsesLimit,
- accessTokenTrustedIps: reformattedAccessTokenTrustedIps
- ? JSON.stringify(reformattedAccessTokenTrustedIps)
- : undefined
+ const updatedAzureAuth = await identityAzureAuthDAL.transaction(async (tx) => {
+ const doc = await identityAzureAuthDAL.updateById(
+ identityGcpAuth.id,
+ {
+ tenantId,
+ resource,
+ allowedServicePrincipalIds,
+ accessTokenMaxTTL,
+ accessTokenTTL,
+ accessTokenNumUsesLimit,
+ accessTokenTrustedIps: reformattedAccessTokenTrustedIps
+ ? JSON.stringify(reformattedAccessTokenTrustedIps)
+ : undefined
+ },
+ tx
+ );
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.AZURE_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.AZURE_AUTH);
@@ -595,6 +647,24 @@ export const identityAzureAuthServiceFactory = ({
const deletedAzureAuth = await identityAzureAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.AZURE_AUTH }, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.AZURE_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return { ...deletedAzureAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };
});
diff --git a/backend/src/services/identity-gcp-auth/identity-gcp-auth-service.ts b/backend/src/services/identity-gcp-auth/identity-gcp-auth-service.ts
index 8f0c5a6892..f6ec6d7d76 100644
--- a/backend/src/services/identity-gcp-auth/identity-gcp-auth-service.ts
+++ b/backend/src/services/identity-gcp-auth/identity-gcp-auth-service.ts
@@ -29,6 +29,13 @@ import {
authAttemptCounter,
recordAuthAttemptMetric
} from "@app/lib/telemetry/metrics";
+import {
+ IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ IdentityAuthMethodChange,
+ TIdentityAuthMethodChangeEventPayload
+} from "@app/services/alert/providers/identity-credential-alert-provider";
+import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -62,6 +69,7 @@ type TIdentityGcpAuthServiceFactoryDep = {
TIdentityAccessTokenServiceFactory,
"issueIdentityAccessToken" | "revokeTokensForIdentityAuthMethod" | "invalidateTrustedIpsCache"
>;
+ eventOutboxService: TEventOutboxEmitter;
};
export type TIdentityGcpAuthServiceFactory = ReturnType<typeof identityGcpAuthServiceFactory>;
@@ -75,7 +83,8 @@ export const identityGcpAuthServiceFactory = ({
permissionService,
licenseService,
orgDAL,
- identityAccessTokenService
+ identityAccessTokenService,
+ eventOutboxService
}: TIdentityGcpAuthServiceFactoryDep) => {
const login = async ({ identityId, jwt: gcpJwt, organizationSlug }: TLoginGcpAuthDTO) => {
const authMetricStartTime = performance.now();
@@ -390,6 +399,24 @@ export const identityGcpAuthServiceFactory = ({
},
tx
);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.GCP_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.GCP_AUTH);
@@ -487,17 +514,42 @@ export const identityGcpAuthServiceFactory = ({
return extractIPDetails(accessTokenTrustedIp.ipAddress);
});
- const updatedGcpAuth = await identityGcpAuthDAL.updateById(identityGcpAuth.id, {
- type,
- allowedServiceAccounts,
- allowedProjects,
- allowedZones,
- accessTokenMaxTTL,
- accessTokenTTL,
- accessTokenNumUsesLimit,
- accessTokenTrustedIps: reformattedAccessTokenTrustedIps
- ? JSON.stringify(reformattedAccessTokenTrustedIps)
- : undefined
+ const updatedGcpAuth = await identityGcpAuthDAL.transaction(async (tx) => {
+ const doc = await identityGcpAuthDAL.updateById(
+ identityGcpAuth.id,
+ {
+ type,
+ allowedServiceAccounts,
+ allowedProjects,
+ allowedZones,
+ accessTokenMaxTTL,
+ accessTokenTTL,
+ accessTokenNumUsesLimit,
+ accessTokenTrustedIps: reformattedAccessTokenTrustedIps
+ ? JSON.stringify(reformattedAccessTokenTrustedIps)
+ : undefined
+ },
+ tx
+ );
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.GCP_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.GCP_AUTH);
@@ -642,6 +694,24 @@ export const identityGcpAuthServiceFactory = ({
const deletedGcpAuth = await identityGcpAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.GCP_AUTH }, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.GCP_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return { ...deletedGcpAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };
});
diff --git a/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts b/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts
index 0a8e14db1d..96e9d025a5 100644
--- a/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts
+++ b/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts
@@ -41,6 +41,13 @@ import {
} from "@app/lib/telemetry/metrics";
import { getValueByDot } from "@app/lib/template/dot-access";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
+import {
+ IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ IdentityAuthMethodChange,
+ TIdentityAuthMethodChangeEventPayload
+} from "@app/services/alert/providers/identity-credential-alert-provider";
+import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -77,6 +84,7 @@ type TIdentityJwtAuthServiceFactoryDep = {
TIdentityAccessTokenServiceFactory,
"issueIdentityAccessToken" | "revokeTokensForIdentityAuthMethod" | "invalidateTrustedIpsCache"
>;
+ eventOutboxService: TEventOutboxEmitter;
};
export type TIdentityJwtAuthServiceFactory = ReturnType<typeof identityJwtAuthServiceFactory>;
@@ -91,7 +99,8 @@ export const identityJwtAuthServiceFactory = ({
identityAccessTokenDAL,
kmsService,
orgDAL,
- identityAccessTokenService
+ identityAccessTokenService,
+ eventOutboxService
}: TIdentityJwtAuthServiceFactoryDep) => {
const login = async ({ identityId, jwt: jwtValue, organizationSlug }: TLoginJwtAuthDTO) => {
const authMetricStartTime = performance.now();
@@ -534,6 +543,24 @@ export const identityJwtAuthServiceFactory = ({
tx
);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.JWT_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.JWT_AUTH);
@@ -677,7 +704,28 @@ export const identityJwtAuthServiceFactory = ({
updateQuery.encryptedPublicKeys = encryptedPublicKeys;
}
- const updatedJwtAuth = await identityJwtAuthDAL.updateById(identityJwtAuth.id, updateQuery);
+ const updatedJwtAuth = await identityJwtAuthDAL.transaction(async (tx) => {
+ const doc = await identityJwtAuthDAL.updateById(identityJwtAuth.id, updateQuery, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.JWT_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return doc;
+ });
const decryptedJwksCaCert = orgDataKeyDecryptor({ cipherTextBlob: updatedJwtAuth.encryptedJwksCaCert }).toString();
const decryptedPublicKeys = orgDataKeyDecryptor({ cipherTextBlob: updatedJwtAuth.encryptedPublicKeys })
.toString()
@@ -848,6 +896,24 @@ export const identityJwtAuthServiceFactory = ({
const deletedJwtAuth = await identityJwtAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.JWT_AUTH }, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.JWT_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return { ...deletedJwtAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };
});
diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
index 604edf3e93..1145bee015 100644
--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
@@ -62,6 +62,13 @@ import {
} from "@app/lib/telemetry/metrics";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { getSharedHttpsAgent, safeRequest } from "@app/lib/validator/safe-request";
+import {
+ IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ IdentityAuthMethodChange,
+ TIdentityAuthMethodChangeEventPayload
+} from "@app/services/alert/providers/identity-credential-alert-provider";
+import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -127,6 +134,7 @@ type TIdentityKubernetesAuthServiceFactoryDep = {
TIdentityAccessTokenServiceFactory,
"issueIdentityAccessToken" | "revokeTokensForIdentityAuthMethod" | "invalidateTrustedIpsCache"
>;
+ eventOutboxService: TEventOutboxEmitter;
};
export type TIdentityKubernetesAuthServiceFactory = ReturnType<typeof identityKubernetesAuthServiceFactory>;
@@ -150,7 +158,8 @@ export const identityKubernetesAuthServiceFactory = ({
gatewayPoolService,
gatewayPoolDAL,
orgDAL,
- identityAccessTokenService
+ identityAccessTokenService,
+ eventOutboxService
}: TIdentityKubernetesAuthServiceFactoryDep) => {
const $gatewayProxyWrapper = async <T>(
inputs: {
@@ -1136,6 +1145,24 @@ export const identityKubernetesAuthServiceFactory = ({
},
tx
);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.KUBERNETES_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return doc;
});
@@ -1596,7 +1623,28 @@ export const identityKubernetesAuthServiceFactory = ({
updateQuery.isTokenReviewerJwtTemplateSourced = false;
}
- const updatedKubernetesAuth = await identityKubernetesAuthDAL.updateById(identityKubernetesAuth.id, updateQuery);
+ const updatedKubernetesAuth = await identityKubernetesAuthDAL.transaction(async (tx) => {
+ const doc = await identityKubernetesAuthDAL.updateById(identityKubernetesAuth.id, updateQuery, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.KUBERNETES_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return doc;
+ });
const updatedCACert = updatedKubernetesAuth.encryptedKubernetesCaCertificate
? decryptor({
@@ -1796,6 +1844,24 @@ export const identityKubernetesAuthServiceFactory = ({
const revokedIdentityKubernetesAuth = await identityKubernetesAuthDAL.transaction(async (tx) => {
const deletedKubernetesAuth = await identityKubernetesAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.KUBERNETES_AUTH }, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.KUBERNETES_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return { ...deletedKubernetesAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };
});
diff --git a/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts
index 5ec50ff6bc..49cb17b2a4 100644
--- a/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts
+++ b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts
@@ -40,6 +40,13 @@ import {
recordAuthAttemptMetric
} from "@app/lib/telemetry/metrics";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
+import {
+ IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ IdentityAuthMethodChange,
+ TIdentityAuthMethodChangeEventPayload
+} from "@app/services/alert/providers/identity-credential-alert-provider";
+import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -96,6 +103,7 @@ type TIdentityLdapAuthServiceFactoryDep = {
TIdentityAccessTokenServiceFactory,
"issueIdentityAccessToken" | "revokeTokensForIdentityAuthMethod" | "invalidateTrustedIpsCache"
>;
+ eventOutboxService: TEventOutboxEmitter;
};
export type TIdentityLdapAuthServiceFactory = ReturnType<typeof identityLdapAuthServiceFactory>;
@@ -111,7 +119,8 @@ export const identityLdapAuthServiceFactory = ({
identityAuthTemplateDAL,
keyStore,
orgDAL,
- identityAccessTokenService
+ identityAccessTokenService,
+ eventOutboxService
}: TIdentityLdapAuthServiceFactoryDep) => {
const getLdapConfig = async (identityId: string) => {
const identity = await identityDAL.findOne({ id: identityId });
@@ -520,6 +529,24 @@ export const identityLdapAuthServiceFactory = ({
},
tx
);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.LDAP_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.LDAP_AUTH);
@@ -730,25 +757,50 @@ export const identityLdapAuthServiceFactory = ({
});
}
- const updatedLdapAuth = await identityLdapAuthDAL.updateById(identityLdapAuth.id, {
- url: config.url,
- searchBase: config.searchBase,
- searchFilter,
- encryptedBindDN,
- encryptedBindPass,
- encryptedLdapCaCertificate,
- allowedFields: allowedFields ? JSON.stringify(allowedFields) : undefined,
- accessTokenMaxTTL,
- templateId: template?.id || null,
- accessTokenTTL,
- accessTokenNumUsesLimit,
- accessTokenTrustedIps: reformattedAccessTokenTrustedIps
- ? JSON.stringify(reformattedAccessTokenTrustedIps)
- : undefined,
- lockoutEnabled,
- lockoutThreshold,
- lockoutDurationSeconds,
- lockoutCounterResetSeconds
+ const updatedLdapAuth = await identityLdapAuthDAL.transaction(async (tx) => {
+ const doc = await identityLdapAuthDAL.updateById(
+ identityLdapAuth.id,
+ {
+ url: config.url,
+ searchBase: config.searchBase,
+ searchFilter,
+ encryptedBindDN,
+ encryptedBindPass,
+ encryptedLdapCaCertificate,
+ allowedFields: allowedFields ? JSON.stringify(allowedFields) : undefined,
+ accessTokenMaxTTL,
+ templateId: template?.id || null,
+ accessTokenTTL,
+ accessTokenNumUsesLimit,
+ accessTokenTrustedIps: reformattedAccessTokenTrustedIps
+ ? JSON.stringify(reformattedAccessTokenTrustedIps)
+ : undefined,
+ lockoutEnabled,
+ lockoutThreshold,
+ lockoutDurationSeconds,
+ lockoutCounterResetSeconds
+ },
+ tx
+ );
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.LDAP_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.LDAP_AUTH);
@@ -905,6 +957,24 @@ export const identityLdapAuthServiceFactory = ({
const [deletedLdapAuth] = await identityLdapAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.LDAP_AUTH }, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.LDAP_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return { ...deletedLdapAuth, orgId: identityMembershipOrg.scopeOrgId };
});
diff --git a/backend/src/services/identity-oci-auth/identity-oci-auth-service.ts b/backend/src/services/identity-oci-auth/identity-oci-auth-service.ts
index 7c8f09cafd..d1b6e55c89 100644
--- a/backend/src/services/identity-oci-auth/identity-oci-auth-service.ts
+++ b/backend/src/services/identity-oci-auth/identity-oci-auth-service.ts
@@ -34,6 +34,13 @@ import {
authAttemptCounter,
recordAuthAttemptMetric
} from "@app/lib/telemetry/metrics";
+import {
+ IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ IdentityAuthMethodChange,
+ TIdentityAuthMethodChangeEventPayload
+} from "@app/services/alert/providers/identity-credential-alert-provider";
+import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -66,6 +73,7 @@ type TIdentityOciAuthServiceFactoryDep = {
TIdentityAccessTokenServiceFactory,
"issueIdentityAccessToken" | "revokeTokensForIdentityAuthMethod" | "invalidateTrustedIpsCache"
>;
+ eventOutboxService: TEventOutboxEmitter;
};
export type TIdentityOciAuthServiceFactory = ReturnType<typeof identityOciAuthServiceFactory>;
@@ -79,7 +87,8 @@ export const identityOciAuthServiceFactory = ({
licenseService,
permissionService,
orgDAL,
- identityAccessTokenService
+ identityAccessTokenService,
+ eventOutboxService
}: TIdentityOciAuthServiceFactoryDep) => {
const login = async ({ identityId, headers, userOcid, organizationSlug }: TLoginOciAuthDTO) => {
const authMetricStartTime = performance.now();
@@ -358,6 +367,24 @@ export const identityOciAuthServiceFactory = ({
},
tx
);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.OCI_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.OCI_AUTH);
@@ -454,15 +481,40 @@ export const identityOciAuthServiceFactory = ({
return extractIPDetails(accessTokenTrustedIp.ipAddress);
});
- const updatedOciAuth = await identityOciAuthDAL.updateById(identityOciAuth.id, {
- tenancyOcid,
- allowedUsernames,
- accessTokenMaxTTL,
- accessTokenTTL,
- accessTokenNumUsesLimit,
- accessTokenTrustedIps: reformattedAccessTokenTrustedIps
- ? JSON.stringify(reformattedAccessTokenTrustedIps)
- : undefined
+ const updatedOciAuth = await identityOciAuthDAL.transaction(async (tx) => {
+ const doc = await identityOciAuthDAL.updateById(
+ identityOciAuth.id,
+ {
+ tenancyOcid,
+ allowedUsernames,
+ accessTokenMaxTTL,
+ accessTokenTTL,
+ accessTokenNumUsesLimit,
+ accessTokenTrustedIps: reformattedAccessTokenTrustedIps
+ ? JSON.stringify(reformattedAccessTokenTrustedIps)
+ : undefined
+ },
+ tx
+ );
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.OCI_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.OCI_AUTH);
@@ -607,6 +659,24 @@ export const identityOciAuthServiceFactory = ({
const deletedOciAuth = await identityOciAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.OCI_AUTH }, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.OCI_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return { ...deletedOciAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };
});
diff --git a/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts b/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts
index 1dd60c3141..7f1ad40576 100644
--- a/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts
+++ b/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts
@@ -51,6 +51,13 @@ import {
} from "@app/lib/telemetry/metrics";
import { getValueByDot } from "@app/lib/template/dot-access";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
+import {
+ IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ IdentityAuthMethodChange,
+ TIdentityAuthMethodChangeEventPayload
+} from "@app/services/alert/providers/identity-credential-alert-provider";
+import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -87,6 +94,7 @@ type TIdentityOidcAuthServiceFactoryDep = {
TIdentityAccessTokenServiceFactory,
"issueIdentityAccessToken" | "revokeTokensForIdentityAuthMethod" | "invalidateTrustedIpsCache"
>;
+ eventOutboxService: TEventOutboxEmitter;
};
export type TIdentityOidcAuthServiceFactory = ReturnType<typeof identityOidcAuthServiceFactory>;
@@ -102,7 +110,8 @@ export const identityOidcAuthServiceFactory = ({
identityAccessTokenDAL,
kmsService,
orgDAL,
- identityAccessTokenService
+ identityAccessTokenService,
+ eventOutboxService
}: TIdentityOidcAuthServiceFactoryDep) => {
const login = async ({ identityId, jwt: oidcJwt, organizationSlug }: TLoginOidcAuthDTO) => {
const authMetricStartTime = performance.now();
@@ -767,6 +776,24 @@ export const identityOidcAuthServiceFactory = ({
},
tx
);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.OIDC_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.OIDC_AUTH);
@@ -972,7 +999,28 @@ export const identityOidcAuthServiceFactory = ({
updateQuery.encryptedCaCertificate = encryptor({ plainText: Buffer.from(caCert) }).cipherTextBlob;
}
- const updatedOidcAuth = await identityOidcAuthDAL.updateById(identityOidcAuth.id, updateQuery);
+ const updatedOidcAuth = await identityOidcAuthDAL.transaction(async (tx) => {
+ const doc = await identityOidcAuthDAL.updateById(identityOidcAuth.id, updateQuery, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.OIDC_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return doc;
+ });
const updatedCACert = updatedOidcAuth.encryptedCaCertificate
? decryptor({ cipherTextBlob: updatedOidcAuth.encryptedCaCertificate }).toString()
: "";
@@ -1145,6 +1193,24 @@ export const identityOidcAuthServiceFactory = ({
const deletedOidcAuth = await identityOidcAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.OIDC_AUTH }, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.OIDC_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return { ...deletedOidcAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };
});
diff --git a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-service.ts b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-service.ts
index 04f37f65a1..d8a1aa0dfc 100644
--- a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-service.ts
+++ b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-service.ts
@@ -39,6 +39,13 @@ import {
recordAuthAttemptMetric
} from "@app/lib/telemetry/metrics";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
+import {
+ IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ IdentityAuthMethodChange,
+ TIdentityAuthMethodChangeEventPayload
+} from "@app/services/alert/providers/identity-credential-alert-provider";
+import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -83,6 +90,7 @@ type TIdentitySpiffeAuthServiceFactoryDep = {
TIdentityAccessTokenServiceFactory,
"issueIdentityAccessToken" | "revokeTokensForIdentityAuthMethod" | "invalidateTrustedIpsCache"
>;
+ eventOutboxService: TEventOutboxEmitter;
};
export type TIdentitySpiffeAuthServiceFactory = ReturnType<typeof identitySpiffeAuthServiceFactory>;
@@ -141,7 +149,8 @@ export const identitySpiffeAuthServiceFactory = ({
identityAccessTokenDAL,
kmsService,
orgDAL,
- identityAccessTokenService
+ identityAccessTokenService,
+ eventOutboxService
}: TIdentitySpiffeAuthServiceFactoryDep) => {
type TFlattenedTrustBundle = {
configurationType: string;
@@ -612,6 +621,24 @@ export const identitySpiffeAuthServiceFactory = ({
tx
);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.SPIFFE_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return doc;
});
@@ -757,7 +784,28 @@ export const identitySpiffeAuthServiceFactory = ({
: null;
}
- const updatedSpiffeAuth = await identitySpiffeAuthDAL.updateById(identitySpiffeAuth.id, updateQuery);
+ const updatedSpiffeAuth = await identitySpiffeAuthDAL.transaction(async (tx) => {
+ const doc = await identitySpiffeAuthDAL.updateById(identitySpiffeAuth.id, updateQuery, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.SPIFFE_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return doc;
+ });
const decryptedCaBundleJwks = updatedSpiffeAuth.encryptedCaBundleJwks
? orgDataKeyDecryptor({ cipherTextBlob: updatedSpiffeAuth.encryptedCaBundleJwks }).toString()
@@ -937,6 +985,24 @@ export const identitySpiffeAuthServiceFactory = ({
const deletedSpiffeAuth = await identitySpiffeAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.SPIFFE_AUTH }, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.SPIFFE_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return deletedSpiffeAuth?.[0];
});
diff --git a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts
index 5fa2b3e06e..1703c5d79a 100644
--- a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts
+++ b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts
@@ -32,6 +32,13 @@ import {
authAttemptCounter,
recordAuthAttemptMetric
} from "@app/lib/telemetry/metrics";
+import {
+ IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ IdentityAuthMethodChange,
+ TIdentityAuthMethodChangeEventPayload
+} from "@app/services/alert/providers/identity-credential-alert-provider";
+import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -185,6 +192,7 @@ type TIdentityTlsCertAuthServiceFactoryDep = {
TIdentityAccessTokenServiceFactory,
"issueIdentityAccessToken" | "revokeTokensForIdentityAuthMethod" | "invalidateTrustedIpsCache"
>;
+ eventOutboxService: TEventOutboxEmitter;
};
export const identityTlsCertAuthServiceFactory = ({
@@ -197,7 +205,8 @@ export const identityTlsCertAuthServiceFactory = ({
permissionService,
kmsService,
orgDAL,
- identityAccessTokenService
+ identityAccessTokenService,
+ eventOutboxService
}: TIdentityTlsCertAuthServiceFactoryDep): TIdentityTlsCertAuthServiceFactory => {
const login: TIdentityTlsCertAuthServiceFactory["login"] = async ({
identityId,
@@ -583,6 +592,24 @@ export const identityTlsCertAuthServiceFactory = ({
},
tx
);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.TLS_CERT_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.TLS_CERT_AUTH);
@@ -693,19 +720,44 @@ export const identityTlsCertAuthServiceFactory = ({
validateCaCertificateUsable(caCertificate);
}
- const updatedTlsCertAuth = await identityTlsCertAuthDAL.updateById(identityTlsCertAuth.id, {
- allowedCommonNames,
- allowedSubjectAltNames: serializeAllowedSubjectAltNames(allowedSubjectAltNames),
- encryptedCaCertificate: caCertificate
- ? encryptor({ plainText: Buffer.from(caCertificate) }).cipherTextBlob
- : undefined,
- verifyClientCertificateChain: verifyClientCertificateChainOpt,
- accessTokenMaxTTL,
- accessTokenTTL,
- accessTokenNumUsesLimit,
- accessTokenTrustedIps: reformattedAccessTokenTrustedIps
- ? JSON.stringify(reformattedAccessTokenTrustedIps)
- : undefined
+ const updatedTlsCertAuth = await identityTlsCertAuthDAL.transaction(async (tx) => {
+ const doc = await identityTlsCertAuthDAL.updateById(
+ identityTlsCertAuth.id,
+ {
+ allowedCommonNames,
+ allowedSubjectAltNames: serializeAllowedSubjectAltNames(allowedSubjectAltNames),
+ encryptedCaCertificate: caCertificate
+ ? encryptor({ plainText: Buffer.from(caCertificate) }).cipherTextBlob
+ : undefined,
+ verifyClientCertificateChain: verifyClientCertificateChainOpt,
+ accessTokenMaxTTL,
+ accessTokenTTL,
+ accessTokenNumUsesLimit,
+ accessTokenTrustedIps: reformattedAccessTokenTrustedIps
+ ? JSON.stringify(reformattedAccessTokenTrustedIps)
+ : undefined
+ },
+ tx
+ );
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.TLS_CERT_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.TLS_CERT_AUTH);
@@ -863,6 +915,24 @@ export const identityTlsCertAuthServiceFactory = ({
const deletedTlsCertAuth = await identityTlsCertAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.TLS_CERT_AUTH }, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.TLS_CERT_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return { ...deletedTlsCertAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };
});
diff --git a/backend/src/services/identity-token-auth/identity-token-auth-service.ts b/backend/src/services/identity-token-auth/identity-token-auth-service.ts
index dec4dcb2b5..c1a0ecfa0e 100644
--- a/backend/src/services/identity-token-auth/identity-token-auth-service.ts
+++ b/backend/src/services/identity-token-auth/identity-token-auth-service.ts
@@ -26,6 +26,13 @@ import {
import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
+import {
+ IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ IdentityAuthMethodChange,
+ TIdentityAuthMethodChangeEventPayload
+} from "@app/services/alert/providers/identity-credential-alert-provider";
+import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";
@@ -69,6 +76,7 @@ type TIdentityTokenAuthServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;
+ eventOutboxService: TEventOutboxEmitter;
};
export type TIdentityTokenAuthServiceFactory = ReturnType<typeof identityTokenAuthServiceFactory>;
@@ -81,7 +89,8 @@ export const identityTokenAuthServiceFactory = ({
identityAccessTokenService,
permissionService,
licenseService,
- orgDAL
+ orgDAL,
+ eventOutboxService
}: TIdentityTokenAuthServiceFactoryDep) => {
const attachTokenAuth = async ({
identityId,
@@ -177,6 +186,24 @@ export const identityTokenAuthServiceFactory = ({
},
tx
);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.TOKEN_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.TOKEN_AUTH);
@@ -272,13 +299,38 @@ export const identityTokenAuthServiceFactory = ({
return extractIPDetails(accessTokenTrustedIp.ipAddress);
});
- const updatedTokenAuth = await identityTokenAuthDAL.updateById(identityTokenAuth.id, {
- accessTokenMaxTTL,
- accessTokenTTL,
- accessTokenNumUsesLimit,
- accessTokenTrustedIps: reformattedAccessTokenTrustedIps
- ? JSON.stringify(reformattedAccessTokenTrustedIps)
- : undefined
+ const updatedTokenAuth = await identityTokenAuthDAL.transaction(async (tx) => {
+ const doc = await identityTokenAuthDAL.updateById(
+ identityTokenAuth.id,
+ {
+ accessTokenMaxTTL,
+ accessTokenTTL,
+ accessTokenNumUsesLimit,
+ accessTokenTrustedIps: reformattedAccessTokenTrustedIps
+ ? JSON.stringify(reformattedAccessTokenTrustedIps)
+ : undefined
+ },
+ tx
+ );
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.TOKEN_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.TOKEN_AUTH);
@@ -425,11 +477,26 @@ export const identityTokenAuthServiceFactory = ({
const revokedIdentityTokenAuth = await identityTokenAuthDAL.transaction(async (tx) => {
const deletedTokenAuth = await identityTokenAuthDAL.delete({ identityId }, tx);
- await identityAccessTokenDAL.delete({
- identityId,
- authMethod: IdentityAuthMethod.TOKEN_AUTH
- });
+ await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.TOKEN_AUTH }, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.TOKEN_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return { ...deletedTokenAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };
});
@@ -587,7 +654,7 @@ export const identityTokenAuthServiceFactory = ({
await recordIdentityLastLogin(membershipIdentityDAL, identity, IdentityAuthMethod.TOKEN_AUTH, tx);
}
- return identityAccessTokenService.issueIdentityAccessToken({
+ const issued = await identityAccessTokenService.issueIdentityAccessToken({
identityId: identity.id,
identityName: identity.name,
authMethod: IdentityAuthMethod.TOKEN_AUTH,
@@ -603,6 +670,27 @@ export const identityTokenAuthServiceFactory = ({
accessTokenTrustedIps: identityTokenAuth.accessTokenTrustedIps as TIp[],
persistToPg: { tx, name }
});
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.TOKEN_AUTH,
+ change: IdentityAuthMethodChange.CredentialAdded,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString(),
+ credentialId: issued.identityAccessToken.id,
+ credentialName: name
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return issued;
});
return { accessToken, identityTokenAuth, identityAccessToken, identity };
@@ -833,16 +921,34 @@ export const identityTokenAuthServiceFactory = ({
await validateIdentityUpdateForSuperAdminPrivileges(foundToken.identityId, isActorSuperAdmin);
- const [token] = await identityAccessTokenDAL.update(
- {
- authMethod: IdentityAuthMethod.TOKEN_AUTH,
- identityId: foundToken.identityId,
- id: tokenId
- },
- {
- name
- }
- );
+ const token = await identityTokenAuthDAL.transaction(async (tx) => {
+ const [doc] = await identityAccessTokenDAL.update(
+ { authMethod: IdentityAuthMethod.TOKEN_AUTH, identityId: foundToken.identityId, id: tokenId },
+ { name },
+ tx
+ );
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.TOKEN_AUTH,
+ change: IdentityAuthMethodChange.CredentialUpdated,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString(),
+ credentialId: doc.id,
+ credentialName: doc.name ?? undefined
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return doc;
+ });
return { token, identityMembershipOrg };
};
@@ -910,15 +1016,34 @@ export const identityTokenAuthServiceFactory = ({
await validateIdentityUpdateForSuperAdminPrivileges(identityAccessToken.identityId, isActorSuperAdmin);
- const [revokedToken] = await identityAccessTokenDAL.update(
- {
- id: identityAccessToken.id,
- authMethod: IdentityAuthMethod.TOKEN_AUTH
- },
- {
- isAccessTokenRevoked: true
- }
- );
+ const revokedToken = await identityTokenAuthDAL.transaction(async (tx) => {
+ const [doc] = await identityAccessTokenDAL.update(
+ { id: identityAccessToken.id, authMethod: IdentityAuthMethod.TOKEN_AUTH },
+ { isAccessTokenRevoked: true },
+ tx
+ );
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityOrgMembership.identity.id,
+ orgId: identityOrgMembership.scopeOrgId,
+ projectId: identityOrgMembership.identity.projectId,
+ payload: {
+ targetIds: [identityOrgMembership.identity.id],
+ authMethod: IdentityAuthMethod.TOKEN_AUTH,
+ change: IdentityAuthMethodChange.CredentialRevoked,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString(),
+ credentialId: doc.id,
+ credentialName: doc.name ?? undefined
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return doc;
+ });
// No JWT here, so the helper anchors on now plus the row's issuance cap.
const expiresAt = computeTokenAuthRevokeMarkerExpiry({
diff --git a/backend/src/services/identity-ua/identity-ua-service.ts b/backend/src/services/identity-ua/identity-ua-service.ts
index 3eda256ce9..89426bf195 100644
--- a/backend/src/services/identity-ua/identity-ua-service.ts
+++ b/backend/src/services/identity-ua/identity-ua-service.ts
@@ -32,6 +32,13 @@ import {
authAttemptCounter,
recordAuthAttemptMetric
} from "@app/lib/telemetry/metrics";
+import {
+ IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ IdentityAuthMethodChange,
+ TIdentityAuthMethodChangeEventPayload
+} from "@app/services/alert/providers/identity-credential-alert-provider";
+import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -86,6 +93,7 @@ type TIdentityUaServiceFactoryDep = {
| "sortedSetMembersPrimary"
| "acquireLock"
>;
+ eventOutboxService: TEventOutboxEmitter;
};
export type TIdentityUaServiceFactory = ReturnType<typeof identityUaServiceFactory>;
@@ -102,7 +110,8 @@ export const identityUaServiceFactory = ({
orgDAL,
keyStore,
identityDAL,
- identityAccessTokenService
+ identityAccessTokenService,
+ eventOutboxService
}: TIdentityUaServiceFactoryDep) => {
const login = async ({ clientId, clientSecret, ip, organizationSlug }: TLoginUaDTO) => {
const authMetricStartTime = performance.now();
@@ -545,6 +554,24 @@ export const identityUaServiceFactory = ({
},
tx
);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(
@@ -668,21 +695,46 @@ export const identityUaServiceFactory = ({
return extractIPDetails(accessTokenTrustedIp.ipAddress);
});
- const updatedUaAuth = await identityUaDAL.updateById(uaIdentityAuth.id, {
- clientSecretTrustedIps: reformattedClientSecretTrustedIps
- ? JSON.stringify(reformattedClientSecretTrustedIps)
- : undefined,
- accessTokenMaxTTL,
- accessTokenTTL,
- accessTokenNumUsesLimit,
- accessTokenPeriod,
- accessTokenTrustedIps: reformattedAccessTokenTrustedIps
- ? JSON.stringify(reformattedAccessTokenTrustedIps)
- : undefined,
- lockoutEnabled,
- lockoutThreshold,
- lockoutDurationSeconds,
- lockoutCounterResetSeconds
+ const updatedUaAuth = await identityUaDAL.transaction(async (tx) => {
+ const doc = await identityUaDAL.updateById(
+ uaIdentityAuth.id,
+ {
+ clientSecretTrustedIps: reformattedClientSecretTrustedIps
+ ? JSON.stringify(reformattedClientSecretTrustedIps)
+ : undefined,
+ accessTokenMaxTTL,
+ accessTokenTTL,
+ accessTokenNumUsesLimit,
+ accessTokenPeriod,
+ accessTokenTrustedIps: reformattedAccessTokenTrustedIps
+ ? JSON.stringify(reformattedAccessTokenTrustedIps)
+ : undefined,
+ lockoutEnabled,
+ lockoutThreshold,
+ lockoutDurationSeconds,
+ lockoutCounterResetSeconds
+ },
+ tx
+ );
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.UNIVERSAL_AUTH);
return { ...updatedUaAuth, orgId: identityMembershipOrg.scopeOrgId };
@@ -825,6 +877,24 @@ export const identityUaServiceFactory = ({
await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);
const revokedIdentityUniversalAuth = await identityUaDAL.transaction(async (tx) => {
const deletedUniversalAuth = await identityUaDAL.delete({ identityId }, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString()
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
return { ...deletedUniversalAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };
});
@@ -937,15 +1007,41 @@ export const identityUaServiceFactory = ({
const identityUaAuth = await identityUaDAL.findOne({ identityId: identityMembershipOrg.identity.id });
if (!identityUaAuth) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
- const identityUaClientSecret = await identityUaClientSecretDAL.create({
- identityUAId: identityUaAuth.id,
- description,
- clientSecretPrefix: clientSecret.slice(0, 4),
- clientSecretHash,
- clientSecretNumUses: 0,
- clientSecretNumUsesLimit: numUsesLimit,
- clientSecretTTL: ttl,
- isClientSecretRevoked: false
+ const identityUaClientSecret = await identityUaDAL.transaction(async (tx) => {
+ const doc = await identityUaClientSecretDAL.create(
+ {
+ identityUAId: identityUaAuth.id,
+ description,
+ clientSecretPrefix: clientSecret.slice(0, 4),
+ clientSecretHash,
+ clientSecretNumUses: 0,
+ clientSecretNumUsesLimit: numUsesLimit,
+ clientSecretTTL: ttl,
+ isClientSecretRevoked: false
+ },
+ tx
+ );
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
+ change: IdentityAuthMethodChange.CredentialAdded,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString(),
+ credentialId: doc.id,
+ credentialName: doc.description || doc.clientSecretPrefix
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return doc;
});
return {
clientSecret,
@@ -1239,8 +1335,29 @@ export const identityUaServiceFactory = ({
clientSecretId
});
- const updatedClientSecret = await identityUaClientSecretDAL.updateById(clientSecretId, {
- isClientSecretRevoked: true
+ const updatedClientSecret = await identityUaDAL.transaction(async (tx) => {
+ const doc = await identityUaClientSecretDAL.updateById(clientSecretId, { isClientSecretRevoked: true }, tx);
+ await eventOutboxService.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: identityMembershipOrg.identity.id,
+ orgId: identityMembershipOrg.scopeOrgId,
+ projectId: identityMembershipOrg.identity.projectId,
+ payload: {
+ targetIds: [identityMembershipOrg.identity.id],
+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
+ change: IdentityAuthMethodChange.CredentialRevoked,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString(),
+ credentialId: doc.id,
+ credentialName: doc.description || doc.clientSecretPrefix
+ } satisfies TIdentityAuthMethodChangeEventPayload
+ },
+ tx
+ );
+ return doc;
});
return { ...updatedClientSecret, identityId, orgId: identityMembershipOrg.scopeOrgId };
diff --git a/docs/documentation/platform/identities/machine-identities.mdx b/docs/documentation/platform/identities/machine-identities.mdx
index 6ecb50f245..7298142879 100644
--- a/docs/documentation/platform/identities/machine-identities.mdx
+++ b/docs/documentation/platform/identities/machine-identities.mdx
@@ -16,7 +16,7 @@ Key Features:
- Role Assignment: Identities must be assigned [roles](/documentation/platform/access-controls/role-based-access-controls). These roles determine the scope of access to resources, either at the organization level or project level.
- Auth/Token Configuration: Identities must be configured with corresponding authentication methods and access token properties to securely interact with the Infisical API.
-- Expiry Alerting: Identities with expiring credentials can notify your team ahead of time via [Credential Expiry Alerts](#credential-expiry-alerts).
+- Alerting: An identity can notify your team before a credential expires or whenever one of its auth methods changes via [Alerts](#alerts).
## Scopes
@@ -87,11 +87,20 @@ Once revoked, the token is rejected on subsequent authenticated requests and can
If you need a revocation to take effect with no propagation delay even under those conditions, rotate the underlying credential (delete the Universal Auth client secret) or delete the identity, both of which invalidate the affected tokens regardless of cache state.
</Note>
-## Credential expiry alerts
+## Alerts
-A machine identity whose credential expires unnoticed takes your workload down with it. Expiry alerts watch the credentials attached to an identity and notify your team a configurable number of days before they expire, so the credential gets rotated before anything breaks.
+An alert on a machine identity notifies your team through the channels you pick. Each alert watches one event, chosen when you create it:
-Alerts currently cover **Universal Auth client secrets that have a TTL**. A client secret is only monitored when its TTL is greater than `0`, since one created with the default TTL of `0` never expires and has nothing to alert on. Revoked client secrets are skipped.
+| Event | When it fires |
+|-------|---------------|
+| **Client Secret Expiration** | A set number of days before a Universal Auth client secret expires, checked once a day |
+| **Auth Method or Credential Change** | Right after an auth method is added, updated, or removed, or a Universal Auth client secret or Token Auth token is created, updated, or revoked |
+
+### Client secret expiration
+
+A machine identity whose credential expires unnoticed takes your workload down with it. This alert watches the Universal Auth client secrets attached to the identity and notifies your team a configurable number of days before they expire, so the credential gets rotated before anything breaks.
+
+A client secret is only monitored when its TTL is greater than `0`, since one created with the default TTL of `0` never expires and has nothing to alert on. Revoked client secrets are skipped.
<Note>
The alert watches the **client secret**, not the access tokens minted from it. Access tokens are
@@ -100,9 +109,17 @@ Alerts currently cover **Universal Auth client secrets that have a TTL**. A clie
Client Secret TTL, Access Token TTL, and Access Token Max TTL.
</Note>
+### Auth method or credential change
+
+Changing how a machine identity authenticates changes who can act as it. This alert fires every time any of the identity's auth methods is added, updated, or removed, whether through the dashboard, the API, or Terraform. It covers all auth methods, from Universal Auth and Token Auth to the cloud, Kubernetes, OIDC, JWT, LDAP, SPIFFE, and TLS certificate methods.
+
+It also fires when a credential inside a method changes: a Universal Auth client secret is created or revoked, or a Token Auth token is created, renamed, or revoked. Access tokens minted by logging in with a credential aren't credentials themselves and don't fire it.
+
+Each notification names the auth method, the kind of change, the credential where one is involved, who made the change (a user's email or a machine identity's name), and when. It takes no condition and has no daily run: the notification is sent as soon as the change is saved.
+
### Create an alert
-Open the machine identity you want to monitor and select **Alert** in the top-right of the page to create one.
+Open the machine identity you want to monitor and select **Alert** in the top-right of the page to create one. An identity holds one alert, so pick the event you care about most.
![Create Machine Identity Alert](/images/platform/organization/mi-create-alert.png)
@@ -110,11 +127,12 @@ Open the machine identity you want to monitor and select **Alert** in the top-ri
|-------|-------------|
| **Name** | A name for the alert, e.g. `ua-secret-expiry` |
| **Description** | Optional context about this alert |
-| **Condition** | How many days before expiration to notify, as a whole number from `1` to `90` |
-| **Daily Reminder** | If enabled, repeats the alert every day from the threshold until the credential expires |
+| **Event** | **Client Secret Expiration** or **Auth Method or Credential Change**. The event can't be changed after the alert is created; remove the alert and create a new one instead. |
+| **Condition** | For **Client Secret Expiration** only: how many days before expiration to notify, as a whole number from `1` to `90` |
+| **Daily Reminder** | For **Client Secret Expiration** only: if enabled, repeats the alert every day from the threshold until the credential expires |
| **Enabled** | Turn the alert off without deleting it |
-With **Daily Reminder** off, each credential triggers the alert once. Turn it on for credentials you can't afford to miss, and you'll get one notification per day until the credential expires or is rotated.
+With **Daily Reminder** off, each credential triggers the expiration alert once. Turn it on for credentials you can't afford to miss, and you'll get one notification per day until the credential expires or is rotated.
### Notification channels
@@ -124,12 +142,12 @@ An alert delivers through one or more channels, up to 10 per alert. Add at least
|---------|---------------|
| **Email** | Pick recipients from the organization's users and groups, up to 20 per channel. Group membership is expanded at send time. |
| **Slack** | An [Incoming Webhook](https://api.slack.com/messaging/webhooks) URL. Must be an HTTPS `hooks.slack.com` URL. |
-| **PagerDuty** | An [Events API v2](https://developer.pagerduty.com/docs/events-api-v2-overview) integration key (32-character hex string). Triggers one incident per expiring credential, deduplicated by credential. |
+| **PagerDuty** | An [Events API v2](https://developer.pagerduty.com/docs/events-api-v2-overview) integration key (32-character hex string). Triggers one incident per expiring credential, deduplicated by credential. For auth method changes, repeated changes of the same kind to the same method land on one open incident. |
| **Webhook** | Any HTTPS endpoint, with an optional signing secret for verification. |
### Webhook payload
-Webhook deliveries are [CloudEvents](https://cloudevents.io/) 1.0 JSON documents with the type `com.infisical.identity.authentication.expiration`. Every credential due for this run is listed in `data.items`:
+Webhook deliveries are [CloudEvents](https://cloudevents.io/) 1.0 JSON documents. The `type` names the event: `com.infisical.identity.authentication.expiration` for a client secret expiration and `com.infisical.identity.authentication.auth-method-changed` for an auth method change. Every credential due for this run, or the change that fired, is listed in `data.items`:
```json
{
@@ -166,6 +184,43 @@ Webhook deliveries are [CloudEvents](https://cloudevents.io/) 1.0 JSON documents
}
```
+An auth method or credential change carries one item whose fields name the method, the change, the credential when one is involved, who made the change, and when. The `Change` field is one of `Added`, `Updated`, `Removed`, `Credential Added`, `Credential Updated`, or `Credential Revoked`:
+
+```json
+{
+ "specversion": "1.0",
+ "type": "com.infisical.identity.authentication.auth-method-changed",
+ "source": "/alerts/6c1e5a9b-2f4d-4b7e-8a3c-1d9e0f2b5c7a",
+ "id": "a7d3e1f9-4b2c-4e8d-9f01-3c5b7a9d2e4f",
+ "time": "2026-09-10T10:00:01.204Z",
+ "datacontenttype": "application/json",
+ "subject": "identity.authentication.auth-method-changed",
+ "data": {
+ "alert": {
+ "id": "6c1e5a9b-2f4d-4b7e-8a3c-1d9e0f2b5c7a",
+ "name": "auth-method-change",
+ "resourceType": "identity.authentication"
+ },
+ "items": [
+ {
+ "id": "auth-method-change:c6002a8c-4571-4660-b169-f891f4734851:universal-auth:added",
+ "title": "ci-deploy-bot",
+ "fields": [
+ { "label": "Auth Method", "value": "Universal Auth" },
+ { "label": "Change", "value": "Added" },
+ { "label": "Changed By", "value": "[email protected] (user)" },
+ { "label": "Changed At", "value": "September 10, 2026 at 10:00 AM UTC" }
+ ]
+ }
+ ],
+ "metadata": {
+ "totalItems": 1,
+ "viewUrl": "https://app.infisical.com/organizations/18b65352-ad1e-43d5-830f-65c72245c3a3/identities/c6002a8c-4571-4660-b169-f891f4734851"
+ }
+ }
+}
+```
+
When a signing secret is set, Infisical signs the request and sends it in the `x-infisical-signature` header:
```
@@ -206,4 +261,7 @@ You can learn more about how to do this in the CLI quickstart [here](/cli/usage)
<Accordion title="What happens to an alert after I rotate the credential?">
The new client secret is evaluated on its own TTL, and the old one drops out of the alert once it's revoked or expires. No change to the alert is needed.
</Accordion>
+<Accordion title="Does the auth method or credential change alert fire when I rotate a client secret?">
+ Yes. Creating the new client secret sends one notification and revoking the old one sends another, each naming the secret by its description or prefix. Logging in with a client secret to mint an access token doesn't fire it.
+</Accordion>
</AccordionGroup>
diff --git a/docs/documentation/platform/identities/universal-auth.mdx b/docs/documentation/platform/identities/universal-auth.mdx
index 2f50af2396..3aae88ce3c 100644
--- a/docs/documentation/platform/identities/universal-auth.mdx
+++ b/docs/documentation/platform/identities/universal-auth.mdx
@@ -112,7 +112,7 @@ using the Universal Auth authentication method.
Feel free to input any (optional) details for the **Client Secret** configuration:
- Description: A description for the **Client Secret**.
- - TTL (default is `0`): The time-to-live for the **Client Secret**. By default, the TTL will be set to 0 which implies that the **Client Secret** will never expire; a value of `0` implies an infinite lifetime. When you set a TTL, configure a [credential expiry alert](/documentation/platform/identities/machine-identities#credential-expiry-alerts) so your team is notified before the **Client Secret** expires.
+ - TTL (default is `0`): The time-to-live for the **Client Secret**. By default, the TTL will be set to 0 which implies that the **Client Secret** will never expire; a value of `0` implies an infinite lifetime. When you set a TTL, configure a [credential expiry alert](/documentation/platform/identities/machine-identities#client-secret-expiration) so your team is notified before the **Client Secret** expires.
- Max Number of Uses (default is `0`): The maximum number of times that the **Client Secret** can be used together with the **Client ID** to get back an access token; a value of `0` implies infinite number of uses.
<Info>
diff --git a/frontend/src/hooks/api/alerts/types.ts b/frontend/src/hooks/api/alerts/types.ts
index 74b50ecbbf..e2dd944e13 100644
--- a/frontend/src/hooks/api/alerts/types.ts
+++ b/frontend/src/hooks/api/alerts/types.ts
@@ -5,7 +5,8 @@ export enum AlertResourceType {
}
export enum AlertEventType {
- IdentityAuthenticationExpiry = "identity.authentication.expiry"
+ IdentityAuthenticationExpiry = "identity.authentication.expiry",
+ IdentityAuthMethodChanged = "identity.authentication.auth-method-changed"
}
export enum AlertChannelType {
@@ -28,7 +29,15 @@ export const ALERT_RESOURCE_TYPE_LABELS: Record<AlertResourceType, string> = {
};
export const ALERT_EVENT_TYPE_LABELS: Record<AlertEventType, string> = {
- [AlertEventType.IdentityAuthenticationExpiry]: "Expiration"
+ [AlertEventType.IdentityAuthenticationExpiry]: "Client Secret Expiration",
+ [AlertEventType.IdentityAuthMethodChanged]: "Auth Method Change"
+};
+
+export const ALERT_EVENT_TYPE_DESCRIPTIONS: Record<AlertEventType, string> = {
+ [AlertEventType.IdentityAuthenticationExpiry]:
+ "Notify a set number of days before a Universal Auth client secret expires.",
+ [AlertEventType.IdentityAuthMethodChanged]:
+ "Notify whenever an auth method is added, updated, or removed."
};
export const ALERT_CHANNEL_TYPE_LABELS: Record<AlertChannelType, string> = {
@@ -184,19 +193,32 @@ export const channelFormSchema = z
export type TChannelForm = z.infer<typeof channelFormSchema>;
-export const alertFormSchema = z.object({
+const alertFormBaseSchema = z.object({
name: z.string().min(1, "Name is required").max(255),
description: z.string().max(1000).optional(),
resourceType: z.nativeEnum(AlertResourceType),
eventType: z.nativeEnum(AlertEventType),
- alertBeforeDays: z
- .number({ invalid_type_error: "Enter a number" })
- .int("Must be a whole number")
- .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`),
+ // Only the expiry event reads these; validated in superRefine so a hidden field can't block submit.
+ alertBeforeDays: z.number().or(z.nan()),
dailyReminder: z.boolean().default(false),
enabled: z.boolean().default(true),
channels: z.array(channelFormSchema).min(1, "At least one channel is required")
});
+const alertBeforeDaysIssue = (days: number): string | null => {
+ if (Number.isNaN(days)) return "Enter a number";
+ if (!Number.isInteger(days)) return "Must be a whole number";
+ if (days < MIN_ALERT_BEFORE_DAYS) return `Must be at least ${MIN_ALERT_BEFORE_DAYS} day`;
+ if (days > MAX_ALERT_BEFORE_DAYS) return `Must be at most ${MAX_ALERT_BEFORE_DAYS} days`;
+ return null;
+};
+
+export const alertFormSchema = alertFormBaseSchema.superRefine((form, ctx) => {
+ if (form.eventType !== AlertEventType.IdentityAuthenticationExpiry) return;
+ const message = alertBeforeDaysIssue(form.alertBeforeDays);
+ if (message) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["alertBeforeDays"], message });
+ }
+});
+
export type TAlertForm = z.infer<typeof alertFormSchema>;
diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx
index 6383da70fc..a06c8bb9e5 100644
--- a/frontend/src/pages/organization/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx
+++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx
@@ -112,7 +112,7 @@ const Page = () => {
title={data.identity.name}
>
{isScopeIdentity && !data.identity.projectId && (
- <IdentityAlertAction identityId={identityId} identityName={data.identity.name} />
+ <IdentityAlertAction identityId={identityId} />
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityAlertAction.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityAlertAction.tsx
index 9278ecb076..660cffc634 100644
--- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityAlertAction.tsx
+++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityAlertAction.tsx
@@ -4,13 +4,11 @@ import { AlertAction } from "@app/views/Alerts";
type Props = {
identityId: string;
- identityName: string;
};
-export const IdentityAlertAction = ({ identityId, identityName }: Props) => (
+export const IdentityAlertAction = ({ identityId }: Props) => (
<AlertAction
identityId={identityId}
- identityName={identityName}
renderPermissionGate={(render) => (
<OrgPermissionCan I={OrgPermissionIdentityActions.Edit} a={OrgPermissionSubjects.Identity}>
{render}
diff --git a/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx
index ea1fec7cfe..f943afe7d0 100644
--- a/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx
+++ b/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx
@@ -217,14 +217,11 @@ const Page = () => {
{isProjectIdentity ? (
<ProjectIdentityAlertAction
identityId={identityMembershipDetails.identity.id}
- identityName={identityMembershipDetails.identity.name}
projectId={currentProject.id}
- projectName={currentProject.name}
/>
) : (
<ProjectIdentityAlertAction
identityId={identityMembershipDetails.identity.id}
- identityName={identityMembershipDetails.identity.name}
readOnly
/>
)}
diff --git a/frontend/src/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityAlertAction.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityAlertAction.tsx
index 3db8cb0163..99414e8de7 100644
--- a/frontend/src/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityAlertAction.tsx
+++ b/frontend/src/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityAlertAction.tsx
@@ -6,24 +6,14 @@ import { AlertAction } from "@app/views/Alerts";
type Props = {
identityId: string;
- identityName: string;
projectId?: string;
- projectName?: string;
readOnly?: boolean;
};
-export const ProjectIdentityAlertAction = ({
- identityId,
- identityName,
- projectId,
- projectName,
- readOnly = false
-}: Props) => (
+export const ProjectIdentityAlertAction = ({ identityId, projectId, readOnly = false }: Props) => (
<AlertAction
identityId={identityId}
- identityName={identityName}
projectId={projectId}
- scopeName={projectName}
readOnly={readOnly}
renderPermissionGate={(render) => (
<ProjectPermissionCan
diff --git a/frontend/src/views/Alerts/AddAlertModal.tsx b/frontend/src/views/Alerts/AddAlertModal.tsx
index 611bda9fa9..6645174196 100644
--- a/frontend/src/views/Alerts/AddAlertModal.tsx
+++ b/frontend/src/views/Alerts/AddAlertModal.tsx
@@ -7,21 +7,11 @@ type Props = {
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
projectId?: string;
- scopeName?: string;
resourceId?: string;
- resourceName?: string;
alert?: TAlert;
};
-export const AddAlertModal = ({
- isOpen,
- onOpenChange,
- projectId,
- scopeName,
- resourceId,
- resourceName,
- alert
-}: Props) => {
+export const AddAlertModal = ({ isOpen, onOpenChange, projectId, resourceId, alert }: Props) => {
const isEditing = Boolean(alert);
return (
@@ -37,9 +27,7 @@ export const AddAlertModal = ({
<AlertForm
key={alert?.id ?? "new"}
projectId={projectId}
- scopeName={scopeName}
resourceId={resourceId}
- resourceName={resourceName}
alert={alert}
onComplete={() => onOpenChange(false)}
onCancel={() => onOpenChange(false)}
diff --git a/frontend/src/views/Alerts/AlertAction.tsx b/frontend/src/views/Alerts/AlertAction.tsx
index 53a456c117..1f43dd8865 100644
--- a/frontend/src/views/Alerts/AlertAction.tsx
+++ b/frontend/src/views/Alerts/AlertAction.tsx
@@ -40,10 +40,8 @@ import { AddAlertModal } from "./AddAlertModal";
type Props = {
identityId: string;
- identityName: string;
// Org-scoped when omitted.
projectId?: string;
- scopeName?: string;
// Renders the alert without any way to create, edit or remove it.
readOnly?: boolean;
// Wraps the mutating actions in the caller's permission gate (org- or project-scoped), which is the
@@ -54,6 +52,9 @@ type Props = {
// "7 days before client secret expiry"; falls back to the event label when the
// stored condition is missing or malformed.
const formatConditionSummary = (alert: TAlert): string => {
+ if (alert.eventType === AlertEventType.IdentityAuthMethodChanged) {
+ return "When an auth method or one of its credentials changes";
+ }
const days = parseAlertBeforeDays(alert.condition?.alertBefore);
if (days === null) {
return ALERT_EVENT_TYPE_LABELS[alert.eventType as AlertEventType] ?? alert.eventType;
@@ -71,9 +72,7 @@ const formatChannelSummary = (alert: TAlert): string =>
export const AlertAction = ({
identityId,
- identityName,
projectId,
- scopeName,
readOnly = false,
renderPermissionGate
}: Props) => {
@@ -134,9 +133,7 @@ export const AlertAction = ({
isOpen={popUp.alert.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("alert", isOpen)}
projectId={projectId}
- scopeName={scopeName}
resourceId={identityId}
- resourceName={identityName}
/>
</>
);
@@ -222,9 +219,7 @@ export const AlertAction = ({
isOpen={popUp.alert.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("alert", isOpen)}
projectId={projectId}
- scopeName={scopeName}
resourceId={identityId}
- resourceName={identityName}
alert={existingAlert}
/>
<AlertDialog
diff --git a/frontend/src/views/Alerts/AlertForm.tsx b/frontend/src/views/Alerts/AlertForm.tsx
index 16ba4da595..d4aab5892f 100644
--- a/frontend/src/views/Alerts/AlertForm.tsx
+++ b/frontend/src/views/Alerts/AlertForm.tsx
@@ -1,15 +1,14 @@
import { Controller, FormProvider, useForm, useWatch } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
-import { ClockAlertIcon, KeyRoundIcon } from "lucide-react";
+import { KeyRoundIcon } from "lucide-react";
import { createNotification } from "@app/components/notifications";
import {
- Alert,
- AlertDescription,
Button,
Checkbox,
Field,
FieldContent,
+ FieldDescription,
FieldError,
FieldLabel,
Input,
@@ -25,6 +24,8 @@ import {
} from "@app/components/v3";
import { useScopeVariant } from "@app/hooks";
import {
+ ALERT_EVENT_TYPE_DESCRIPTIONS,
+ ALERT_EVENT_TYPE_LABELS,
ALERT_RESOURCE_TYPE_LABELS,
AlertEventType,
alertFormSchema,
@@ -45,16 +46,18 @@ import { ChannelsField } from "./ChannelsField";
type Props = {
projectId?: string;
- scopeName?: string;
resourceId?: string;
- resourceName?: string;
alert?: TAlert;
onComplete: () => void;
onCancel: () => void;
};
const DEFAULT_ALERT_BEFORE_DAYS = 7;
-const DEFAULT_ALERT_NAME = "Secret expiration alert";
+const DEFAULT_ALERT_NAMES: Record<AlertEventType, string> = {
+ [AlertEventType.IdentityAuthenticationExpiry]: "Secret expiration alert",
+ [AlertEventType.IdentityAuthMethodChanged]: "Auth method change alert"
+};
+const DEFAULT_EVENT_TYPE = AlertEventType.IdentityAuthenticationExpiry;
const toChannelForm = (channel: TAlert["channels"][number]): TChannelForm => ({
id: channel.id,
@@ -74,10 +77,10 @@ const toChannelForm = (channel: TAlert["channels"][number]): TChannelForm => ({
const buildFormDefaults = (alert?: TAlert): TAlertForm => {
if (!alert) {
return {
- name: DEFAULT_ALERT_NAME,
+ name: DEFAULT_ALERT_NAMES[DEFAULT_EVENT_TYPE],
description: "",
resourceType: AlertResourceType.IdentityAuthentication,
- eventType: AlertEventType.IdentityAuthenticationExpiry,
+ eventType: DEFAULT_EVENT_TYPE,
alertBeforeDays: DEFAULT_ALERT_BEFORE_DAYS,
dailyReminder: false,
enabled: true,
@@ -90,7 +93,7 @@ const buildFormDefaults = (alert?: TAlert): TAlertForm => {
description: alert.description ?? "",
resourceType:
(alert.resourceType as AlertResourceType) ?? AlertResourceType.IdentityAuthentication,
- eventType: (alert.eventType as AlertEventType) ?? AlertEventType.IdentityAuthenticationExpiry,
+ eventType: (alert.eventType as AlertEventType) ?? DEFAULT_EVENT_TYPE,
alertBeforeDays:
parseAlertBeforeDays(alert.condition?.alertBefore) ?? DEFAULT_ALERT_BEFORE_DAYS,
dailyReminder: alert.condition?.dailyReminder ?? false,
@@ -99,15 +102,7 @@ const buildFormDefaults = (alert?: TAlert): TAlertForm => {
};
};
-export const AlertForm = ({
- projectId,
- scopeName,
- resourceId,
- resourceName,
- alert,
- onComplete,
- onCancel
-}: Props) => {
+export const AlertForm = ({ projectId, resourceId, alert, onComplete, onCancel }: Props) => {
const isEditing = Boolean(alert);
const scopeVariant = useScopeVariant();
const createAlert = useCreateAlert();
@@ -122,24 +117,27 @@ export const AlertForm = ({
control,
register,
handleSubmit,
+ getValues,
+ setValue,
formState: { errors, isSubmitting }
} = formMethods;
const resourceTypeValue = useWatch({ control, name: "resourceType" });
- const isProjectScope = Boolean(projectId);
+ const eventTypeValue = useWatch({ control, name: "eventType" });
+ const isExpiryEvent = eventTypeValue === AlertEventType.IdentityAuthenticationExpiry;
const isResourceScope = Boolean(resourceId ?? alert?.resourceId);
- // eslint-disable-next-line no-nested-ternary
- const watchTarget = isResourceScope
- ? (resourceName ?? "this machine identity")
- : isProjectScope
- ? `every machine identity in ${scopeName ?? "this project"}`
- : `every machine identity in this ${scopeVariant === "sub-org" ? "sub-organization" : "organization"}`;
+ const handleEventTypeChange = (previous: AlertEventType, next: AlertEventType) => {
+ setValue("eventType", next, { shouldDirty: true });
+ if (getValues("name") === DEFAULT_ALERT_NAMES[previous]) {
+ setValue("name", DEFAULT_ALERT_NAMES[next]);
+ }
+ };
const onSubmit = async (data: TAlertForm) => {
- const condition = {
- alertBefore: toAlertBefore(data.alertBeforeDays),
- dailyReminder: data.dailyReminder
- };
+ const condition =
+ data.eventType === AlertEventType.IdentityAuthenticationExpiry
+ ? { alertBefore: toAlertBefore(data.alertBeforeDays), dailyReminder: data.dailyReminder }
+ : null;
const channels = data.channels.map(toChannelInput);
try {
if (isEditing && alert) {
@@ -186,7 +184,9 @@ export const AlertForm = ({
<Input
id="alert-name"
autoFocus
- placeholder={DEFAULT_ALERT_NAME}
+ placeholder={
+ DEFAULT_ALERT_NAMES[eventTypeValue] ?? DEFAULT_ALERT_NAMES[DEFAULT_EVENT_TYPE]
+ }
isError={Boolean(errors.name)}
{...register("name")}
/>
@@ -210,15 +210,34 @@ export const AlertForm = ({
</FieldContent>
</Field>
- <Alert className="items-start [&>svg]:mt-0.5 [&>svg]:text-info">
- <ClockAlertIcon />
- <AlertDescription>
- <span>
- Watching <span className="font-medium text-foreground">{watchTarget}</span> ·
- Universal Auth client secret expiration
- </span>
- </AlertDescription>
- </Alert>
+ <Controller
+ control={control}
+ name="eventType"
+ render={({ field: { value } }) => (
+ <Field>
+ <FieldLabel>Event</FieldLabel>
+ <FieldContent>
+ <Select
+ value={value}
+ disabled={isEditing}
+ onValueChange={(next) => handleEventTypeChange(value, next as AlertEventType)}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {Object.values(AlertEventType).map((eventType) => (
+ <SelectItem key={eventType} value={eventType}>
+ {ALERT_EVENT_TYPE_LABELS[eventType]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldDescription>{ALERT_EVENT_TYPE_DESCRIPTIONS[value]}</FieldDescription>
+ </FieldContent>
+ </Field>
+ )}
+ />
<Controller
control={control}
@@ -271,38 +290,40 @@ export const AlertForm = ({
/>
)}
- <div className="mb-1 flex flex-col gap-1.5">
- <Label htmlFor="alert-alert-before">Condition</Label>
- <div className="mt-1 flex flex-wrap items-center gap-3 text-sm text-foreground">
- <span>Alert</span>
- <Input
- id="alert-alert-before"
- type="number"
- min={MIN_ALERT_BEFORE_DAYS}
- max={MAX_ALERT_BEFORE_DAYS}
- className="w-16 text-center"
- isError={Boolean(errors.alertBeforeDays)}
- {...register("alertBeforeDays", { valueAsNumber: true })}
+ {isExpiryEvent && (
+ <div className="mb-1 flex flex-col gap-1.5">
+ <Label htmlFor="alert-alert-before">Condition</Label>
+ <div className="mt-1 flex flex-wrap items-center gap-3 text-sm text-foreground">
+ <span>Alert</span>
+ <Input
+ id="alert-alert-before"
+ type="number"
+ min={MIN_ALERT_BEFORE_DAYS}
+ max={MAX_ALERT_BEFORE_DAYS}
+ className="w-16 text-center"
+ isError={Boolean(errors.alertBeforeDays)}
+ {...register("alertBeforeDays", { valueAsNumber: true })}
+ />
+ <span>days before a client secret expires</span>
+ </div>
+ <FieldError errors={[errors.alertBeforeDays]} />
+ <Controller
+ control={control}
+ name="dailyReminder"
+ render={({ field }) => (
+ <Label htmlFor="alert-repeat-daily" className="cursor-pointer font-normal">
+ <Checkbox
+ id="alert-repeat-daily"
+ variant={scopeVariant}
+ isChecked={field.value}
+ onCheckedChange={(checked) => field.onChange(checked === true)}
+ />
+ Repeat daily until the secret is rotated
+ </Label>
+ )}
/>
- <span>days before a client secret expires</span>
</div>
- <FieldError errors={[errors.alertBeforeDays]} />
- <Controller
- control={control}
- name="dailyReminder"
- render={({ field }) => (
- <Label htmlFor="alert-repeat-daily" className="cursor-pointer font-normal">
- <Checkbox
- id="alert-repeat-daily"
- variant={scopeVariant}
- isChecked={field.value}
- onCheckedChange={(checked) => field.onChange(checked === true)}
- />
- Repeat daily until the secret is rotated
- </Label>
- )}
- />
- </div>
+ )}
<ChannelsField
projectId={projectId}