Skip to content

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

feat: addressed review comments

=47f17634a70e
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 138b1974af..2a3bb5f232 100644
--- a/backend/src/ee/services/event-bus/event-bus-service.ts
+++ b/backend/src/ee/services/event-bus/event-bus-service.ts
@@ -76,14 +76,6 @@ export const eventBusServiceFactory = ({ redis }: TEventBusServiceFactoryDep) =>
return memoryBus.subscribe(type, callback);
};
- /**
- * Subscribe to ALL events (useful for debugging/logging)
- * @returns Unsubscribe function
- */
- const subscribeAll = (callback: TEventBusSubscriber): TEventBusUnsubscribe => {
- return memoryBus.subscribeAll(callback);
- };
-
/**
* Close the event bus and cleanup resources
*/
@@ -97,7 +89,6 @@ export const eventBusServiceFactory = ({ redis }: TEventBusServiceFactoryDep) =>
init,
publish,
subscribe,
- subscribeAll,
close
};
};
diff --git a/backend/src/ee/services/event-bus/index.ts b/backend/src/ee/services/event-bus/index.ts
deleted file mode 100644
index e2e14f87d8..0000000000
--- a/backend/src/ee/services/event-bus/index.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-export { eventBusServiceFactory, TEventBusService } from "./event-bus-service";
-export {
- EventBusServiceEvents,
- EventBusTopicName,
- TEventBusEvent,
- TEventBusSubscriber,
- TEventBusUnsubscribe
-} from "./event-bus-types";
diff --git a/backend/src/ee/services/event-bus/memory-bus.ts b/backend/src/ee/services/event-bus/memory-bus.ts
index c363ce49d1..c6109cdd80 100644
--- a/backend/src/ee/services/event-bus/memory-bus.ts
+++ b/backend/src/ee/services/event-bus/memory-bus.ts
@@ -4,8 +4,6 @@ import { logger } from "@app/lib/logger";
import { EventBusServiceEvents, TEventBusEvent, TEventBusSubscriber, TEventBusUnsubscribe } from "./event-bus-types";
-const ALL_EVENTS_CHANNEL = "__all__";
-
export const createMemoryBus = () => {
const emitter = new EventEmitter();
// Increase max listeners to avoid warnings with many subscribers
@@ -17,7 +15,6 @@ export const createMemoryBus = () => {
*/
const emit = (event: TEventBusEvent): void => {
emitter.emit(event.type, event);
- emitter.emit(ALL_EVENTS_CHANNEL, event);
};
/**
@@ -46,31 +43,6 @@ export const createMemoryBus = () => {
};
};
- /**
- * Subscribe to ALL events (useful for debugging/logging)
- * @returns Unsubscribe function
- */
- const subscribeAll = (callback: TEventBusSubscriber): TEventBusUnsubscribe => {
- const wrappedCallback = (event: TEventBusEvent) => {
- try {
- const result = callback(event);
- if (result instanceof Promise) {
- result.catch((error) => {
- logger.error(error, "Error in event bus global subscriber");
- });
- }
- } catch (error) {
- logger.error(error, "Error in event bus global subscriber");
- }
- };
-
- emitter.on(ALL_EVENTS_CHANNEL, wrappedCallback);
-
- return () => {
- emitter.off(ALL_EVENTS_CHANNEL, wrappedCallback);
- };
- };
-
/**
* Remove all listeners from the memory bus
*/
@@ -81,7 +53,6 @@ export const createMemoryBus = () => {
return {
emit,
subscribe,
- subscribeAll,
removeAllListeners
};
};
diff --git a/backend/src/ee/services/project-events/project-events-service.ts b/backend/src/ee/services/project-events/project-events-service.ts
index 27cc591931..16c1b8c87b 100644
--- a/backend/src/ee/services/project-events/project-events-service.ts
+++ b/backend/src/ee/services/project-events/project-events-service.ts
@@ -1,6 +1,7 @@
import { logger } from "@app/lib/logger";
-import { EventBusServiceEvents, TEventBusService } from "../event-bus";
+import { TEventBusService } from "../event-bus/event-bus-service";
+import { EventBusServiceEvents } from "../event-bus/event-bus-types";
import { TProjectEventPayload, TProjectEventSubscriber, TProjectEventUnsubscribe } from "./project-events-types";
type TProjectEventsServiceFactoryDep = {
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
index 0225799b31..91e48e1284 100644
--- a/backend/src/ee/services/project-events/project-events-sse-service.ts
+++ b/backend/src/ee/services/project-events/project-events-sse-service.ts
@@ -2,6 +2,7 @@ import { Readable } from "node:stream";
import { ForbiddenError, subject } from "@casl/ability";
import { nanoid } from "nanoid";
+import picomatch from "picomatch";
import { ProjectType } from "@app/db/schemas";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
@@ -35,7 +36,7 @@ const MutationTypeToAction: Record<ProjectEvents, ProjectPermissionSecretEventAc
[ProjectEvents.SecretCreate]: ProjectPermissionSecretEventActions.SubscribeCreated,
[ProjectEvents.SecretUpdate]: ProjectPermissionSecretEventActions.SubscribeUpdated,
[ProjectEvents.SecretDelete]: ProjectPermissionSecretEventActions.SubscribeDeleted,
- [ProjectEvents.SecretImportMutation]: ProjectPermissionSecretEventActions.SubscribeImportMutations
+ [ProjectEvents.SecretImportMutations]: ProjectPermissionSecretEventActions.SubscribeImportMutations
};
const getBusEventToSubject = (type: ProjectEvents) => {
@@ -44,7 +45,7 @@ const getBusEventToSubject = (type: ProjectEvents) => {
ProjectEvents.SecretCreate,
ProjectEvents.SecretUpdate,
ProjectEvents.SecretDelete,
- ProjectEvents.SecretImportMutation
+ ProjectEvents.SecretImportMutations
].includes(type)
) {
return ProjectPermissionSub.SecretEvents;
@@ -95,25 +96,24 @@ export const projectEventsSSEServiceFactory = ({
>();
// Connection management functions for rate limiting
- const registerConnection = async (projectId: string, connectionId: string): Promise<void> => {
+ const $registerConnection = async (projectId: string, connectionId: string): Promise<void> => {
const set = KeyStorePrefixes.ProjectSSEConnectionsSet(projectId);
const key = KeyStorePrefixes.ProjectSSEConnection(projectId, connectionId);
- await Promise.all([
- keyStore.listPush(set, connectionId),
- keyStore.setItemWithExpiry(key, CONNECTION_TTL_SECONDS, "1")
- ]);
+ await keyStore.setItemWithExpiry(key, CONNECTION_TTL_SECONDS, "1");
+ await keyStore.listPush(set, connectionId);
};
- const refreshConnection = async (projectId: string, connectionId: string): Promise<void> => {
+ const $refreshConnection = async (projectId: string, connectionId: string): Promise<void> => {
const key = KeyStorePrefixes.ProjectSSEConnection(projectId, connectionId);
await keyStore.setItemWithExpiry(key, CONNECTION_TTL_SECONDS, "1");
};
- const removeConnection = async (projectId: string, connectionId: string): Promise<void> => {
+ const $removeConnection = async (projectId: string, connectionId: string): Promise<void> => {
try {
const set = KeyStorePrefixes.ProjectSSEConnectionsSet(projectId);
const key = KeyStorePrefixes.ProjectSSEConnection(projectId, connectionId);
- await Promise.all([keyStore.listRemove(set, 0, connectionId), keyStore.deleteItem(key)]);
+ await keyStore.listRemove(set, 0, connectionId);
+ await keyStore.deleteItem(key);
} catch (error) {
logger.error(error, "Failed to remove SSE connection from keystore");
}
@@ -133,8 +133,8 @@ export const projectEventsSSEServiceFactory = ({
// Clean up stale connections (crashed servers - expired TTL keys)
const staleConnections = connections.filter((_, i) => values[i] === null);
- if (staleConnections.length > 0) {
- await Promise.all(staleConnections.map((c) => keyStore.listRemove(set, 0, c)));
+ for await (const staleConnection of staleConnections) {
+ await keyStore.listRemove(set, 0, staleConnection);
}
return connections.length - staleConnections.length;
@@ -144,7 +144,7 @@ export const projectEventsSSEServiceFactory = ({
const heartbeatInterval = setInterval(() => {
for (const [clientId, { client, opts }] of clients) {
if (!client.stream.closed) {
- void refreshConnection(opts.projectId, clientId);
+ void $refreshConnection(opts.projectId, clientId);
}
}
}, HEARTBEAT_INTERVAL);
@@ -203,7 +203,7 @@ export const projectEventsSSEServiceFactory = ({
* Refresh permission for a client
* Also re-validates registered permissions - closes connection if revoked
*/
- const refreshPermission = async (clientId: string): Promise<void> => {
+ const $refreshPermission = async (clientId: string): Promise<void> => {
const entry = clients.get(clientId);
if (!entry) return;
@@ -226,7 +226,7 @@ export const projectEventsSSEServiceFactory = ({
const refreshInterval = setInterval(() => {
for (const [clientId, entry] of clients) {
if (!entry.client.stream.closed) {
- void refreshPermission(clientId);
+ void $refreshPermission(clientId);
}
}
}, PERMISSION_REFRESH_INTERVAL);
@@ -235,7 +235,7 @@ export const projectEventsSSEServiceFactory = ({
* 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 = (
+ const $canReceiveEvent = (
permissionCache: TSSEPermissionCache,
payload: TProjectEventPayload,
register: TSSERegisterEntry[]
@@ -251,7 +251,10 @@ export const projectEventsSSEServiceFactory = ({
if (reg.conditions?.environmentSlug && payload.environment !== reg.conditions.environmentSlug) {
return false;
}
- if (reg.conditions?.secretPath && !payload.secretPath.startsWith(reg.conditions.secretPath)) {
+ if (
+ reg.conditions?.secretPath &&
+ !picomatch.isMatch(payload.secretPath, reg.conditions.secretPath, { strictSlashes: false })
+ ) {
return false;
}
@@ -298,20 +301,18 @@ export const projectEventsSSEServiceFactory = ({
const activeCount = await getActiveConnectionsCountFromKeyStore(opts.projectId);
if (activeCount >= MAX_CONNECTIONS_PER_PROJECT) {
throw new RateLimitError({
- message: `Maximum SSE connections (${MAX_CONNECTIONS_PER_PROJECT}) reached for this project.`
+ message: `You have reached your maximum concurrent event subscriptions for this project. Your project supports ${MAX_CONNECTIONS_PER_PROJECT} concurrent event subscriptions.`
});
}
// Register connection in keystore
- await registerConnection(opts.projectId, id);
+ await $registerConnection(opts.projectId, id);
} finally {
await lock?.release();
}
// Create the readable stream
- const stream = new Readable({ objectMode: true });
- // eslint-disable-next-line no-underscore-dangle
- stream._read = () => {}; // Manual push mode
+ const stream = new Readable({ objectMode: true, read: () => {} });
const send = (event: TSSEEvent) => {
const chunk = serializeSSEEvent(event);
@@ -352,15 +353,15 @@ export const projectEventsSSEServiceFactory = ({
if (payload.projectId !== opts.projectId) return;
// Check permission and registered events/conditions
- if (!canReceiveEvent(currentEntry.permissionCache, payload, opts.register)) {
+ if (!$canReceiveEvent(currentEntry.permissionCache, payload, opts.register)) {
return;
}
const payloadFormattedData = {
- type: ProjectType.SecretManager,
+ projectType: ProjectType.SecretManager,
data: { eventType: payload.type, payload: {} }
};
- if (payload.type === ProjectEvents.SecretImportMutation) {
+ if (payload.type === ProjectEvents.SecretImportMutations) {
payloadFormattedData.data.payload = {
environment: payload.environment,
secretPath: payload.secretPath
@@ -373,7 +374,7 @@ export const projectEventsSSEServiceFactory = ({
payloadFormattedData.data.payload = payload.secretKeys.map((key) => ({
environment: payload.environment,
secretPath: payload.secretPath,
- secretKeys: key
+ secretKey: key
}));
}
@@ -392,7 +393,7 @@ export const projectEventsSSEServiceFactory = ({
cleaned = true;
unsubscribe();
clients.delete(id);
- void removeConnection(opts.projectId, id);
+ void $removeConnection(opts.projectId, id);
};
// Handle stream errors - ensure cleanup even if "close" doesn't fire
@@ -424,7 +425,7 @@ export const projectEventsSSEServiceFactory = ({
const cleanupPromises: Promise<void>[] = [];
for (const [clientId, { client, opts }] of clients) {
client.close();
- cleanupPromises.push(removeConnection(opts.projectId, clientId));
+ cleanupPromises.push($removeConnection(opts.projectId, clientId));
}
await Promise.all(cleanupPromises);
diff --git a/backend/src/ee/services/project-events/project-events-types.ts b/backend/src/ee/services/project-events/project-events-types.ts
index efd32c7557..f8e99c12bf 100644
--- a/backend/src/ee/services/project-events/project-events-types.ts
+++ b/backend/src/ee/services/project-events/project-events-types.ts
@@ -5,7 +5,7 @@ export enum ProjectEvents {
SecretCreate = "secret:create",
SecretUpdate = "secret:update",
SecretDelete = "secret:delete",
- SecretImportMutation = "secret:import-mutation"
+ SecretImportMutations = "secret:import-mutations"
}
// Base fields for all secret mutations
@@ -35,7 +35,7 @@ interface SecretDeletedPayload extends SecretMutationBase {
// Payload for import mutation - NO secretKey
interface SecretImportMutationPayload extends SecretMutationBase {
- type: ProjectEvents.SecretImportMutation;
+ type: ProjectEvents.SecretImportMutations;
}
// Discriminated union of all mutation payloads
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index f2216ceac7..0e5ffebc75 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -47,7 +47,7 @@ import { buildDynamicSecretProviders } from "@app/ee/services/dynamic-secret/pro
import { dynamicSecretLeaseDALFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-dal";
import { dynamicSecretLeaseQueueServiceFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue";
import { dynamicSecretLeaseServiceFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-service";
-import { eventBusServiceFactory } from "@app/ee/services/event-bus";
+import { eventBusServiceFactory } from "@app/ee/services/event-bus/event-bus-service";
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";
diff --git a/backend/src/services/secret-import/secret-import-service.ts b/backend/src/services/secret-import/secret-import-service.ts
index 2d9f5325aa..d257f2c56a 100644
--- a/backend/src/services/secret-import/secret-import-service.ts
+++ b/backend/src/services/secret-import/secret-import-service.ts
@@ -185,7 +185,7 @@ export const secretImportServiceFactory = ({
actor,
events: [
{
- type: ProjectEvents.SecretImportMutation,
+ type: ProjectEvents.SecretImportMutations,
projectId,
secretPath,
environment
@@ -368,7 +368,7 @@ export const secretImportServiceFactory = ({
actorId,
events: [
{
- type: ProjectEvents.SecretImportMutation,
+ type: ProjectEvents.SecretImportMutations,
projectId,
secretPath,
environment
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
index 7e4c1799e2..867caddd3d 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
@@ -2987,7 +2987,7 @@ export const secretV2BridgeServiceFactory = ({
actor,
events: [
{
- type: ProjectEvents.SecretImportMutation,
+ type: ProjectEvents.SecretImportMutations,
projectId,
secretPath: sourceFolder.path,
environment: sourceFolder.environment.slug
@@ -3007,7 +3007,7 @@ export const secretV2BridgeServiceFactory = ({
actor,
events: [
{
- type: ProjectEvents.SecretImportMutation,
+ type: ProjectEvents.SecretImportMutations,
projectId,
secretPath: sourceFolder.path,
environment: sourceFolder.environment.slug
diff --git a/backend/src/services/secret/secret-queue.ts b/backend/src/services/secret/secret-queue.ts
index 98973f9d33..3621a4d52e 100644
--- a/backend/src/services/secret/secret-queue.ts
+++ b/backend/src/services/secret/secret-queue.ts
@@ -770,7 +770,7 @@ export const secretQueueFactory = ({
excludeReplication: true,
events: [
{
- type: ProjectEvents.SecretImportMutation,
+ type: ProjectEvents.SecretImportMutations,
projectId,
secretPath: foldersGroupedById[folderId][0]?.path as string,
environment: foldersGroupedById[folderId][0]?.environmentSlug as string
@@ -831,7 +831,7 @@ export const secretQueueFactory = ({
excludeReplication: true,
events: [
{
- type: ProjectEvents.SecretImportMutation,
+ type: ProjectEvents.SecretImportMutations,
projectId,
secretPath: referencedFoldersGroupedById[folderId][0]?.path as string,
environment: referencedFoldersGroupedById[folderId][0]?.environmentSlug as string
diff --git a/docs/documentation/platform/event-subscriptions.mdx b/docs/documentation/platform/event-subscriptions.mdx
index c2006f21df..cb698b2b27 100644
--- a/docs/documentation/platform/event-subscriptions.mdx
+++ b/docs/documentation/platform/event-subscriptions.mdx
@@ -1,13 +1,12 @@
---
title: "Event Subscriptions"
-sidebarTitle: "Events"
+sidebarTitle: "Events Subscriptions"
description: "Subscribe to events in Infisical for real-time updates"
---
<Info>
- Event Subscriptions is a paid feature.
- - **Infisical Cloud:** Available under the **Enterprise Tier**.
- - **Self-Hosted:** Contact [[email protected]](mailto:[email protected]) to purchase an enterprise license.
+ Event Subscriptions is a paid feature that is available under the Enterprise license.
+ Please contact[[email protected]](mailto:[email protected]).
</Info>
Event Subscriptions allow you to receive real-time notifications when specific actions occur within your Infisical projects. You can subscribe to changes such as secret modifications, with support for additional resource types coming soon.
@@ -37,7 +36,7 @@ You can subscribe to the following event types:
| `secret:created` | Triggered when a new secret is created |
| `secret:updated` | Triggered when an existing secret is modified |
| `secret:deleted` | Triggered when a secret is removed |
-| `secret:import-mutation` | Triggered when a secret changes via an import |
+| `secret:import-mutations` | Triggered when a secret changes via an import |
## Permissions Setup
@@ -45,16 +44,6 @@ You can subscribe to the following event types:
To receive events, the machine identity must have the **Secret Events** permission with the appropriate actions enabled.
<Steps>
- <Step title="Copy your Project ID">
- ![Select Project](/images/platform/events/select-project.png)
-
- Navigate to **Project Settings** from the sidebar. In the Project name section, click **Copy Project ID**, or extract it from the URL:
-
- ```
- https://app.infisical.com/project/<your_project_id>/settings
- ```
- </Step>
-
<Step title="Open Project Roles">
![Project Detail](/images/platform/events/project-detail.png)
![Project Access](/images/platform/events/project-access.png)
@@ -115,13 +104,71 @@ To subscribe to events, make a request to the events endpoint with your project
| `register[].conditions.environmentSlug` | string | Filter by environment (e.g., `dev`, `staging`, `prod`) |
| `register[].conditions.secretPath` | string | Filter by secret path (e.g., `/api/keys`) |
-#### Response
The endpoint responds with `Content-Type: text/event-stream` to initiate an SSE connection.
-![Postman Subscription Response](/images/platform/events/postman-sse-response.png)
-
-Events are delivered as JSON payloads containing the event type and relevant metadata.
+```bash
+curl -N --location \
+ 'http://app.infisical.com/api/v1/events/subscribe/project-events' \
+ --header 'Content-Type: application/json' \
+ --header 'Authorization: Bearer <identity token>' \
+ --data '{
+ "projectId": "<project-id>",
+ "register": [
+ {
+ "event": "secret:create"
+ },
+ {
+ "event": "secret:update"
+ },
+ {
+ {
+ "event": "secret:import-mutations"
+ }
+ ]
+ }'
+```
+
+### Response Format
+
+<AccordionGroup>
+<Accordion title="Secret Changes">
+ - Event triggered on a secret change
+
+```json
+{
+ "projectType": "secret-manager",
+ "data": {
+ "eventType": "secret:<create,update,delete>",
+ "payload": [
+ {
+ "environment": "staging",
+ "secretPath": "/",
+ "secretKey": "TEST"
+ }
+ ]
+ }
+}
+```
+</Accordion>
+<Accordion title="Secret Import Mutation">
+ - Event triggered on a secret change in an import
+
+
+```json
+{
+ "projectType": "secret-manager",
+ "data": {
+ "eventType": "secret:import-mutations",
+ "payload": {
+ "environment": "staging",
+ "secretPath": "/"
+ }
+ }
+}
+```
+</Accordion>
+</AccordionGroup>
<Tip>
For complete API specifications and additional examples, see the [API Reference](/api-reference/endpoints/events).