Skip to content

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

refactor to make domain concise

Thiago Araujo da Silva2d0b44c03924
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 2518500dbd..8e145d6790 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -712,12 +712,13 @@ new consumer gets them for free.
`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
+**The event contract belongs to the domain that emits it, not to a consumer.** The identity auth method
+event (key, resource type, change enum, payload schema, and the `emitIdentityAuthMethodChanged` helper)
+lives in `src/services/identity/identity-auth-method-events.ts`. The 13 auth method services import the
+helper from there and the alert provider imports the schema from there, so neither depends on the other
+and a second consumer of the same event has one place to import from. When several services fire the same
+event, give it one such helper rather than repeating the `emit` literal: the helper owns the payload shape,
+and the provider's test parses what the helper emits with the delivery 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
diff --git a/backend/src/services/alert/alert-engine.ts b/backend/src/services/alert/alert-engine.ts
index ac8fcd5615..66520194ea 100644
--- a/backend/src/services/alert/alert-engine.ts
+++ b/backend/src/services/alert/alert-engine.ts
@@ -224,18 +224,52 @@ export const alertEngineFactory = ({
};
};
- const runAlert = async (alert: TAlerts, opts?: { asOf?: Date }): Promise<AlertDispatchOutcome> => {
+ const $buildChannelWork = (
+ alert: TAlerts,
+ channels: TAlertChannels[],
+ targets: { target: unknown; id: string }[],
+ alreadyAlerted?: Set<string>
+ ): TChannelWork[] =>
+ channels
+ .map((channel) => {
+ const due = alreadyAlerted
+ ? targets.filter((target) => !alreadyAlerted.has(`${channel.id}:${target.id}`))
+ : targets;
+ const cap = ALERT_CHANNEL_REGISTRY[channel.channelType as AlertChannelType]?.maxTargetsPerRun;
+ if (!cap || due.length <= cap) return { channel, due };
+
+ const dropped = due.slice(cap);
+ if (alreadyAlerted) {
+ logger.info(
+ `Alert ${channel.channelType} channel capped at ${cap} targets this run; ${dropped.length} deferred to the next run [alertId=${alert.id}] [channelId=${channel.id}]`
+ );
+ } else {
+ logger.warn(
+ `Alert ${channel.channelType} channel caps at ${cap} targets; dropping ${dropped.length} from this event [alertId=${alert.id}] [channelId=${channel.id}] [dropped=${dropped.map((target) => target.id).join(",")}]`
+ );
+ }
+ return { channel, due: due.slice(0, cap) };
+ })
+ .filter((work) => work.due.length > 0);
+
+ const $getProvider = (alert: TAlerts, discovery: "findDueTargets" | "findTargetsByIds") => {
const provider = alertProviderRegistry.get(alert.resourceType);
if (!provider) {
logger.warn(`No alert provider registered for resource type '${alert.resourceType}' [alertId=${alert.id}]`);
- return AlertDispatchOutcome.NoProvider;
+ return undefined;
}
- if (!provider.findDueTargets) {
+ if (!provider[discovery]) {
logger.warn(
- `Alert provider '${alert.resourceType}' has no findDueTargets, so a scheduled alert cannot run [alertId=${alert.id}]`
+ `Alert provider '${alert.resourceType}' has no ${discovery}, so this alert cannot run [alertId=${alert.id}]`
);
- return AlertDispatchOutcome.NoProvider;
+ return undefined;
}
+ return provider;
+ };
+
+ const runAlert = async (alert: TAlerts, opts?: { asOf?: Date }): Promise<AlertDispatchOutcome> => {
+ const provider = $getProvider(alert, "findDueTargets");
+ if (!provider?.findDueTargets) return AlertDispatchOutcome.NoProvider;
const channels = await alertChannelDAL.findByAlertId(alert.id, { enabled: true });
if (channels.length === 0) return AlertDispatchOutcome.NoChannels;
@@ -260,20 +294,7 @@ export const alertEngineFactory = ({
);
const alertedSet = new Set(recentlyAlerted.map((row) => `${row.channelId}:${row.targetId}`));
- const channelWork = channels
- .map((channel) => {
- const definition = ALERT_CHANNEL_REGISTRY[channel.channelType as AlertChannelType];
- const due = targets.filter((target) => !alertedSet.has(`${channel.id}:${target.id}`));
- const cap = definition?.maxTargetsPerRun;
- if (cap && due.length > cap) {
- logger.info(
- `Alert ${channel.channelType} channel capped at ${cap} targets this run; ${due.length - cap} deferred to the next run [alertId=${alert.id}] [channelId=${channel.id}]`
- );
- return { channel, due: due.slice(0, cap) };
- }
- return { channel, due };
- })
- .filter((work) => work.due.length > 0);
+ const channelWork = $buildChannelWork(alert, channels, targets, alertedSet);
if (channelWork.length === 0) return AlertDispatchOutcome.AllDeduped;
const { outcome } = await $dispatchChannelWork(alert, provider, channelWork);
@@ -284,17 +305,8 @@ export const alertEngineFactory = ({
alert: TAlerts,
input: { eventType: string; targetIds: string[]; payload: Record<string, unknown>; skipChannelIds?: string[] }
): Promise<TDispatchResult> => {
- const provider = alertProviderRegistry.get(alert.resourceType);
- if (!provider) {
- logger.warn(`No alert provider registered for resource type '${alert.resourceType}' [alertId=${alert.id}]`);
- return { outcome: AlertDispatchOutcome.NoProvider, deliveredChannelIds: [] };
- }
- if (!provider.findTargetsByIds) {
- logger.warn(
- `Alert provider '${alert.resourceType}' has no findTargetsByIds, so an event alert cannot run [alertId=${alert.id}]`
- );
- return { outcome: AlertDispatchOutcome.NoProvider, deliveredChannelIds: [] };
- }
+ const provider = $getProvider(alert, "findTargetsByIds");
+ if (!provider?.findTargetsByIds) return { outcome: AlertDispatchOutcome.NoProvider, deliveredChannelIds: [] };
const skip = new Set(input.skipChannelIds ?? []);
const channels = (await alertChannelDAL.findByAlertId(alert.id, { enabled: true, readFromPrimary: true })).filter(
@@ -315,22 +327,7 @@ export const alertEngineFactory = ({
const targets = resolved.map((target) => ({ target, id: provider.targetId(target) }));
- const channelWork = channels.map((channel) => {
- const definition = ALERT_CHANNEL_REGISTRY[channel.channelType as AlertChannelType];
- const cap = definition?.maxTargetsPerRun;
- if (cap && targets.length > cap) {
- 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)
- .map((target) => target.id)
- .join(",")}]`
- );
- return { channel, due: targets.slice(0, cap) };
- }
- return { channel, due: targets };
- });
-
- return $dispatchChannelWork(alert, provider, channelWork);
+ return $dispatchChannelWork(alert, provider, $buildChannelWork(alert, channels, targets));
};
return { runAlert, runAlertForEvent };
diff --git a/backend/src/services/alert/alert-event-consumer.test.ts b/backend/src/services/alert/alert-event-consumer.test.ts
index 5fc1e1bc06..8523099392 100644
--- a/backend/src/services/alert/alert-event-consumer.test.ts
+++ b/backend/src/services/alert/alert-event-consumer.test.ts
@@ -1,5 +1,6 @@
import { AlertDispatchOutcome } from "@app/lib/telemetry/metrics";
-import { EventOutboxStatus, TEventOutboxRow } from "@app/services/event-outbox/event-outbox-types";
+import { TEventOutbox } from "@app/db/schemas";
+import { EventOutboxStatus } from "@app/services/event-outbox/event-outbox-types";
import { alertEventConsumerFactory } from "./alert-event-consumer";
import { AlertTriggerType } from "./alert-types";
@@ -14,7 +15,7 @@ const EVENT_TYPE = "approval.workflow.request_opened";
const makeAlert = (id: string) => ({ id, resourceType: "approval.workflow", orgId: ORG_ID }) as never;
-const makeRow = (overrides?: Partial<TEventOutboxRow>): TEventOutboxRow =>
+const makeRow = (overrides?: Partial<TEventOutbox>): TEventOutbox =>
({
id: 1,
consumer: "alert",
@@ -29,7 +30,7 @@ const makeRow = (overrides?: Partial<TEventOutboxRow>): TEventOutboxRow =>
attempts: 0,
progress: null,
...overrides
- }) as TEventOutboxRow;
+ }) as TEventOutbox;
const buildConsumer = (opts?: {
alerts?: unknown[];
diff --git a/backend/src/services/alert/alert-event-consumer.ts b/backend/src/services/alert/alert-event-consumer.ts
index 32ac470790..853d76d4ba 100644
--- a/backend/src/services/alert/alert-event-consumer.ts
+++ b/backend/src/services/alert/alert-event-consumer.ts
@@ -1,10 +1,10 @@
import { z } from "zod";
+import { TEventOutbox } from "@app/db/schemas";
import { AlertDispatchOutcome, recordAlertDispatchOutcomeMetric } from "@app/lib/telemetry/metrics";
import {
EventOutboxStatus,
IEventOutboxConsumer,
- TEventOutboxRow,
TOutboxRowResult
} from "@app/services/event-outbox/event-outbox-types";
@@ -31,7 +31,7 @@ export type TAlertEventConsumerDep = {
alertProviderRegistry: Pick<TAlertProviderRegistry, "get" | "eventTriggeredKeys">;
};
-type TAlertLookup = Pick<TAlertDALFactory, "findEnabledForEvent">["findEnabledForEvent"];
+type TAlertLookup = TAlertDALFactory["findEnabledForEvent"];
export const alertEventConsumerFactory = ({
alertDAL,
@@ -42,14 +42,14 @@ export const alertEventConsumerFactory = ({
// subscribesTo only sees the event type, so a valid event key on the wrong resourceType gets past it.
// Fail here, terminally and naming both, instead of marking the row delivered as "no matching alert".
- const $isDeclaredEvent = (row: TEventOutboxRow): boolean =>
+ const $isDeclaredEvent = (row: TEventOutbox): boolean =>
Boolean(
alertProviderRegistry
.get(row.resourceType)
?.events.some((event) => event.key === row.eventType && event.triggerType === AlertTriggerType.Event)
);
- const $handleRow = async (row: TEventOutboxRow, findAlerts: TAlertLookup): Promise<TOutboxRowResult> => {
+ const $handleRow = async (row: TEventOutbox, findAlerts: TAlertLookup): Promise<TOutboxRowResult> => {
const id = String(row.id);
if (!$isDeclaredEvent(row)) {
@@ -116,8 +116,7 @@ export const alertEventConsumerFactory = ({
return { ...outcome, status: EventOutboxStatus.Delivered };
};
- const handle = async (rows: TEventOutboxRow[]): Promise<TOutboxRowResult[]> => {
- // A batch shares one resource, so a burst of rows would repeat the same lookup.
+ const handle = async (rows: TEventOutbox[]): Promise<TOutboxRowResult[]> => {
const alertsByScope = new Map<string, ReturnType<TAlertLookup>>();
const findAlerts: TAlertLookup = (filter) => {
const key = `${filter.orgId}|${filter.projectId ?? ""}|${filter.eventType}`;
@@ -136,7 +135,6 @@ export const alertEventConsumerFactory = ({
// eslint-disable-next-line no-await-in-loop -- ordering is the point
results.push(await $handleRow(row, findAlerts));
} catch (error) {
- // Throwing out of handle() retries the whole batch, which re-notifies the rows that already sent.
results.push({
id: String(row.id),
status: EventOutboxStatus.Retry,
diff --git a/backend/src/services/alert/alert-provider-registry.ts b/backend/src/services/alert/alert-provider-registry.ts
index a907e024dc..1608dd0b1a 100644
--- a/backend/src/services/alert/alert-provider-registry.ts
+++ b/backend/src/services/alert/alert-provider-registry.ts
@@ -4,6 +4,7 @@ export type TAlertProviderRegistry = ReturnType<typeof alertProviderRegistryFact
export const alertProviderRegistryFactory = () => {
const providers = new Map<string, IResourceAlertProvider>();
+ let eventTriggeredKeyCache: Set<string> | undefined;
const register = (provider: IResourceAlertProvider) => {
if (providers.has(provider.resourceType)) {
@@ -24,18 +25,21 @@ export const alertProviderRegistryFactory = () => {
}
providers.set(provider.resourceType, provider);
+ eventTriggeredKeyCache = undefined;
};
const get = (resourceType: string): IResourceAlertProvider | undefined => providers.get(resourceType);
const resourceTypes = (): string[] => [...providers.keys()];
- const eventTriggeredKeys = (): Set<string> =>
- new Set(
+ const eventTriggeredKeys = (): Set<string> => {
+ eventTriggeredKeyCache ??= new Set(
[...providers.values()].flatMap((provider) =>
provider.events.filter((event) => event.triggerType === AlertTriggerType.Event).map((event) => event.key)
)
);
+ return eventTriggeredKeyCache;
+ };
return { register, get, resourceTypes, eventTriggeredKeys };
};
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 c5bb3d5922..b4694211b6 100644
--- a/backend/src/services/alert/providers/identity-credential-alert-dal.ts
+++ b/backend/src/services/alert/providers/identity-credential-alert-dal.ts
@@ -141,10 +141,10 @@ export const identityCredentialAlertDALFactory = (db: TDbClient) => {
}
};
- const findIdentitiesByIds = async (identityIds: string[]): Promise<{ id: string; name: string }[]> => {
+ const findIdentitiesByIds = async (identityIds: string[], orgId: 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 {
+ const rows = (await db(TableName.Identity).whereIn("id", identityIds).where({ orgId }).select("id", "name")) as {
id: string;
name: string;
}[];
diff --git a/backend/src/services/alert/providers/identity-credential-alert-provider.test.ts b/backend/src/services/alert/providers/identity-credential-alert-provider.test.ts
index b37fd30104..e9527ab9f7 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
@@ -3,6 +3,11 @@ import { vi } from "vitest";
import { IdentityAuthMethod } from "@app/db/schemas";
import { ActorType } from "@app/services/auth/auth-type";
+import {
+ emitIdentityAuthMethodChanged,
+ IdentityAuthMethodChange,
+ IdentityAuthMethodChangePayloadSchema
+} from "@app/services/identity/identity-auth-method-events";
import {
ALERT_HISTORY_RETENTION_DAYS,
@@ -15,10 +20,7 @@ import {
IDENTITY_AUTH_METHOD_CHANGED_EVENT,
IDENTITY_AUTHENTICATION_EXPIRY_EVENT,
IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
- IdentityAuthMethodChange,
- IdentityAuthMethodChangePayloadSchema,
identityCredentialAlertProviderFactory,
- TIdentityAuthMethodChangeEventPayload,
TIdentityCredentialAlertProviderDep
} from "./identity-credential-alert-provider";
@@ -146,27 +148,36 @@ describe("identity credential alert provider", () => {
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);
+ // The auth method services emit through this helper and the provider parses the schema at delivery.
+ // This is the one place the two are checked against each other.
+ test("the emitted payload is accepted by the delivery schema", async () => {
+ const emitted: unknown[] = [];
+ const emitter = { emit: async (event: { payload: unknown }) => void emitted.push(event.payload) };
+ const membership = { identity: { id: "ident-1", projectId: null }, scopeOrgId: "org-1" };
+
+ await emitIdentityAuthMethodChanged(
+ emitter,
+ {
+ membership,
+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
+ change: IdentityAuthMethodChange.CredentialAdded,
+ actor: ActorType.USER,
+ actorId: "u1",
+ credential: { id: "cs-1", name: null }
+ },
+ {} as never
+ );
+ await emitIdentityAuthMethodChanged(
+ emitter,
+ { membership, authMethod: IdentityAuthMethod.TOKEN_AUTH, change: IdentityAuthMethodChange.Removed, actor: ActorType.PLATFORM },
+ {} as never
+ );
+
+ expect(emitted).toHaveLength(2);
+ for (const payload of emitted) {
+ expect(IdentityAuthMethodChangePayloadSchema.safeParse(payload).success).toBe(true);
+ expect((payload as { targetIds: string[] }).targetIds).toEqual(["ident-1"]);
+ }
});
test("findTargetsByIds rehydrates the identity and the change from the event payload", async () => {
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 5dd69581a7..a40f6f04ff 100644
--- a/backend/src/services/alert/providers/identity-credential-alert-provider.ts
+++ b/backend/src/services/alert/providers/identity-credential-alert-provider.ts
@@ -9,6 +9,12 @@ import { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/ee/
import { getConfig } from "@app/lib/config/env";
import { ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { ActorType } from "@app/services/auth/auth-type";
+import {
+ IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ IdentityAuthMethodChange,
+ IdentityAuthMethodChangePayloadSchema
+} from "@app/services/identity/identity-auth-method-events";
import { TAlertPayload, TAlertSeverity } from "../alert-channel-types";
import {
@@ -27,45 +33,13 @@ import {
} 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 { IDENTITY_AUTH_METHOD_CHANGED_EVENT, IDENTITY_AUTHENTICATION_RESOURCE_TYPE };
-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;
-};
+export const IDENTITY_AUTHENTICATION_EXPIRY_EVENT = "identity.authentication.expiry";
const IdentityAuthMethodChangeConditionSchema = z.object({}).nullish();
-export const IDENTITY_AUTH_METHOD_LABELS: Record<IdentityAuthMethod, string> = {
+const IDENTITY_AUTH_METHOD_LABELS: Record<IdentityAuthMethod, string> = {
[IdentityAuthMethod.TOKEN_AUTH]: "Token Auth",
[IdentityAuthMethod.UNIVERSAL_AUTH]: "Universal Auth",
[IdentityAuthMethod.KUBERNETES_AUTH]: "Kubernetes Auth",
@@ -272,7 +246,7 @@ export const identityCredentialAlertProviderFactory = ({
}));
};
- const resolveActorLabel = async (actorType: ActorType, actorId?: string): Promise<string> => {
+ const resolveActorLabel = async (orgId: string, actorType: ActorType, actorId?: string): Promise<string> => {
const typeLabel = ACTOR_TYPE_LABEL[actorType] ?? actorType;
if (!actorId) return typeLabel;
@@ -281,7 +255,7 @@ export const identityCredentialAlertProviderFactory = ({
return label ? `${label} (user)` : typeLabel;
}
if (actorType === ActorType.IDENTITY) {
- const [identity] = await identityCredentialAlertDAL.findIdentitiesByIds([actorId]);
+ const [identity] = await identityCredentialAlertDAL.findIdentitiesByIds([actorId], orgId);
return identity ? `${identity.name} (machine identity)` : typeLabel;
}
return typeLabel;
@@ -300,10 +274,10 @@ export const identityCredentialAlertProviderFactory = ({
}
const change = parsed.data;
- const identities = await identityCredentialAlertDAL.findIdentitiesByIds(input.targetIds);
+ const identities = await identityCredentialAlertDAL.findIdentitiesByIds(input.targetIds, input.orgId);
if (identities.length === 0) return [];
- const actorLabel = await resolveActorLabel(change.actorType, change.actorId);
+ const actorLabel = await resolveActorLabel(input.orgId, change.actorType, change.actorId);
return identities.map((identity) => ({
kind: "auth-method-change" as const,
diff --git a/backend/src/services/event-outbox/event-outbox-dal.ts b/backend/src/services/event-outbox/event-outbox-dal.ts
index b1f905dbc7..c90c4b36e7 100644
--- a/backend/src/services/event-outbox/event-outbox-dal.ts
+++ b/backend/src/services/event-outbox/event-outbox-dal.ts
@@ -1,10 +1,10 @@
import { Knex } from "knex";
import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
+import { TableName, TEventOutbox } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
-import { computeBackoffMs, EventOutboxStatus, TEventOutboxRow, TOutboxFlushKey } from "./event-outbox-types";
+import { computeBackoffMs, EventOutboxStatus, TOutboxFlushKey } from "./event-outbox-types";
export type TEventOutboxDALFactory = ReturnType<typeof eventOutboxDALFactory>;
@@ -60,7 +60,7 @@ export const eventOutboxDALFactory = (db: TDbClient) => {
};
// One statement on purpose: the row locks live only as long as the UPDATE.
- const claimBatch = async (key: TOutboxFlushKey, limit: number): Promise<TEventOutboxRow[]> => {
+ const claimBatch = async (key: TOutboxFlushKey, limit: number): Promise<TEventOutbox[]> => {
try {
const claimed = await db(TableName.EventOutbox)
.whereIn("id", (qb) => {
@@ -79,7 +79,7 @@ export const eventOutboxDALFactory = (db: TDbClient) => {
.returning("*");
// RETURNING order is arbitrary, and handle() is promised id order.
- return (claimed as unknown as TEventOutboxRow[]).sort((a, b) => (BigInt(a.id) < BigInt(b.id) ? -1 : 1));
+ return (claimed as unknown as TEventOutbox[]).sort((a, b) => (BigInt(a.id) < BigInt(b.id) ? -1 : 1));
} catch (error) {
throw new DatabaseError({ error, name: "EventOutbox: claimBatch" });
}
@@ -112,51 +112,38 @@ export const eventOutboxDALFactory = (db: TDbClient) => {
try {
await db.transaction(async (tx) => {
+ const settle = (ids: string[], values: Record<string, unknown>) =>
+ tx(TableName.EventOutbox)
+ .whereIn("id", ids)
+ .where("status", EventOutboxStatus.Processing)
+ .update({ lockedAt: null, ...values });
+
+ const progressOf = (group: { progress?: Record<string, unknown> | null }) =>
+ group.progress !== undefined ? { progress: JSON.stringify(group.progress) } : {};
+
for (const group of input.delivered) {
- if (group.ids.length > 0) {
- // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes are serial
- await tx(TableName.EventOutbox)
- .whereIn("id", group.ids)
- .where("status", EventOutboxStatus.Processing)
- .update({
- status: EventOutboxStatus.Delivered,
- lockedAt: null,
- lastError: null,
- ...(group.progress !== undefined ? { progress: JSON.stringify(group.progress) } : {})
- });
- }
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes are serial
+ await settle(group.ids, { status: EventOutboxStatus.Delivered, lastError: null, ...progressOf(group) });
}
for (const group of input.retriable) {
- if (group.ids.length > 0) {
- // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes are serial
- await tx(TableName.EventOutbox)
- .whereIn("id", group.ids)
- .where("status", EventOutboxStatus.Processing)
- .update({
- status: EventOutboxStatus.Retry,
- attempts: db.raw('"attempts" + 1'),
- nextRetryAt: db.raw(`NOW() + (? || ' milliseconds')::INTERVAL`, [group.nextRetryDelayMs]),
- lockedAt: null,
- lastError: group.error ?? null,
- ...(group.progress !== undefined ? { progress: JSON.stringify(group.progress) } : {})
- });
- }
+ // eslint-disable-next-line no-await-in-loop -- see above
+ await settle(group.ids, {
+ status: EventOutboxStatus.Retry,
+ attempts: db.raw('"attempts" + 1'),
+ nextRetryAt: db.raw(`NOW() + (? || ' milliseconds')::INTERVAL`, [group.nextRetryDelayMs]),
+ lastError: group.error ?? null,
+ ...progressOf(group)
+ });
}
for (const group of input.failed) {
- if (group.ids.length > 0) {
- // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes are serial
- await tx(TableName.EventOutbox)
- .whereIn("id", group.ids)
- .where("status", EventOutboxStatus.Processing)
- .update({
- status: EventOutboxStatus.Failed,
- attempts: db.raw('"attempts" + 1'),
- lockedAt: null,
- lastError: group.error ?? null
- });
- }
+ // eslint-disable-next-line no-await-in-loop -- see above
+ await settle(group.ids, {
+ status: EventOutboxStatus.Failed,
+ attempts: db.raw('"attempts" + 1'),
+ lastError: group.error ?? null
+ });
}
});
} catch (error) {
diff --git a/backend/src/services/event-outbox/event-outbox-queue.ts b/backend/src/services/event-outbox/event-outbox-queue.ts
index 232199edf7..a426a33137 100644
--- a/backend/src/services/event-outbox/event-outbox-queue.ts
+++ b/backend/src/services/event-outbox/event-outbox-queue.ts
@@ -46,7 +46,7 @@ export const eventOutboxQueueFactory = ({
unit: "s"
});
oldestPendingGauge.addCallback((result) => {
- if (!getConfig().OTEL_TELEMETRY_COLLECTION_ENABLED) return;
+ if (!appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) return;
oldestPendingByConsumer.forEach(({ consumer, ageSeconds }) => {
result.observe(ageSeconds, { "event_outbox.consumer": consumer });
});
@@ -58,7 +58,7 @@ export const eventOutboxQueueFactory = ({
unit: "{key}"
});
discoveryGauge.addCallback((result) => {
- if (!getConfig().OTEL_TELEMETRY_COLLECTION_ENABLED) return;
+ if (!appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) return;
result.observe(lastDiscoveryCount);
});
};
diff --git a/backend/src/services/event-outbox/event-outbox-service.test.ts b/backend/src/services/event-outbox/event-outbox-service.test.ts
index dc104998e7..ebbbe7f825 100644
--- a/backend/src/services/event-outbox/event-outbox-service.test.ts
+++ b/backend/src/services/event-outbox/event-outbox-service.test.ts
@@ -1,5 +1,7 @@
import { z } from "zod";
+import { TEventOutbox } from "@app/db/schemas";
+
import { eventOutboxRegistryFactory } from "./event-outbox-registry";
import { eventOutboxServiceFactory } from "./event-outbox-service";
import {
@@ -7,7 +9,6 @@ import {
IEventOutboxConsumer,
MAX_OUTBOX_ATTEMPTS,
MAX_OUTBOX_PAYLOAD_BYTES,
- TEventOutboxRow,
TOutboxEvent
} from "./event-outbox-types";
@@ -143,7 +144,7 @@ describe("event outbox emit", () => {
});
describe("event outbox drain", () => {
- const makeRow = (overrides?: Partial<TEventOutboxRow>): TEventOutboxRow =>
+ const makeRow = (overrides?: Partial<TEventOutbox>): TEventOutbox =>
({
id: 1,
consumer: "alert",
@@ -164,10 +165,10 @@ describe("event outbox drain", () => {
createdAt: new Date(),
updatedAt: new Date(),
...overrides
- }) as TEventOutboxRow;
+ }) as TEventOutbox;
const buildDrain = (opts: {
- batches: TEventOutboxRow[][];
+ batches: TEventOutbox[][];
handle: IEventOutboxConsumer["handle"];
consumerName?: string;
}) => {
diff --git a/backend/src/services/event-outbox/event-outbox-service.ts b/backend/src/services/event-outbox/event-outbox-service.ts
index 26ecdfc3cb..ed90bcc222 100644
--- a/backend/src/services/event-outbox/event-outbox-service.ts
+++ b/backend/src/services/event-outbox/event-outbox-service.ts
@@ -1,5 +1,6 @@
import { Knex } from "knex";
+import { TEventOutbox } from "@app/db/schemas";
import { InternalServerError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { recordEventOutboxExhaustedMetric, recordEventOutboxLagMetric } from "@app/lib/telemetry/metrics";
@@ -18,7 +19,6 @@ import {
OUTBOX_CLAIM_BATCH_SIZE,
OutboxEventSchema,
STALE_CLAIM_THRESHOLD_MS,
- TEventOutboxRow,
TOutboxEvent,
TOutboxFlushKey,
TOutboxRowResult
@@ -143,7 +143,7 @@ export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry
}
};
- const $applyResults = async (rows: TEventOutboxRow[], results: TOutboxRowResult[]): Promise<void> => {
+ const $applyResults = async (rows: TEventOutbox[], results: TOutboxRowResult[]): Promise<void> => {
const byId = new Map(results.map((result) => [result.id, result]));
const now = Date.now();
@@ -213,7 +213,7 @@ export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry
const $handleClaimed = async (
consumer: IEventOutboxConsumer,
key: TOutboxFlushKey,
- claimed: TEventOutboxRow[]
+ claimed: TEventOutbox[]
): Promise<TOutboxRowResult[]> => {
const ids = claimed.map((row) => String(row.id));
const heartbeat = setInterval(() => {
diff --git a/backend/src/services/event-outbox/event-outbox-types.ts b/backend/src/services/event-outbox/event-outbox-types.ts
index c23fe2b8a4..384d5b1593 100644
--- a/backend/src/services/event-outbox/event-outbox-types.ts
+++ b/backend/src/services/event-outbox/event-outbox-types.ts
@@ -13,7 +13,7 @@ export enum EventOutboxStatus {
export const MAX_OUTBOX_PAYLOAD_BYTES = 16 * 1024;
-export const MAX_OUTBOX_KEY_LENGTH = 255;
+const MAX_OUTBOX_KEY_LENGTH = 255;
export const RELAY_DISCOVERY_LIMIT = 200;
@@ -62,7 +62,6 @@ export const OutboxEventSchema = z.object({
export type TOutboxEvent = z.input<typeof OutboxEventSchema>;
-export type TEventOutboxRow = TEventOutbox;
export type TOutboxRowResult = {
id: string;
@@ -91,5 +90,5 @@ export interface IEventOutboxConsumer<TPayload = unknown> {
subscribesTo(eventType: string): boolean;
// Rows for a single (resourceType, resourceId), in id order. Must return one result per row.
- handle(rows: TEventOutboxRow[]): Promise<TOutboxRowResult[]>;
+ handle(rows: TEventOutbox[]): Promise<TOutboxRowResult[]>;
}
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 b7a4e8dcee..25301c2120 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
@@ -34,11 +34,9 @@ import {
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";
+ emitIdentityAuthMethodChanged,
+ IdentityAuthMethodChange
+} from "@app/services/identity/identity-auth-method-events";
import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
@@ -353,21 +351,14 @@ export const identityAliCloudAuthServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.ALICLOUD_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actor,
+ actorId
},
tx
);
@@ -480,21 +471,14 @@ export const identityAliCloudAuthServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.ALICLOUD_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actor,
+ actorId
},
tx
);
@@ -643,21 +627,14 @@ export const identityAliCloudAuthServiceFactory = ({
const deletedAliCloudAuth = await identityAliCloudAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.ALICLOUD_AUTH }, tx);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.ALICLOUD_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actor,
+ actorId
},
tx
);
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 13f3805014..8425811df5 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
@@ -35,11 +35,9 @@ import {
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";
+ emitIdentityAuthMethodChanged,
+ IdentityAuthMethodChange
+} from "@app/services/identity/identity-auth-method-events";
import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
@@ -453,21 +451,14 @@ export const identityAwsAuthServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.AWS_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actor,
+ actorId
},
tx
);
@@ -583,21 +574,14 @@ export const identityAwsAuthServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.AWS_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actor,
+ actorId
},
tx
);
@@ -745,21 +729,14 @@ export const identityAwsAuthServiceFactory = ({
const deletedAwsAuth = await identityAwsAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.AWS_AUTH }, tx);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.AWS_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actor,
+ actorId
},
tx
);
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 dcb93fe206..ef5ca70cc4 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
@@ -30,11 +30,9 @@ import {
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";
+ emitIdentityAuthMethodChanged,
+ IdentityAuthMethodChange
+} from "@app/services/identity/identity-auth-method-events";
import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
@@ -354,21 +352,14 @@ export const identityAzureAuthServiceFactory = ({
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.AZURE_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actor,
+ actorId
},
tx
);
@@ -484,21 +475,14 @@ export const identityAzureAuthServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.AZURE_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actor,
+ actorId
},
tx
);
@@ -647,21 +631,14 @@ export const identityAzureAuthServiceFactory = ({
const deletedAzureAuth = await identityAzureAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.AZURE_AUTH }, tx);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.AZURE_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actor,
+ actorId
},
tx
);
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 f6ec6d7d76..929598e9a2 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
@@ -30,11 +30,9 @@ import {
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";
+ emitIdentityAuthMethodChanged,
+ IdentityAuthMethodChange
+} from "@app/services/identity/identity-auth-method-events";
import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
@@ -399,21 +397,14 @@ export const identityGcpAuthServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.GCP_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actor,
+ actorId
},
tx
);
@@ -531,21 +522,14 @@ export const identityGcpAuthServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.GCP_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actor,
+ actorId
},
tx
);
@@ -694,21 +678,14 @@ export const identityGcpAuthServiceFactory = ({
const deletedGcpAuth = await identityGcpAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.GCP_AUTH }, tx);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.GCP_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actor,
+ actorId
},
tx
);
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 96e9d025a5..81364965d0 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
@@ -42,11 +42,9 @@ import {
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";
+ emitIdentityAuthMethodChanged,
+ IdentityAuthMethodChange
+} from "@app/services/identity/identity-auth-method-events";
import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
@@ -543,21 +541,14 @@ export const identityJwtAuthServiceFactory = ({
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.JWT_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actor,
+ actorId
},
tx
);
@@ -706,21 +697,14 @@ export const identityJwtAuthServiceFactory = ({
const updatedJwtAuth = await identityJwtAuthDAL.transaction(async (tx) => {
const doc = await identityJwtAuthDAL.updateById(identityJwtAuth.id, updateQuery, tx);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.JWT_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actor,
+ actorId
},
tx
);
@@ -896,21 +880,14 @@ export const identityJwtAuthServiceFactory = ({
const deletedJwtAuth = await identityJwtAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.JWT_AUTH }, tx);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.JWT_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actor,
+ actorId
},
tx
);
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 1145bee015..fb826698f9 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
@@ -63,11 +63,9 @@ import {
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";
+ emitIdentityAuthMethodChanged,
+ IdentityAuthMethodChange
+} from "@app/services/identity/identity-auth-method-events";
import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
@@ -1145,21 +1143,14 @@ export const identityKubernetesAuthServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.KUBERNETES_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actor,
+ actorId
},
tx
);
@@ -1625,21 +1616,14 @@ export const identityKubernetesAuthServiceFactory = ({
const updatedKubernetesAuth = await identityKubernetesAuthDAL.transaction(async (tx) => {
const doc = await identityKubernetesAuthDAL.updateById(identityKubernetesAuth.id, updateQuery, tx);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.KUBERNETES_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actor,
+ actorId
},
tx
);
@@ -1844,21 +1828,14 @@ 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(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.KUBERNETES_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actor,
+ actorId
},
tx
);
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 49cb17b2a4..36a78954d4 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
@@ -41,11 +41,9 @@ import {
} 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";
+ emitIdentityAuthMethodChanged,
+ IdentityAuthMethodChange
+} from "@app/services/identity/identity-auth-method-events";
import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
@@ -529,21 +527,14 @@ export const identityLdapAuthServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.LDAP_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actor,
+ actorId
},
tx
);
@@ -782,21 +773,14 @@ export const identityLdapAuthServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.LDAP_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actor,
+ actorId
},
tx
);
@@ -957,21 +941,14 @@ export const identityLdapAuthServiceFactory = ({
const [deletedLdapAuth] = await identityLdapAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.LDAP_AUTH }, tx);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.LDAP_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actor,
+ actorId
},
tx
);
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 d1b6e55c89..fc26f6aced 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
@@ -35,11 +35,9 @@ import {
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";
+ emitIdentityAuthMethodChanged,
+ IdentityAuthMethodChange
+} from "@app/services/identity/identity-auth-method-events";
import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
@@ -367,21 +365,14 @@ export const identityOciAuthServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.OCI_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actor,
+ actorId
},
tx
);
@@ -496,21 +487,14 @@ export const identityOciAuthServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.OCI_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actor,
+ actorId
},
tx
);
@@ -659,21 +643,14 @@ export const identityOciAuthServiceFactory = ({
const deletedOciAuth = await identityOciAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.OCI_AUTH }, tx);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.OCI_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actor,
+ actorId
},
tx
);
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 7f1ad40576..4623bab53f 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
@@ -52,11 +52,9 @@ import {
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";
+ emitIdentityAuthMethodChanged,
+ IdentityAuthMethodChange
+} from "@app/services/identity/identity-auth-method-events";
import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
@@ -776,21 +774,14 @@ export const identityOidcAuthServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.OIDC_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actor,
+ actorId
},
tx
);
@@ -1001,21 +992,14 @@ export const identityOidcAuthServiceFactory = ({
const updatedOidcAuth = await identityOidcAuthDAL.transaction(async (tx) => {
const doc = await identityOidcAuthDAL.updateById(identityOidcAuth.id, updateQuery, tx);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.OIDC_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actor,
+ actorId
},
tx
);
@@ -1193,21 +1177,14 @@ export const identityOidcAuthServiceFactory = ({
const deletedOidcAuth = await identityOidcAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.OIDC_AUTH }, tx);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.OIDC_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actor,
+ actorId
},
tx
);
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 d8a1aa0dfc..862cb685e3 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
@@ -40,11 +40,9 @@ import {
} 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";
+ emitIdentityAuthMethodChanged,
+ IdentityAuthMethodChange
+} from "@app/services/identity/identity-auth-method-events";
import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
@@ -621,21 +619,14 @@ export const identitySpiffeAuthServiceFactory = ({
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.SPIFFE_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actor,
+ actorId
},
tx
);
@@ -786,21 +777,14 @@ export const identitySpiffeAuthServiceFactory = ({
const updatedSpiffeAuth = await identitySpiffeAuthDAL.transaction(async (tx) => {
const doc = await identitySpiffeAuthDAL.updateById(identitySpiffeAuth.id, updateQuery, tx);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.SPIFFE_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actor,
+ actorId
},
tx
);
@@ -985,21 +969,14 @@ export const identitySpiffeAuthServiceFactory = ({
const deletedSpiffeAuth = await identitySpiffeAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.SPIFFE_AUTH }, tx);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.SPIFFE_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actor,
+ actorId
},
tx
);
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 1703c5d79a..895f557612 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
@@ -33,11 +33,9 @@ import {
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";
+ emitIdentityAuthMethodChanged,
+ IdentityAuthMethodChange
+} from "@app/services/identity/identity-auth-method-events";
import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
@@ -592,21 +590,14 @@ export const identityTlsCertAuthServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.TLS_CERT_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actor,
+ actorId
},
tx
);
@@ -739,21 +730,14 @@ export const identityTlsCertAuthServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.TLS_CERT_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actor,
+ actorId
},
tx
);
@@ -915,21 +899,14 @@ export const identityTlsCertAuthServiceFactory = ({
const deletedTlsCertAuth = await identityTlsCertAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.TLS_CERT_AUTH }, tx);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.TLS_CERT_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actor,
+ actorId
},
tx
);
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 c1a0ecfa0e..140091df9b 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
@@ -27,11 +27,9 @@ 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";
+ emitIdentityAuthMethodChanged,
+ IdentityAuthMethodChange
+} from "@app/services/identity/identity-auth-method-events";
import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
@@ -186,21 +184,14 @@ export const identityTokenAuthServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.TOKEN_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actor,
+ actorId
},
tx
);
@@ -312,21 +303,14 @@ export const identityTokenAuthServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.TOKEN_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actor,
+ actorId
},
tx
);
@@ -479,21 +463,14 @@ export const identityTokenAuthServiceFactory = ({
const deletedTokenAuth = await identityTokenAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.TOKEN_AUTH }, tx);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.TOKEN_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actor,
+ actorId
},
tx
);
@@ -670,23 +647,15 @@ export const identityTokenAuthServiceFactory = ({
accessTokenTrustedIps: identityTokenAuth.accessTokenTrustedIps as TIp[],
persistToPg: { tx, name }
});
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.TOKEN_AUTH,
+ change: IdentityAuthMethodChange.CredentialAdded,
+ actor,
+ actorId,
+ credential: { id: issued.identityAccessToken.id, name }
},
tx
);
@@ -927,23 +896,15 @@ export const identityTokenAuthServiceFactory = ({
{ name },
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.TOKEN_AUTH,
+ change: IdentityAuthMethodChange.CredentialUpdated,
+ actor,
+ actorId,
+ credential: { id: doc.id, name: doc.name }
},
tx
);
@@ -1022,23 +983,15 @@ export const identityTokenAuthServiceFactory = ({
{ isAccessTokenRevoked: true },
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityOrgMembership,
+ authMethod: IdentityAuthMethod.TOKEN_AUTH,
+ change: IdentityAuthMethodChange.CredentialRevoked,
+ actor,
+ actorId,
+ credential: { id: doc.id, name: doc.name }
},
tx
);
diff --git a/backend/src/services/identity-ua/identity-ua-service.ts b/backend/src/services/identity-ua/identity-ua-service.ts
index 89426bf195..1a73cc5f60 100644
--- a/backend/src/services/identity-ua/identity-ua-service.ts
+++ b/backend/src/services/identity-ua/identity-ua-service.ts
@@ -33,11 +33,9 @@ import {
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";
+ emitIdentityAuthMethodChanged,
+ IdentityAuthMethodChange
+} from "@app/services/identity/identity-auth-method-events";
import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
import { ActorType } from "../auth/auth-type";
@@ -554,21 +552,14 @@ export const identityUaServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
+ change: IdentityAuthMethodChange.Added,
+ actor,
+ actorId
},
tx
);
@@ -716,21 +707,14 @@ export const identityUaServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
+ change: IdentityAuthMethodChange.Updated,
+ actor,
+ actorId
},
tx
);
@@ -877,21 +861,14 @@ export const identityUaServiceFactory = ({
await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);
const revokedIdentityUniversalAuth = await identityUaDAL.transaction(async (tx) => {
const deletedUniversalAuth = await identityUaDAL.delete({ identityId }, tx);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
+ change: IdentityAuthMethodChange.Removed,
+ actor,
+ actorId
},
tx
);
@@ -1021,23 +998,15 @@ export const identityUaServiceFactory = ({
},
tx
);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
+ change: IdentityAuthMethodChange.CredentialAdded,
+ actor,
+ actorId,
+ credential: { id: doc.id, name: doc.description || doc.clientSecretPrefix }
},
tx
);
@@ -1337,23 +1306,15 @@ export const identityUaServiceFactory = ({
const updatedClientSecret = await identityUaDAL.transaction(async (tx) => {
const doc = await identityUaClientSecretDAL.updateById(clientSecretId, { isClientSecretRevoked: true }, tx);
- await eventOutboxService.emit(
+ await emitIdentityAuthMethodChanged(
+ eventOutboxService,
{
- 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
+ membership: identityMembershipOrg,
+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
+ change: IdentityAuthMethodChange.CredentialRevoked,
+ actor,
+ actorId,
+ credential: { id: doc.id, name: doc.description || doc.clientSecretPrefix }
},
tx
);
diff --git a/backend/src/services/identity/identity-auth-method-events.ts b/backend/src/services/identity/identity-auth-method-events.ts
new file mode 100644
index 0000000000..5f152f443f
--- /dev/null
+++ b/backend/src/services/identity/identity-auth-method-events.ts
@@ -0,0 +1,62 @@
+import { Knex } from "knex";
+import { z } from "zod";
+
+import { IdentityAuthMethod } from "@app/db/schemas";
+import { ActorType } from "@app/services/auth/auth-type";
+import { TEventOutboxEmitter } from "@app/services/event-outbox/event-outbox-service";
+
+export const IDENTITY_AUTHENTICATION_RESOURCE_TYPE = "identity.authentication";
+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 TIdentityAuthMethodChangeInput = {
+ membership: { identity: { id: string; projectId?: string | null }; scopeOrgId: string };
+ authMethod: IdentityAuthMethod;
+ change: IdentityAuthMethodChange;
+ actor: ActorType;
+ actorId?: string;
+ credential?: { id: string; name?: string | null };
+};
+
+export const emitIdentityAuthMethodChanged = (
+ eventOutbox: TEventOutboxEmitter,
+ { membership, authMethod, change, actor, actorId, credential }: TIdentityAuthMethodChangeInput,
+ tx: Knex
+): Promise<void> =>
+ eventOutbox.emit(
+ {
+ eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: membership.identity.id,
+ orgId: membership.scopeOrgId,
+ projectId: membership.identity.projectId,
+ payload: {
+ targetIds: [membership.identity.id],
+ authMethod,
+ change,
+ actorType: actor,
+ actorId,
+ changedAt: new Date().toISOString(),
+ ...(credential ? { credentialId: credential.id, credentialName: credential.name ?? undefined } : {})
+ }
+ },
+ tx
+ );