Skip to content

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

feat: new project sse completed

=7d76d0bb3ff6
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 944099e96e..177f12a9c4 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -19,6 +19,7 @@ import { TEventBusService } from "@app/ee/services/event/event-bus-service";
import { TServerSentEventsService } from "@app/ee/services/event/event-sse-service";
import { TEventBusService as TInternalEventBusService } from "@app/ee/services/event-bus";
import { TExternalKmsServiceFactory } from "@app/ee/services/external-kms/external-kms-service";
+import { TProjectEventsService, TProjectEventsSSEService } from "@app/ee/services/project-events";
import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TGithubOrgSyncServiceFactory } from "@app/ee/services/github-org-sync/github-org-sync-service";
@@ -354,6 +355,8 @@ declare module "fastify" {
reminder: TReminderServiceFactory;
bus: TEventBusService;
eventBus: TInternalEventBusService;
+ projectEvents: TProjectEventsService;
+ projectEventsSSE: TProjectEventsSSEService;
sse: TServerSentEventsService;
identityAuthTemplate: TIdentityAuthTemplateServiceFactory;
notification: TNotificationServiceFactory;
diff --git a/backend/src/ee/services/event-bus/event-bus-service.ts b/backend/src/ee/services/event-bus/event-bus-service.ts
index 54a0f0f73b..138b1974af 100644
--- a/backend/src/ee/services/event-bus/event-bus-service.ts
+++ b/backend/src/ee/services/event-bus/event-bus-service.ts
@@ -52,7 +52,7 @@ export const eventBusServiceFactory = ({ redis }: TEventBusServiceFactoryDep) =>
* - Immediately delivers to local subscribers via memory bus
* - Broadcasts to other containers via Redis
*/
- const publish = async <T extends Record<string, unknown>>(type: EventBusServiceEvents, payload: T): Promise<void> => {
+ const publish = async <T>(type: EventBusServiceEvents, payload: T): Promise<void> => {
const event: TEventBusEvent = {
type,
timestamp: new Date().toISOString(),
diff --git a/backend/src/ee/services/event-bus/event-bus-types.ts b/backend/src/ee/services/event-bus/event-bus-types.ts
index 6c0d662511..b6eae9d297 100644
--- a/backend/src/ee/services/event-bus/event-bus-types.ts
+++ b/backend/src/ee/services/event-bus/event-bus-types.ts
@@ -7,10 +7,7 @@ export enum EventBusTopicName {
// Event types that can be published/subscribed
export enum EventBusServiceEvents {
- SecretCreated = "secret.created",
- SecretUpdated = "secret.updated",
- SecretDeleted = "secret.deleted",
- SecretImportMutation = "secret.import-mutation"
+ SecretMutation = "secret.mutation"
}
// Base event schema - all events must have these fields
@@ -18,7 +15,7 @@ export const EventBusSchema = z.object({
type: z.nativeEnum(EventBusServiceEvents),
timestamp: z.string().datetime(),
sourceContainer: z.string(),
- payload: z.record(z.unknown())
+ payload: z.unknown()
});
export type TEventBusEvent = z.infer<typeof EventBusSchema>;
diff --git a/backend/src/ee/services/event-bus/memory-bus.ts b/backend/src/ee/services/event-bus/memory-bus.ts
index c363ce49d1..437e7de2d8 100644
--- a/backend/src/ee/services/event-bus/memory-bus.ts
+++ b/backend/src/ee/services/event-bus/memory-bus.ts
@@ -9,7 +9,7 @@ const ALL_EVENTS_CHANNEL = "__all__";
export const createMemoryBus = () => {
const emitter = new EventEmitter();
// Increase max listeners to avoid warnings with many subscribers
- emitter.setMaxListeners(100);
+ emitter.setMaxListeners(0);
/**
* Emit an event to all subscribers of that event type
diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.ts
index e94f89113d..2a7b08df85 100644
--- a/backend/src/ee/services/license/license-fns.ts
+++ b/backend/src/ee/services/license/license-fns.ts
@@ -110,7 +110,7 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({
enterpriseCertificateSyncs: false,
enterpriseAppConnections: false,
fips: false,
- eventSubscriptions: false,
+ eventSubscriptions: true,
machineIdentityAuthTemplates: false,
pkiLegacyTemplates: false,
secretShareExternalBranding: false
diff --git a/backend/src/ee/services/project-events/index.ts b/backend/src/ee/services/project-events/index.ts
new file mode 100644
index 0000000000..cb93e801d5
--- /dev/null
+++ b/backend/src/ee/services/project-events/index.ts
@@ -0,0 +1,13 @@
+export { projectEventsServiceFactory, TProjectEventsService } from "./project-events-service";
+export {
+ getSSEHeaders,
+ projectEventsSSEServiceFactory,
+ TProjectEventsSSEService
+} from "./project-events-sse-service";
+export { ISSERegisterEntry, ISSESubscribeOpts, TSSEClient, TSSEEvent } from "./project-events-sse-types";
+export {
+ ProjectEvents as SecretMutationType,
+ TProjectEventSubscriber,
+ TProjectEventUnsubscribe,
+ TProjectEventPayload as TSecretMutationPayload
+} from "./project-events-types";
diff --git a/backend/src/ee/services/project-events/project-events-service.ts b/backend/src/ee/services/project-events/project-events-service.ts
new file mode 100644
index 0000000000..6938ac5757
--- /dev/null
+++ b/backend/src/ee/services/project-events/project-events-service.ts
@@ -0,0 +1,47 @@
+import { logger } from "@app/lib/logger";
+
+import { EventBusServiceEvents, TEventBusService } from "../event-bus";
+import { TProjectEventPayload, TProjectEventSubscriber, TProjectEventUnsubscribe } from "./project-events-types";
+
+type TProjectEventsServiceFactoryDep = {
+ eventBus: TEventBusService;
+};
+
+export const projectEventsServiceFactory = ({ eventBus }: TProjectEventsServiceFactoryDep) => {
+ /**
+ * Publish a secret mutation event via the event bus
+ * Events are broadcast to all containers via Redis
+ * Payload contains projectId - subscribers filter as needed
+ */
+ const publishSecretMutation = async (payload: TProjectEventPayload): Promise<void> => {
+ await eventBus.publish(EventBusServiceEvents.SecretMutation, payload);
+ };
+
+ /**
+ * Subscribe to secret mutation events from the event bus
+ * Subscriber is responsible for filtering by projectId if needed
+ * @returns Unsubscribe function
+ */
+ const subscribeToSecretMutation = (callback: TProjectEventSubscriber): TProjectEventUnsubscribe => {
+ return eventBus.subscribe(EventBusServiceEvents.SecretMutation, (event) => {
+ try {
+ const payload = event.payload as TProjectEventPayload;
+ const result = callback(payload);
+ if (result instanceof Promise) {
+ result.catch((error) => {
+ logger.error(error, "Error in project event subscriber");
+ });
+ }
+ } catch (error) {
+ logger.error(error, "Error in project event subscriber");
+ }
+ });
+ };
+
+ return {
+ publishSecretMutation,
+ subscribeToSecretMutation
+ };
+};
+
+export type TProjectEventsService = ReturnType<typeof projectEventsServiceFactory>;
diff --git a/backend/src/ee/services/project-events/project-events-sse-service.ts b/backend/src/ee/services/project-events/project-events-sse-service.ts
new file mode 100644
index 0000000000..155fec916e
--- /dev/null
+++ b/backend/src/ee/services/project-events/project-events-sse-service.ts
@@ -0,0 +1,332 @@
+import { Readable } from "node:stream";
+
+import { ForbiddenError, subject } from "@casl/ability";
+import { nanoid } from "nanoid";
+
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ProjectPermissionSecretEventActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+import { BadRequestError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+
+import { TLicenseServiceFactory } from "../license/license-service";
+import { TProjectEventsService } from "./project-events-service";
+import {
+ ISSERegisterEntry,
+ ISSESubscribeOpts,
+ TSSEClient,
+ TSSEEvent,
+ TSSEPermissionCache
+} from "./project-events-sse-types";
+import { ProjectEvents, TProjectEventPayload } from "./project-events-types";
+
+const PERMISSION_REFRESH_INTERVAL = 60 * 1000; // 60 seconds
+const HEARTBEAT_INTERVAL = 15 * 1000; // 15 seconds
+
+// Map mutation type to permission action
+const MutationTypeToAction: Record<ProjectEvents, ProjectPermissionSecretEventActions> = {
+ [ProjectEvents.SecretCreate]: ProjectPermissionSecretEventActions.SubscribeCreated,
+ [ProjectEvents.SecretUpdate]: ProjectPermissionSecretEventActions.SubscribeUpdated,
+ [ProjectEvents.SecretDelete]: ProjectPermissionSecretEventActions.SubscribeDeleted,
+ [ProjectEvents.SecretImportMutation]: ProjectPermissionSecretEventActions.SubscribeImportMutations
+};
+
+const getBusEventToSubject = (type: ProjectEvents) => {
+ if (
+ [
+ ProjectEvents.SecretCreate,
+ ProjectEvents.SecretUpdate,
+ ProjectEvents.SecretDelete,
+ ProjectEvents.SecretImportMutation
+ ].includes(type)
+ ) {
+ return ProjectPermissionSub.SecretEvents;
+ }
+ throw new Error("Unknown project event type");
+};
+
+// SSE event serialization
+function serializeSSEEvent(event: TSSEEvent): string {
+ let payload = "";
+ if (event.id) payload += `id: ${event.id}\n`;
+ if (event.type) payload += `event: ${event.type}\n`;
+ if (event.data) payload += `data: ${JSON.stringify(event.data)}\n`;
+ return `${payload}\n`;
+}
+
+// SSE Headers
+export const getSSEHeaders = () =>
+ ({
+ "Cache-Control": "no-cache",
+ "Content-Type": "text/event-stream",
+ Connection: "keep-alive",
+ "X-Accel-Buffering": "no"
+ }) as const;
+
+type TProjectEventsSSEServiceFactoryDep = {
+ projectEventsService: TProjectEventsService;
+ permissionService: TPermissionServiceFactory;
+ licenseService: TLicenseServiceFactory;
+};
+
+export const projectEventsSSEServiceFactory = ({
+ projectEventsService,
+ permissionService,
+ licenseService
+}: TProjectEventsSSEServiceFactoryDep) => {
+ // Map: clientId -> { client, opts, permissionCache }
+ const clients = new Map<
+ string,
+ {
+ client: TSSEClient;
+ opts: ISSESubscribeOpts;
+ permissionCache: TSSEPermissionCache;
+ send: (event: TSSEEvent) => void;
+ }
+ >();
+
+ // Heartbeat interval to keep connections alive
+ const heartbeatInterval = setInterval(() => {
+ for (const [, { client }] of clients) {
+ if (!client.stream.closed) {
+ client.ping();
+ }
+ }
+ }, HEARTBEAT_INTERVAL);
+
+ /**
+ * Fetch fresh permission from permission service
+ */
+ const fetchPermission = async (opts: ISSESubscribeOpts): Promise<TSSEPermissionCache> => {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: opts.actor,
+ actorId: opts.actorId,
+ projectId: opts.projectId,
+ actorAuthMethod: opts.actorAuthMethod,
+ actorOrgId: opts.actorOrgId,
+ actionProjectType: opts.actionProjectType
+ });
+
+ return {
+ permission,
+ fetchedAt: Date.now()
+ };
+ };
+
+ /**
+ * Validate that user has permission for all registered events
+ * Throws ForbiddenError if any registration is not permitted
+ */
+ const validateRegisteredPermissions = (permissionCache: TSSEPermissionCache, register: ISSERegisterEntry[]): void => {
+ for (const reg of register) {
+ const permissionSubject = getBusEventToSubject(reg.event);
+ const action = MutationTypeToAction[reg.event];
+
+ // Use registration's conditions for permission check
+ const subjectFields = {
+ environment: reg.conditions?.environmentSlug ?? "",
+ secretPath: reg.conditions?.secretPath ?? "/"
+ };
+
+ ForbiddenError.from(permissionCache.permission).throwUnlessCan(
+ // @ts-expect-error - permissionSubject is narrowed by getBusEventToSubject but TS doesn't infer it
+ action,
+ subject(permissionSubject, subjectFields)
+ );
+ }
+ };
+
+ /**
+ * Refresh permission for a client
+ * Also re-validates registered permissions - closes connection if revoked
+ */
+ const refreshPermission = async (clientId: string): Promise<void> => {
+ const entry = clients.get(clientId);
+ if (!entry) return;
+
+ try {
+ const newPermissionCache = await fetchPermission(entry.opts);
+
+ // Re-validate registered permissions with refreshed permissions
+ validateRegisteredPermissions(newPermissionCache, entry.opts.register);
+
+ entry.permissionCache = newPermissionCache;
+ } catch (error) {
+ logger.error(error, "Failed to refresh SSE client permission or permission revoked");
+ entry.send({ type: "error", data: { message: "Permission denied or refresh failed" } });
+ entry.client.close();
+ clients.delete(clientId);
+ }
+ };
+
+ // Permission refresh interval
+ const refreshInterval = setInterval(() => {
+ for (const [clientId, entry] of clients) {
+ if (!entry.client.stream.closed) {
+ void refreshPermission(clientId);
+ }
+ }
+ }, PERMISSION_REFRESH_INTERVAL);
+
+ /**
+ * Check if client has permission to receive this event based on registrations
+ * This is called for each incoming event - returns boolean, does not throw
+ */
+ const canReceiveEvent = (
+ permissionCache: TSSEPermissionCache,
+ payload: TProjectEventPayload,
+ register: ISSERegisterEntry[]
+ ): boolean => {
+ // Find matching registration for this event type
+ const matchingRegistrations = register.filter((r) => r.event === payload.type);
+ if (matchingRegistrations.length === 0) {
+ return false;
+ }
+
+ return matchingRegistrations.some((reg) => {
+ // If conditions specified, check they match
+ if (reg.conditions?.environmentSlug && payload.environment !== reg.conditions.environmentSlug) {
+ return false;
+ }
+ if (reg.conditions?.secretPath && !payload.secretPath.startsWith(reg.conditions.secretPath)) {
+ return false;
+ }
+
+ // Check permission using CASL against the actual event's environment/path
+ const action = MutationTypeToAction[payload.type];
+ const subjectFields = {
+ environment: payload.environment,
+ secretPath: payload.secretPath
+ };
+
+ return permissionCache.permission.can(action, subject(ProjectPermissionSub.SecretEvents, subjectFields));
+ });
+ };
+
+ /**
+ * Subscribe a client to receive secret mutation events
+ * Returns the SSE client for the router to use
+ */
+ const subscribe = async (opts: ISSESubscribeOpts): Promise<TSSEClient> => {
+ const id = `sse-${nanoid()}`;
+
+ // Fetch initial permission (throws if not authorized)
+ const permissionCache = await fetchPermission(opts);
+
+ // Validate user has permission for all registered events (throws ForbiddenError if not)
+ validateRegisteredPermissions(permissionCache, opts.register);
+
+ const plan = await licenseService.getPlan(opts.actorOrgId);
+ if (!plan.eventSubscriptions) {
+ throw new BadRequestError({
+ message: "Event subscriptions are not available on your current plan. Please upgrade to access this feature."
+ });
+ }
+
+ // Create the readable stream
+ const stream = new Readable({ objectMode: true });
+ // eslint-disable-next-line no-underscore-dangle
+ stream._read = () => {}; // Manual push mode
+
+ const send = (event: TSSEEvent) => {
+ const chunk = serializeSSEEvent(event);
+ if (!stream.push(chunk)) {
+ logger.debug("SSE backpressure detected: event dropped");
+ }
+ };
+
+ const ping = () => {
+ send({ type: "ping" });
+ };
+
+ const close = () => {
+ if (stream.closed) return;
+ stream.push(null);
+ stream.destroy();
+ };
+
+ stream.on("error", (error: Error) => {
+ logger.error(error, "SSE stream error");
+ stream.destroy(error);
+ });
+
+ const client: TSSEClient = {
+ id,
+ stream,
+ projectId: opts.projectId,
+ actorId: opts.actorId,
+ ping,
+ close
+ };
+
+ // Store client with its opts and permission cache
+ const entry = { client, opts, permissionCache, send };
+ clients.set(id, entry);
+
+ // Subscribe to secret mutations and filter for this client
+ const unsubscribe = projectEventsService.subscribeToSecretMutation((payload) => {
+ const currentEntry = clients.get(id);
+ if (!currentEntry) return;
+
+ // Filter by projectId first
+ if (payload.projectId !== opts.projectId) return;
+
+ // Check permission and registered events/conditions
+ if (!canReceiveEvent(currentEntry.permissionCache, payload, opts.register)) {
+ return;
+ }
+
+ // Send event to client
+ send({
+ id: Date.now().toString(),
+ type: `secret.${payload.type}`,
+ data: payload
+ });
+ });
+
+ // Clean up on stream close
+ stream.on("close", () => {
+ unsubscribe();
+ clients.delete(id);
+ });
+
+ return client;
+ };
+
+ /**
+ * Close all connections and clean up
+ */
+ const close = () => {
+ clearInterval(heartbeatInterval);
+ clearInterval(refreshInterval);
+
+ for (const [, { client }] of clients) {
+ client.close();
+ }
+ clients.clear();
+ };
+
+ /**
+ * Get count of active connections for a project/actor
+ */
+ const getActiveConnectionsCount = (projectId: string, actorId: string): number => {
+ let count = 0;
+ for (const [, { client }] of clients) {
+ if (client.projectId === projectId && client.actorId === actorId) {
+ count += 1;
+ }
+ }
+ return count;
+ };
+
+ return {
+ subscribe,
+ close,
+ getActiveConnectionsCount,
+ getSSEHeaders
+ };
+};
+
+export type TProjectEventsSSEService = ReturnType<typeof projectEventsSSEServiceFactory>;
diff --git a/backend/src/ee/services/project-events/project-events-sse-types.ts b/backend/src/ee/services/project-events/project-events-sse-types.ts
new file mode 100644
index 0000000000..2dd8f82e88
--- /dev/null
+++ b/backend/src/ee/services/project-events/project-events-sse-types.ts
@@ -0,0 +1,54 @@
+import { Readable } from "node:stream";
+
+import { MongoAbility } from "@casl/ability";
+import { MongoQuery } from "@ucast/mongo2js";
+
+import { ActionProjectType } from "@app/db/schemas";
+import { ProjectPermissionSet } from "@app/ee/services/permission/project-permission";
+import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
+
+import { ProjectEvents, TProjectEventPayload } from "./project-events-types";
+
+// Cached permission info
+export type TSSEPermissionCache = {
+ permission: MongoAbility<ProjectPermissionSet, MongoQuery>;
+ fetchedAt: number;
+};
+
+// Registration entry for event subscription
+export interface ISSERegisterEntry {
+ event: ProjectEvents;
+ conditions?: {
+ environmentSlug?: string;
+ secretPath?: string;
+ };
+}
+
+// Options for subscribing to SSE events
+export interface ISSESubscribeOpts {
+ projectId: string;
+ actor: ActorType;
+ actorId: string;
+ actorAuthMethod: ActorAuthMethod;
+ actorOrgId: string;
+ actionProjectType: ActionProjectType;
+ // Event registrations with optional conditions
+ register: ISSERegisterEntry[];
+}
+
+// SSE Client interface
+export type TSSEClient = {
+ id: string;
+ stream: Readable;
+ projectId: string;
+ actorId: string;
+ ping: () => void;
+ close: () => void;
+};
+
+// SSE Event format
+export type TSSEEvent = {
+ id?: string;
+ type: string;
+ data?: TProjectEventPayload | object;
+};
diff --git a/backend/src/ee/services/project-events/project-events-types.ts b/backend/src/ee/services/project-events/project-events-types.ts
new file mode 100644
index 0000000000..fa5c875f62
--- /dev/null
+++ b/backend/src/ee/services/project-events/project-events-types.ts
@@ -0,0 +1,62 @@
+import { z } from "zod";
+
+// Mutation types for discriminated union
+export enum ProjectEvents {
+ SecretCreate = "secret:create",
+ SecretUpdate = "secret:update",
+ SecretDelete = "secret:delete",
+ SecretImportMutation = "secret:import-mutation"
+}
+
+// Base fields for all secret mutations
+interface SecretMutationBase {
+ projectId: string;
+ secretPath: string;
+ environment: string;
+}
+
+// Payload for created - includes secretKey
+interface SecretCreatedPayload extends SecretMutationBase {
+ type: ProjectEvents.SecretCreate;
+ secretKey: string;
+}
+
+// Payload for updated - includes secretKey
+interface SecretUpdatedPayload extends SecretMutationBase {
+ type: ProjectEvents.SecretUpdate;
+ secretKey: string;
+}
+
+// Payload for deleted - includes secretKey
+interface SecretDeletedPayload extends SecretMutationBase {
+ type: ProjectEvents.SecretDelete;
+ secretKey: string;
+}
+
+// Payload for import mutation - NO secretKey
+interface SecretImportMutationPayload extends SecretMutationBase {
+ type: ProjectEvents.SecretImportMutation;
+}
+
+// Discriminated union of all mutation payloads
+export type TProjectEventPayload =
+ | SecretCreatedPayload
+ | SecretUpdatedPayload
+ | SecretDeletedPayload
+ | SecretImportMutationPayload;
+
+// Subscriber callback type
+export type TProjectEventSubscriber = (payload: TProjectEventPayload) => void | Promise<void>;
+
+// Unsubscribe function type
+export type TProjectEventUnsubscribe = () => void;
+
+export const ProjectEventRegisterSchema = z.object({
+ event: z.nativeEnum(ProjectEvents),
+ conditions: z
+ .object({
+ secretPath: z.string().optional().default("/"),
+ environmentSlug: z.string()
+ })
+ .optional()
+});
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 8d4a18aa5c..b5c83c2fd8 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -50,6 +50,7 @@ import { dynamicSecretLeaseServiceFactory } from "@app/ee/services/dynamic-secre
import { eventBusFactory } from "@app/ee/services/event/event-bus-service";
import { sseServiceFactory } from "@app/ee/services/event/event-sse-service";
import { eventBusServiceFactory } from "@app/ee/services/event-bus";
+import { projectEventsServiceFactory, projectEventsSSEServiceFactory } from "@app/ee/services/project-events";
import { externalKmsDALFactory } from "@app/ee/services/external-kms/external-kms-dal";
import { externalKmsServiceFactory } from "@app/ee/services/external-kms/external-kms-service";
import { gatewayDALFactory } from "@app/ee/services/gateway/gateway-dal";
@@ -628,6 +629,9 @@ export const registerRoutes = async (
// New event bus for inter-container communication
const internalEventBus = eventBusServiceFactory({ redis: server.redis });
+ // Project events service (publishes via event bus for inter-container communication)
+ const projectEventsService = projectEventsServiceFactory({ eventBus: internalEventBus });
+
const permissionService = permissionServiceFactory({
permissionDAL,
serviceTokenDAL,
@@ -652,6 +656,13 @@ export const registerRoutes = async (
envConfig
});
+ // Project events SSE service (for clients to subscribe to secret mutation events)
+ const projectEventsSSEService = projectEventsSSEServiceFactory({
+ projectEventsService,
+ permissionService,
+ licenseService
+ });
+
const tokenService = tokenServiceFactory({ tokenDAL: authTokenDAL, userDAL, membershipUserDAL, orgDAL });
const membershipUserService = membershipUserServiceFactory({
@@ -2802,6 +2813,8 @@ export const registerRoutes = async (
reminder: reminderService,
bus: eventBusService,
eventBus: internalEventBus,
+ projectEvents: projectEventsService,
+ projectEventsSSE: projectEventsSSEService,
sse: sseService,
notification: notificationService,
pamFolder: pamFolderService,
diff --git a/backend/src/server/routes/v1/event-router.ts b/backend/src/server/routes/v1/event-router.ts
index 53ce47b341..2549b1a765 100644
--- a/backend/src/server/routes/v1/event-router.ts
+++ b/backend/src/server/routes/v1/event-router.ts
@@ -1,14 +1,11 @@
/* eslint-disable @typescript-eslint/no-floating-promises */
-import { subject } from "@casl/ability";
import { pipeline } from "stream/promises";
import { z } from "zod";
-import { ActionProjectType, ProjectType } from "@app/db/schemas";
-import { getServerSentEventsHeaders } from "@app/ee/services/event/event-sse-stream";
-import { EventRegisterSchema, Mappings } from "@app/ee/services/event/types";
-import { ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
+import { ActionProjectType } from "@app/db/schemas";
+import { getSSEHeaders } from "@app/ee/services/project-events";
+import { ProjectEventRegisterSchema } from "@app/ee/services/project-events/project-events-types";
import { ApiDocsTags, EventSubscriptions } from "@app/lib/api-docs";
-import { BadRequestError, ForbiddenRequestError, RateLimitError } from "@app/lib/errors";
import { readLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
@@ -27,98 +24,25 @@ export const registerEventRouter = async (server: FastifyZodProvider) => {
description: "Subscribe to project events",
body: z.object({
projectId: z.string().trim().describe(EventSubscriptions.SUBSCRIBE_PROJECT_EVENTS.projectId),
- register: z.array(EventRegisterSchema).min(1).max(10)
+ register: z.array(ProjectEventRegisterSchema).min(1).max(10)
}),
produces: ["text/event-stream"]
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req, reply) => {
- try {
- const { sse, permission, identityAccessToken, authToken, license } = req.server.services;
-
- const plan = await license.getPlan(req.auth.orgId);
-
- if (!plan.eventSubscriptions) {
- throw new BadRequestError({
- message:
- "Failed to use event subscriptions due to plan restriction. Upgrade plan to access enterprise event subscriptions."
- });
- }
-
- const count = await sse.getActiveConnectionsCount(req.body.projectId, req.permission.id);
-
- if (count >= 5) {
- throw new RateLimitError({
- message: `Too many active connections for project ${req.body.projectId}. Please close some connections before opening a new one.`
- });
- }
-
- const client = await sse.subscribe({
- type: ProjectType.SecretManager,
- registered: req.body.register,
- async getAuthInfo() {
- const ability = await permission.getProjectPermission({
- actor: req.auth.actor,
- projectId: req.body.projectId,
- actionProjectType: ActionProjectType.Any,
- actorAuthMethod: req.auth.authMethod,
- actorId: req.permission.id,
- actorOrgId: req.permission.orgId
- });
-
- return { permission: ability.permission, actorId: req.permission.id, projectId: req.body.projectId };
- },
- async onAuthRefresh(info) {
- switch (req.auth.authMode) {
- case AuthMode.JWT:
- await authToken.fnValidateJwtIdentity(req.auth.token);
- break;
- case AuthMode.IDENTITY_ACCESS_TOKEN:
- await identityAccessToken.fnValidateIdentityAccessToken(req.auth.token, req.realIp);
- break;
- default:
- throw new Error("Unsupported authentication method");
- }
-
- req.body.register.forEach((r) => {
- const fields = {
- environment: r.conditions?.environmentSlug ?? "",
- secretPath: r.conditions?.secretPath ?? "/"
- };
-
- const action = Mappings.BusEventToAction(r.event);
-
- const allowed = info.permission.can(action, subject(ProjectPermissionSub.SecretEvents, fields));
-
- if (!allowed) {
- throw new ForbiddenRequestError({
- name: "PermissionDenied",
- message: `You are not allowed to subscribe on ${ProjectPermissionSub.SecretEvents}`,
- details: {
- action,
- environmentSlug: fields.environment,
- secretPath: fields.secretPath
- }
- });
- }
- });
- }
- });
-
- // Switches to manual response and enable SSE streaming
- reply.hijack();
- reply.raw.writeHead(200, getServerSentEventsHeaders()).flushHeaders();
- reply.raw.on("close", client.abort);
-
- await pipeline(client.stream, reply.raw, { signal: client.signal });
- } catch (error) {
- if (error instanceof Error && error.name === "AbortError") {
- // If the stream is aborted, we don't need to do anything
- return;
- }
-
- throw error;
- }
+ const client = await server.services.projectEventsSSE.subscribe({
+ projectId: req.body.projectId,
+ actor: req.auth.actor,
+ actorId: req.permission.id,
+ actorAuthMethod: req.auth.authMethod,
+ actorOrgId: req.permission.orgId,
+ actionProjectType: ActionProjectType.Any,
+ register: req.body.register
+ });
+
+ reply.hijack();
+ reply.raw.writeHead(200, getSSEHeaders()).flushHeaders();
+ await pipeline(client.stream, reply.raw);
}
});
};