Skip to content

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

feat(pam): support external object storage for session recordings

x032205d475e8c0ea8a
diff --git a/backend/package-lock.json b/backend/package-lock.json
index 6c0db7c375..ce9cbf52f6 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -20,6 +20,7 @@
"@aws-sdk/client-secrets-manager": "^3.504.0",
"@aws-sdk/client-ssm": "^3.1015.0",
"@aws-sdk/client-sts": "^3.600.0",
+ "@aws-sdk/s3-request-presigner": "^3.1020.0",
"@casl/ability": "^6.5.0",
"@clickhouse/client": "^1.17.0",
"@elastic/elasticsearch": "^9.1.1",
@@ -1623,6 +1624,25 @@
"node": ">=20.0.0"
}
},
+ "node_modules/@aws-sdk/s3-request-presigner": {
+ "version": "3.1020.0",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/s3-request-presigner/-/s3-request-presigner-3.1020.0.tgz",
+ "integrity": "sha512-13slasDcOC+Dfi252bcB6MCDavfLP11DsAAxROKr3fyvMTWOh/gFZJyE1a5sBhKAQElzMyqlOLvxPp8cyqvEQQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/signature-v4-multi-region": "^3.996.15",
+ "@aws-sdk/types": "^3.973.6",
+ "@aws-sdk/util-format-url": "^3.972.8",
+ "@smithy/middleware-endpoint": "^4.4.28",
+ "@smithy/protocol-http": "^5.3.12",
+ "@smithy/smithy-client": "^4.12.8",
+ "@smithy/types": "^4.13.1",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
"node_modules/@aws-sdk/signature-v4-multi-region": {
"version": "3.996.22",
"resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.22.tgz",
@@ -1699,6 +1719,21 @@
"node": ">=20.0.0"
}
},
+ "node_modules/@aws-sdk/util-format-url": {
+ "version": "3.972.10",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/util-format-url/-/util-format-url-3.972.10.tgz",
+ "integrity": "sha512-DEKiHNJVtNxdyTeQspzY+15Po/kHm6sF0Cs4HV9Q2+lplB63+DrvdeiSoOSdWEWAoO2RcY1veoXVDz2tWxWCgQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/types": "^3.973.8",
+ "@smithy/querystring-builder": "^4.2.14",
+ "@smithy/types": "^4.14.1",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
"node_modules/@aws-sdk/util-locate-window": {
"version": "3.465.0",
"resolved": "https://registry.npmjs.org/@aws-sdk/util-locate-window/-/util-locate-window-3.465.0.tgz",
diff --git a/backend/package.json b/backend/package.json
index 2ffc2095d7..2751a3f393 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -143,9 +143,11 @@
"@aws-sdk/client-iam": "^3.525.0",
"@aws-sdk/client-kms": "^3.609.0",
"@aws-sdk/client-route-53": "^3.810.0",
+ "@aws-sdk/client-s3": "^3.1020.0",
"@aws-sdk/client-secrets-manager": "^3.504.0",
"@aws-sdk/client-ssm": "^3.1015.0",
"@aws-sdk/client-sts": "^3.600.0",
+ "@aws-sdk/s3-request-presigner": "^3.1020.0",
"@casl/ability": "^6.5.0",
"@clickhouse/client": "^1.17.0",
"@elastic/elasticsearch": "^9.1.1",
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 81a5972858..fa270535b1 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -36,8 +36,10 @@ import { TPamAccountPolicyServiceFactory } from "@app/ee/services/pam-account-po
import { TPamDiscoverySourceServiceFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-service";
import { TPamDomainServiceFactory } from "@app/ee/services/pam-domain/pam-domain-service";
import { TPamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";
+import { TPamProjectRecordingConfigServiceFactory } from "@app/ee/services/pam-project-recording-config/pam-project-recording-config-service";
import { TPamResourceRotationRulesServiceFactory } from "@app/ee/services/pam-resource/pam-resource-rotation-rules-service";
import { TPamResourceServiceFactory } from "@app/ee/services/pam-resource/pam-resource-service";
+import { TPamSessionChunkServiceFactory } from "@app/ee/services/pam-session/pam-session-chunk-service";
import { TPamSessionServiceFactory } from "@app/ee/services/pam-session/pam-session-service";
import { TPamWebAccessServiceFactory } from "@app/ee/services/pam-web-access/pam-web-access-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
@@ -388,6 +390,8 @@ declare module "fastify" {
pamAccount: TPamAccountServiceFactory;
pamAccountPolicy: TPamAccountPolicyServiceFactory;
pamSession: TPamSessionServiceFactory;
+ pamSessionChunk: TPamSessionChunkServiceFactory;
+ pamProjectRecordingConfig: TPamProjectRecordingConfigServiceFactory;
pamWebAccess: TPamWebAccessServiceFactory;
pamDiscoverySource: TPamDiscoverySourceServiceFactory;
mfaSession: TMfaSessionServiceFactory;
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index 12fe095e2d..0156cf33e7 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -714,6 +714,11 @@ import {
} from "@app/db/schemas/pam-discovery-sources";
import { TPamDomains, TPamDomainsInsert, TPamDomainsUpdate } from "@app/db/schemas/pam-domains";
import { TPamFolders, TPamFoldersInsert, TPamFoldersUpdate } from "@app/db/schemas/pam-folders";
+import {
+ TPamProjectRecordingConfigs,
+ TPamProjectRecordingConfigsInsert,
+ TPamProjectRecordingConfigsUpdate
+} from "@app/db/schemas/pam-project-recording-configs";
import {
TPamResourceFavorites,
TPamResourceFavoritesInsert,
@@ -730,6 +735,11 @@ import {
TPamSessionEventBatchesInsert,
TPamSessionEventBatchesUpdate
} from "@app/db/schemas/pam-session-event-batches";
+import {
+ TPamSessionEventChunks,
+ TPamSessionEventChunksInsert,
+ TPamSessionEventChunksUpdate
+} from "@app/db/schemas/pam-session-event-chunks";
import { TPamSessions, TPamSessionsInsert, TPamSessionsUpdate } from "@app/db/schemas/pam-sessions";
import {
TProjectMicrosoftTeamsConfigs,
@@ -1622,6 +1632,16 @@ declare module "knex/types/tables" {
TPamSessionEventBatchesInsert,
TPamSessionEventBatchesUpdate
>;
+ [TableName.PamSessionEventChunk]: KnexOriginal.CompositeTableType<
+ TPamSessionEventChunks,
+ TPamSessionEventChunksInsert,
+ TPamSessionEventChunksUpdate
+ >;
+ [TableName.PamProjectRecordingConfig]: KnexOriginal.CompositeTableType<
+ TPamProjectRecordingConfigs,
+ TPamProjectRecordingConfigsInsert,
+ TPamProjectRecordingConfigsUpdate
+ >;
[TableName.PamDiscoverySource]: KnexOriginal.CompositeTableType<
TPamDiscoverySources,
TPamDiscoverySourcesInsert,
diff --git a/backend/src/db/migrations/20260429014404_pam-recording-config-and-chunks.ts b/backend/src/db/migrations/20260429014404_pam-recording-config-and-chunks.ts
new file mode 100644
index 0000000000..16f1ff7cfb
--- /dev/null
+++ b/backend/src/db/migrations/20260429014404_pam-recording-config-and-chunks.ts
@@ -0,0 +1,92 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
+
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasTable(TableName.PamProjectRecordingConfig))) {
+ await knex.schema.createTable(TableName.PamProjectRecordingConfig, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+
+ t.string("projectId").notNullable().unique(); // Unique ensures that there's only one config per project
+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
+
+ t.string("storageBackend").notNullable(); // e.g. 'aws-s3' or 'postgres'
+
+ t.uuid("connectionId").notNullable();
+ t.foreign("connectionId").references("id").inTable(TableName.AppConnection).onDelete("RESTRICT");
+
+ t.string("bucket").notNullable();
+ t.string("region").notNullable();
+ t.string("keyPrefix").nullable();
+
+ t.timestamps(true, true, true);
+ });
+
+ await createOnUpdateTrigger(knex, TableName.PamProjectRecordingConfig);
+ }
+
+ if (!(await knex.schema.hasTable(TableName.PamSessionEventChunk))) {
+ await knex.schema.createTable(TableName.PamSessionEventChunk, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+
+ t.uuid("sessionId").notNullable();
+ t.foreign("sessionId").references("id").inTable(TableName.PamSession).onDelete("CASCADE");
+ t.index("sessionId");
+
+ t.integer("chunkIndex").notNullable(); // Sequential starting from 0
+ t.bigInteger("startElapsedMs").notNullable(); // Elapsed MS from start of session
+ t.bigInteger("endElapsedMs").notNullable();
+
+ t.string("storageBackend").notNullable(); // e.g. 'aws-s3' or 'postgres'
+
+ // Postgres backend
+ t.binary("encryptedEventsBlob").nullable();
+
+ // External object storage backend
+ t.string("externalChunkObjectKey", 1024).nullable();
+ t.bigInteger("chunkSizeBytes").nullable();
+ t.string("externalKeyframeObjectKey", 1024).nullable(); // RDP Only
+ t.bigInteger("keyframeSizeBytes").nullable(); // RDP Only
+
+ // Integrity
+ t.binary("ciphertextSha256").notNullable();
+ t.bigInteger("ciphertextBytes").notNullable();
+ t.binary("iv").notNullable();
+
+ t.timestamps(true, true, true);
+
+ t.unique(["sessionId", "chunkIndex"]);
+ });
+
+ await createOnUpdateTrigger(knex, TableName.PamSessionEventChunk);
+ }
+
+ if (await knex.schema.hasTable(TableName.PamSession)) {
+ const hasEncryptedKey = await knex.schema.hasColumn(TableName.PamSession, "encryptedSessionKey");
+ const hasUploadTokenHash = await knex.schema.hasColumn(TableName.PamSession, "gatewayUploadTokenHash");
+
+ await knex.schema.alterTable(TableName.PamSession, (t) => {
+ if (!hasEncryptedKey) t.binary("encryptedSessionKey").nullable();
+ if (!hasUploadTokenHash) t.binary("gatewayUploadTokenHash").nullable();
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.PamSession)) {
+ const hasEncryptedKey = await knex.schema.hasColumn(TableName.PamSession, "encryptedSessionKey");
+ const hasUploadTokenHash = await knex.schema.hasColumn(TableName.PamSession, "gatewayUploadTokenHash");
+
+ await knex.schema.alterTable(TableName.PamSession, (t) => {
+ if (hasEncryptedKey) t.dropColumn("encryptedSessionKey");
+ if (hasUploadTokenHash) t.dropColumn("gatewayUploadTokenHash");
+ });
+ }
+
+ await dropOnUpdateTrigger(knex, TableName.PamSessionEventChunk);
+ await knex.schema.dropTableIfExists(TableName.PamSessionEventChunk);
+
+ await dropOnUpdateTrigger(knex, TableName.PamProjectRecordingConfig);
+ await knex.schema.dropTableIfExists(TableName.PamProjectRecordingConfig);
+}
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index 8ac69fffb7..c77e6dfa9e 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -124,10 +124,12 @@ export * from "./pam-discovery-source-runs";
export * from "./pam-discovery-sources";
export * from "./pam-domains";
export * from "./pam-folders";
+export * from "./pam-project-recording-configs";
export * from "./pam-resource-favorites";
export * from "./pam-resource-rotation-rules";
export * from "./pam-resources";
export * from "./pam-session-event-batches";
+export * from "./pam-session-event-chunks";
export * from "./pam-sessions";
export * from "./pki-acme-accounts";
export * from "./pki-acme-auths";
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index 5eec2ab6be..5ab22f2cea 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -229,6 +229,8 @@ export enum TableName {
PamAccount = "pam_accounts",
PamSession = "pam_sessions",
PamSessionEventBatch = "pam_session_event_batches",
+ PamSessionEventChunk = "pam_session_event_chunks",
+ PamProjectRecordingConfig = "pam_project_recording_configs",
PamDiscoverySource = "pam_discovery_sources",
PamDiscoverySourceRun = "pam_discovery_source_runs",
PamDiscoverySourceResource = "pam_discovery_source_resources",
diff --git a/backend/src/db/schemas/pam-project-recording-configs.ts b/backend/src/db/schemas/pam-project-recording-configs.ts
new file mode 100644
index 0000000000..5dfb86646f
--- /dev/null
+++ b/backend/src/db/schemas/pam-project-recording-configs.ts
@@ -0,0 +1,29 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const PamProjectRecordingConfigsSchema = z.object({
+ id: z.string().uuid(),
+ projectId: z.string(),
+ storageBackend: z.string(),
+ connectionId: z.string().uuid(),
+ bucket: z.string(),
+ region: z.string(),
+ keyPrefix: z.string().nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TPamProjectRecordingConfigs = z.infer<typeof PamProjectRecordingConfigsSchema>;
+export type TPamProjectRecordingConfigsInsert = Omit<
+ z.input<typeof PamProjectRecordingConfigsSchema>,
+ TImmutableDBKeys
+>;
+export type TPamProjectRecordingConfigsUpdate = Partial<
+ Omit<z.input<typeof PamProjectRecordingConfigsSchema>, TImmutableDBKeys>
+>;
diff --git a/backend/src/db/schemas/pam-session-event-chunks.ts b/backend/src/db/schemas/pam-session-event-chunks.ts
new file mode 100644
index 0000000000..6a702a3a2b
--- /dev/null
+++ b/backend/src/db/schemas/pam-session-event-chunks.ts
@@ -0,0 +1,33 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { zodBuffer } from "@app/lib/zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const PamSessionEventChunksSchema = z.object({
+ id: z.string().uuid(),
+ sessionId: z.string().uuid(),
+ chunkIndex: z.number(),
+ startElapsedMs: z.coerce.number(),
+ endElapsedMs: z.coerce.number(),
+ storageBackend: z.string(),
+ encryptedEventsBlob: zodBuffer.nullable().optional(),
+ externalChunkObjectKey: z.string().nullable().optional(),
+ chunkSizeBytes: z.coerce.number().nullable().optional(),
+ externalKeyframeObjectKey: z.string().nullable().optional(),
+ keyframeSizeBytes: z.coerce.number().nullable().optional(),
+ ciphertextSha256: zodBuffer,
+ ciphertextBytes: z.coerce.number(),
+ iv: zodBuffer,
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TPamSessionEventChunks = z.infer<typeof PamSessionEventChunksSchema>;
+export type TPamSessionEventChunksInsert = Omit<z.input<typeof PamSessionEventChunksSchema>, TImmutableDBKeys>;
+export type TPamSessionEventChunksUpdate = Partial<Omit<z.input<typeof PamSessionEventChunksSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/db/schemas/pam-sessions.ts b/backend/src/db/schemas/pam-sessions.ts
index a3fc0d4ad4..a107329a8e 100644
--- a/backend/src/db/schemas/pam-sessions.ts
+++ b/backend/src/db/schemas/pam-sessions.ts
@@ -33,7 +33,9 @@ export const PamSessionsSchema = z.object({
encryptedAiInsights: zodBuffer.nullable().optional(),
aiInsightsStatus: z.string().nullable().optional(),
aiInsightsError: z.string().nullable().optional(),
- reason: z.string().nullable().optional()
+ reason: z.string().nullable().optional(),
+ encryptedSessionKey: zodBuffer.nullable().optional(),
+ gatewayUploadTokenHash: zodBuffer.nullable().optional()
});
export type TPamSessions = z.infer<typeof PamSessionsSchema>;
diff --git a/backend/src/ee/routes/v1/index.ts b/backend/src/ee/routes/v1/index.ts
index 7ef91cddff..279d857ea8 100644
--- a/backend/src/ee/routes/v1/index.ts
+++ b/backend/src/ee/routes/v1/index.ts
@@ -41,9 +41,11 @@ import {
registerPamDomainRouter
} from "./pam-domain-routers";
import { registerPamFolderRouter } from "./pam-folder-router";
+import { registerPamRecordingConfigRouter } from "./pam-recording-config-router";
import { PAM_RESOURCE_REGISTER_ROUTER_MAP } from "./pam-resource-routers";
import { registerPamResourceRotationRulesRouter } from "./pam-resource-routers/pam-resource-rotation-rules-router";
import { registerPamResourceRouter } from "./pam-resource-routers/pam-resource-router";
+import { registerPamSessionChunkRouter } from "./pam-session-chunk-router";
import { registerPamSessionRouter } from "./pam-session-router";
import { registerPITRouter } from "./pit-router";
import { registerPkiAcmeRouter } from "./pki-acme-router";
@@ -208,7 +210,14 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {
await server.register(
async (pamRouter) => {
await pamRouter.register(registerPamFolderRouter, { prefix: "/folders" });
- await pamRouter.register(registerPamSessionRouter, { prefix: "/sessions" });
+ await pamRouter.register(
+ async (sessionRouter) => {
+ await sessionRouter.register(registerPamSessionRouter);
+ await sessionRouter.register(registerPamSessionChunkRouter);
+ },
+ { prefix: "/sessions" }
+ );
+ await pamRouter.register(registerPamRecordingConfigRouter);
await pamRouter.register(registerPamAccountPolicyRouter, { prefix: "/account-policies" });
await pamRouter.register(
async (pamDomainRouter) => {
diff --git a/backend/src/ee/routes/v1/pam-recording-config-router.ts b/backend/src/ee/routes/v1/pam-recording-config-router.ts
new file mode 100644
index 0000000000..842f9fe74d
--- /dev/null
+++ b/backend/src/ee/routes/v1/pam-recording-config-router.ts
@@ -0,0 +1,151 @@
+import RE2 from "re2";
+import { z } from "zod";
+
+import { PamProjectRecordingConfigsSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { PamRecordingStorageBackend } from "@app/ee/services/pam-session-recording-storage/pam-session-recording-storage-enums";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AWSRegion } from "@app/services/app-connection/app-connection-enums";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+const StorageBackendEnum = z.nativeEnum(PamRecordingStorageBackend);
+
+const SanitizedConfigSchema = PamProjectRecordingConfigsSchema.pick({
+ id: true,
+ projectId: true,
+ storageBackend: true,
+ connectionId: true,
+ bucket: true,
+ region: true,
+ keyPrefix: true,
+ createdAt: true,
+ updatedAt: true
+});
+
+const UpsertBodySchema = z.object({
+ storageBackend: StorageBackendEnum,
+ connectionId: z.string().uuid(),
+ bucket: z.string().trim().min(1).max(255),
+ region: z.nativeEnum(AWSRegion),
+ keyPrefix: z
+ .string()
+ .trim()
+ .max(512)
+ .regex(
+ new RE2(/^[a-zA-Z0-9\-_/]+$/),
+ "Key prefix may only contain letters, numbers, hyphens, underscores, and slashes"
+ )
+ .nullable()
+ .optional()
+});
+
+export const registerPamRecordingConfigRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/projects/:projectId/recording-config",
+ config: { rateLimit: readLimit },
+ schema: {
+ params: z.object({ projectId: z.string().uuid() }),
+ response: {
+ 200: z.object({
+ config: SanitizedConfigSchema.nullable()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { config } = await server.services.pamProjectRecordingConfig.getConfig(
+ { projectId: req.params.projectId },
+ req.permission
+ );
+ return { config };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/projects/:projectId/recording-config",
+ config: { rateLimit: writeLimit },
+ schema: {
+ params: z.object({ projectId: z.string().uuid() }),
+ body: UpsertBodySchema,
+ response: {
+ 200: z.object({ config: SanitizedConfigSchema })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ let config;
+ try {
+ ({ config } = await server.services.pamProjectRecordingConfig.upsertConfig(
+ { projectId: req.params.projectId, ...req.body },
+ req.permission
+ ));
+ } catch (err) {
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.params.projectId,
+ event: {
+ type: EventType.PAM_RECORDING_BUCKET_CONNECTION_TEST_FAILED,
+ metadata: {
+ projectId: req.params.projectId,
+ storageBackend: req.body.storageBackend,
+ bucket: req.body.bucket,
+ region: req.body.region,
+ reason: (err as Error)?.message ?? "unknown"
+ }
+ }
+ });
+ throw err;
+ }
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.params.projectId,
+ event: {
+ type: EventType.PAM_RECORDING_CONFIG_UPDATE,
+ metadata: {
+ projectId: req.params.projectId,
+ storageBackend: req.body.storageBackend,
+ bucket: req.body.bucket,
+ region: req.body.region
+ }
+ }
+ });
+
+ return { config };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/projects/:projectId/recording-config",
+ config: { rateLimit: writeLimit },
+ schema: {
+ params: z.object({ projectId: z.string().uuid() }),
+ response: { 200: z.object({ ok: z.literal(true) }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pamProjectRecordingConfig.deleteConfig(
+ { projectId: req.params.projectId },
+ req.permission
+ );
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.params.projectId,
+ event: {
+ type: EventType.PAM_RECORDING_CONFIG_DELETE,
+ metadata: { projectId: req.params.projectId }
+ }
+ });
+
+ return result;
+ }
+ });
+};
diff --git a/backend/src/ee/routes/v1/pam-session-chunk-router.ts b/backend/src/ee/routes/v1/pam-session-chunk-router.ts
new file mode 100644
index 0000000000..962714e2a2
--- /dev/null
+++ b/backend/src/ee/routes/v1/pam-session-chunk-router.ts
@@ -0,0 +1,252 @@
+import { z } from "zod";
+
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { PamRecordingStorageBackend } from "@app/ee/services/pam-session-recording-storage/pam-session-recording-storage-enums";
+import { BadRequestError } from "@app/lib/errors";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+const GATEWAY_TOKEN_HEADER = "x-gateway-upload-token";
+
+const ChunkPlaybackSchema = z.object({
+ chunkIndex: z.number().int().nonnegative().max(999999),
+ startElapsedMs: z.number(),
+ endElapsedMs: z.number(),
+ storageBackend: z.nativeEnum(PamRecordingStorageBackend),
+ externalChunkObjectKey: z.string().nullable(),
+ ciphertextSha256: z.string(),
+ ciphertextBytes: z.number(),
+ iv: z.string(),
+ presignedGetUrl: z.string().nullable()
+});
+
+export const registerPamSessionChunkRouter = async (server: FastifyZodProvider) => {
+ // Mint a presigned PUT URL for a single chunk. Gateway-authenticated
+ server.route({
+ method: "POST",
+ url: "/:sessionId/chunks/presigned-put",
+ config: { rateLimit: writeLimit },
+ schema: {
+ description: "Mint a presigned PUT URL for a session recording chunk (gateway only)",
+ params: z.object({ sessionId: z.string().uuid() }),
+ body: z.object({
+ chunkIndex: z.number().int().nonnegative().max(999999),
+ ciphertextBytes: z.number().int().positive(),
+ isKeyframe: z.boolean().optional()
+ }),
+ response: {
+ 200: z.object({
+ url: z.string(),
+ objectKey: z.string(),
+ method: z.literal("PUT"),
+ expiresInSeconds: z.number()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const uploadToken = req.headers[GATEWAY_TOKEN_HEADER];
+ if (typeof uploadToken !== "string" || !uploadToken) {
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.PAM_SESSION_UPLOAD_TOKEN_INVALID,
+ metadata: { sessionId: req.params.sessionId, chunkIndex: req.body.chunkIndex }
+ }
+ });
+ throw new BadRequestError({
+ message: `Missing ${GATEWAY_TOKEN_HEADER} header: required for chunk upload`
+ });
+ }
+
+ try {
+ return await server.services.pamSessionChunk.requestPresignedPut(
+ {
+ sessionId: req.params.sessionId,
+ chunkIndex: req.body.chunkIndex,
+ ciphertextBytes: req.body.ciphertextBytes,
+ isKeyframe: req.body.isKeyframe,
+ uploadToken
+ },
+ req.permission
+ );
+ } catch (err) {
+ const msg = (err as Error)?.message ?? "";
+ if (msg.includes("Invalid upload token")) {
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.PAM_SESSION_UPLOAD_TOKEN_INVALID,
+ metadata: { sessionId: req.params.sessionId, chunkIndex: req.body.chunkIndex }
+ }
+ });
+ }
+ throw err;
+ }
+ }
+ });
+
+ // Submit chunk metadata after the gateway has uploaded ciphertext to S3,
+ // OR (for Postgres backend) submit ciphertext + metadata in one call
+ server.route({
+ method: "POST",
+ url: "/:sessionId/chunks",
+ config: { rateLimit: writeLimit },
+ schema: {
+ description: "Record chunk metadata after upload, or upload ciphertext for Postgres backend",
+ params: z.object({ sessionId: z.string().uuid() }),
+ body: z.object({
+ chunkIndex: z.number().int().nonnegative().max(999999),
+ startElapsedMs: z.number(),
+ endElapsedMs: z.number(),
+ ciphertextSha256: z.string(),
+ ciphertextBytes: z.number().int().positive(),
+ iv: z.string(),
+ keyframeObjectKey: z.string().nullable().optional(),
+ keyframeSizeBytes: z.number().int().nonnegative().nullable().optional(),
+
+ // Base64 inline ciphertext for Postgres backend
+ ciphertext: z.string().optional()
+ }),
+ response: {
+ 200: z.object({
+ ok: z.literal(true),
+ storageBackend: z.string()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const uploadToken = req.headers[GATEWAY_TOKEN_HEADER];
+ if (typeof uploadToken !== "string" || !uploadToken) {
+ throw new BadRequestError({
+ message: `Missing ${GATEWAY_TOKEN_HEADER} header: required for chunk upload`
+ });
+ }
+
+ let ciphertextBuf: Buffer | undefined;
+ if (req.body.ciphertext) {
+ try {
+ ciphertextBuf = Buffer.from(req.body.ciphertext, "base64");
+ } catch {
+ throw new BadRequestError({ message: "ciphertext must be valid base64" });
+ }
+ }
+
+ const result = await server.services.pamSessionChunk.recordChunk(
+ {
+ sessionId: req.params.sessionId,
+ chunkIndex: req.body.chunkIndex,
+ startElapsedMs: req.body.startElapsedMs,
+ endElapsedMs: req.body.endElapsedMs,
+ ciphertextSha256Base64: req.body.ciphertextSha256,
+ ciphertextBytes: req.body.ciphertextBytes,
+ ivBase64: req.body.iv,
+ keyframeObjectKey: req.body.keyframeObjectKey ?? undefined,
+ keyframeSizeBytes: req.body.keyframeSizeBytes ?? undefined,
+ ciphertext: ciphertextBuf,
+ uploadToken
+ },
+ req.permission
+ );
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: result.projectId,
+ event: {
+ type: EventType.PAM_SESSION_CHUNK_UPLOAD,
+ metadata: {
+ sessionId: req.params.sessionId,
+ chunkIndex: req.body.chunkIndex,
+ storageBackend: result.storageBackend,
+ ciphertextBytes: req.body.ciphertextBytes
+ }
+ }
+ });
+
+ return { ok: true as const, storageBackend: result.storageBackend };
+ }
+ });
+
+ // User-facing playback endpoint: returns the unwrapped session key, chunk metadata, and presigned GET URLs
+ // For Postgres-backed chunks, the frontend instead calls /:sessionId/chunks/:chunkIndex/ciphertext to fetch bytes
+ server.route({
+ method: "GET",
+ url: "/:sessionId/playback",
+ config: { rateLimit: readLimit },
+ schema: {
+ description: "Get playback bundle: session key + chunk metadata + presigned GET URLs",
+ params: z.object({ sessionId: z.string().uuid() }),
+ response: {
+ 200: z.object({
+ legacy: z.boolean(),
+ sessionKey: z.string().nullable(),
+ projectId: z.string().optional(),
+ storageBackend: z.string().optional(),
+ chunks: z.array(ChunkPlaybackSchema)
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const result = await server.services.pamSessionChunk.getPlaybackBundle(req.params.sessionId, req.permission);
+ if (result.legacy) {
+ return { legacy: true, sessionKey: null, chunks: [] };
+ }
+ return {
+ legacy: false,
+ sessionKey: result.sessionKey,
+ projectId: result.projectId,
+ storageBackend: result.storageBackend,
+ chunks: result.chunks
+ };
+ }
+ });
+
+ // Postgres-backed chunk ciphertext fetch (since there's no presigned GET URL for inline blobs)
+ // Returns raw ciphertext bytes for the browser to verify + decrypt
+ server.route({
+ method: "GET",
+ url: "/:sessionId/chunks/:chunkIndex/ciphertext",
+ config: { rateLimit: readLimit },
+ schema: {
+ params: z.object({
+ sessionId: z.string().uuid(),
+ chunkIndex: z.coerce.number().int().nonnegative().max(999999)
+ })
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req, reply) => {
+ const { ciphertext } = await server.services.pamSessionChunk.getChunkCiphertext(
+ req.params.sessionId,
+ req.params.chunkIndex,
+ req.permission
+ );
+ void reply.header("Content-Type", "application/octet-stream");
+ void reply.header("Cache-Control", "no-store");
+ return reply.send(ciphertext);
+ }
+ });
+
+ // Storage backend constants exposed to the gateway for sanity checks (read-only)
+ server.route({
+ method: "GET",
+ url: "/recording-storage-backends",
+ config: { rateLimit: readLimit },
+ schema: {
+ response: {
+ 200: z.object({
+ backends: z.array(z.string())
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),
+ handler: async () => ({
+ backends: Object.values(PamRecordingStorageBackend)
+ })
+ });
+};
diff --git a/backend/src/ee/routes/v1/pam-session-router.ts b/backend/src/ee/routes/v1/pam-session-router.ts
index d894aa3dac..d25c26d4ec 100644
--- a/backend/src/ee/routes/v1/pam-session-router.ts
+++ b/backend/src/ee/routes/v1/pam-session-router.ts
@@ -12,6 +12,7 @@ import { SSHSessionCredentialsSchema } from "@app/ee/services/pam-resource/ssh/s
import {
HttpEventSchema,
PamSessionCommandLogSchema,
+ SanitizedSessionListItemSchema,
SanitizedSessionSchema,
SessionLogsPageSchema,
TerminalEventSchema
@@ -52,13 +53,23 @@ export const registerPamSessionRouter = async (server: FastifyZodProvider) => {
response: {
200: z.object({
credentials: SessionCredentialsSchema,
- policyRules: PolicyRulesResponseSchema
+ policyRules: PolicyRulesResponseSchema,
+ recording: z
+ .object({
+ sessionKey: z.string(),
+ uploadToken: z.string(),
+ storageBackend: z.string(),
+ projectId: z.string(),
+ sessionId: z.string()
+ })
+ .nullable()
+ .optional()
})
}
},
onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),
handler: async (req) => {
- const { credentials, policyRules, projectId, account, sessionStarted } =
+ const { credentials, policyRules, projectId, account, sessionStarted, recording } =
await server.services.pamAccount.getSessionCredentials(req.params.sessionId, req.permission);
await server.services.auditLog.createAuditLog({
@@ -102,7 +113,16 @@ export const registerPamSessionRouter = async (server: FastifyZodProvider) => {
return {
credentials: credentials as z.infer<typeof SessionCredentialsSchema>,
- policyRules
+ policyRules,
+ recording: recording
+ ? {
+ sessionKey: recording.sessionKeyBase64,
+ uploadToken: recording.uploadTokenBase64,
+ storageBackend: recording.storageBackend,
+ projectId,
+ sessionId: req.params.sessionId
+ }
+ : null
};
}
});
@@ -340,7 +360,7 @@ export const registerPamSessionRouter = async (server: FastifyZodProvider) => {
}),
response: {
200: z.object({
- sessions: SanitizedSessionSchema.array()
+ sessions: SanitizedSessionListItemSchema.array()
})
}
},
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 8dd84ceaba..092fb00c72 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -618,6 +618,11 @@ export enum EventType {
PAM_SESSION_GET = "pam-session-get",
PAM_SESSION_LIST = "pam-session-list",
PAM_SESSION_EVENT_BATCH_UPLOAD = "pam-session-event-batch-upload",
+ PAM_SESSION_CHUNK_UPLOAD = "pam-session-chunk-upload",
+ PAM_SESSION_UPLOAD_TOKEN_INVALID = "pam-session-upload-token-invalid",
+ PAM_RECORDING_CONFIG_UPDATE = "pam-recording-config-update",
+ PAM_RECORDING_CONFIG_DELETE = "pam-recording-config-delete",
+ PAM_RECORDING_BUCKET_CONNECTION_TEST_FAILED = "pam-recording-bucket-connection-test-failed",
PAM_FOLDER_CREATE = "pam-folder-create",
PAM_FOLDER_UPDATE = "pam-folder-update",
PAM_FOLDER_DELETE = "pam-folder-delete",
@@ -4902,6 +4907,52 @@ interface PamSessionEventBatchUploadEvent {
};
}
+interface PamSessionChunkUploadEvent {
+ type: EventType.PAM_SESSION_CHUNK_UPLOAD;
+ metadata: {
+ sessionId: string;
+ chunkIndex: number;
+ storageBackend: string;
+ ciphertextBytes: number;
+ };
+}
+
+interface PamSessionUploadTokenInvalidEvent {
+ type: EventType.PAM_SESSION_UPLOAD_TOKEN_INVALID;
+ metadata: {
+ sessionId: string;
+ chunkIndex?: number;
+ };
+}
+
+interface PamRecordingConfigUpsertEvent {
+ type: EventType.PAM_RECORDING_CONFIG_UPDATE;
+ metadata: {
+ projectId: string;
+ storageBackend: string;
+ bucket: string;
+ region: string;
+ };
+}
+
+interface PamRecordingConfigDeleteEvent {
+ type: EventType.PAM_RECORDING_CONFIG_DELETE;
+ metadata: {
+ projectId: string;
+ };
+}
+
+interface PamRecordingBucketConnectionTestFailedEvent {
+ type: EventType.PAM_RECORDING_BUCKET_CONNECTION_TEST_FAILED;
+ metadata: {
+ projectId: string;
+ storageBackend: string;
+ bucket: string;
+ region: string;
+ reason: string;
+ };
+}
+
interface PamFolderCreateEvent {
type: EventType.PAM_FOLDER_CREATE;
metadata: {
@@ -6605,6 +6656,11 @@ export type Event =
| PamSessionGetEvent
| PamSessionListEvent
| PamSessionEventBatchUploadEvent
+ | PamSessionChunkUploadEvent
+ | PamSessionUploadTokenInvalidEvent
+ | PamRecordingConfigUpsertEvent
+ | PamRecordingConfigDeleteEvent
+ | PamRecordingBucketConnectionTestFailedEvent
| PamFolderCreateEvent
| PamFolderUpdateEvent
| PamFolderDeleteEvent
diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.ts
index b0c89be071..aa76aa890c 100644
--- a/backend/src/ee/services/pam-account/pam-account-service.ts
+++ b/backend/src/ee/services/pam-account/pam-account-service.ts
@@ -65,6 +65,7 @@ import { TPamAccountDependenciesDALFactory } from "../pam-discovery/pam-account-
import { TPamDomainDALFactory } from "../pam-domain/pam-domain-dal";
import { PamDomainType } from "../pam-domain/pam-domain-enums";
import { PAM_DOMAIN_FACTORY_MAP } from "../pam-domain/pam-domain-factory";
+import { TPamProjectRecordingConfigServiceFactory } from "../pam-project-recording-config/pam-project-recording-config-service";
import { TPamResourceDALFactory } from "../pam-resource/pam-resource-dal";
import { PamResource } from "../pam-resource/pam-resource-enums";
import { TPamResourceRotationRulesDALFactory } from "../pam-resource/pam-resource-rotation-rules-dal";
@@ -74,6 +75,8 @@ import { TSqlAccountCredentials, TSqlResourceConnectionDetails } from "../pam-re
import { TSSHAccountCredentials, TSSHResourceInternalMetadata } from "../pam-resource/ssh/ssh-resource-types";
import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";
import { PamSessionStatus } from "../pam-session/pam-session-enums";
+import { generateSessionRecordingSecrets } from "../pam-session/pam-session-recording-secrets";
+import { PamRecordingStorageBackend } from "../pam-session-recording-storage/pam-session-recording-storage-enums";
import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permission/org-permission";
import { TPamAccountDALFactory } from "./pam-account-dal";
import { PamAccountRotationStatus } from "./pam-account-enums";
@@ -122,6 +125,7 @@ type TPamAccountServiceFactoryDep = {
"findByAccountId" | "updateById" | "countByAccountIds"
>;
keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "getItem">;
+ pamProjectRecordingConfigService: Pick<TPamProjectRecordingConfigServiceFactory, "resolveConfigForProject">;
};
export type TPamAccountServiceFactory = ReturnType<typeof pamAccountServiceFactory>;
@@ -148,7 +152,8 @@ export const pamAccountServiceFactory = ({
pamSessionExpirationService,
resourceMetadataDAL,
pamAccountDependenciesDAL,
- keyStore
+ keyStore,
+ pamProjectRecordingConfigService
}: TPamAccountServiceFactoryDep) => {
// Helper to resolve account parent (resource or domain)
const resolveAccountParent = async ({
@@ -954,6 +959,9 @@ export const pamAccountServiceFactory = ({
}
// For gateway-based resources (Postgres, MySQL, SSH), create session first
+ //
+ // Recording secrets are generated lazily at credential fetch time so the raw
+ // upload token can be returned exactly once to the gateway without persisting it
const session = await pamSessionDAL.create({
accountName: account.name,
actorEmail,
@@ -1243,13 +1251,40 @@ export const pamAccountServiceFactory = ({
let sessionStarted = false;
- // Mark session as started
+ // Recording secrets are lazily generated on the first /credentials call
+ // Returned exactly once to the gateway; only the encrypted session key and the SHA-256 of the upload token are persisted
+ // After the first call, the gateway is responsible for keeping these in memory (and persisting the upload token to disk for reconciliation)
+ let sessionRecordingSecrets: {
+ sessionKeyBase64: string;
+ uploadTokenBase64: string;
+ storageBackend: PamRecordingStorageBackend;
+ } | null = null;
if (session.status === PamSessionStatus.Starting) {
+ const projectRecordingConfig = await pamProjectRecordingConfigService.resolveConfigForProject(
+ session.projectId,
+ actor
+ );
+ const storageBackend = projectRecordingConfig?.backend ?? PamRecordingStorageBackend.Postgres;
+
+ const { sessionKey, uploadToken, encryptedSessionKey, uploadTokenHash } = await generateSessionRecordingSecrets({
+ projectId: session.projectId,
+ sessionId,
+ kmsService
+ });
+
await pamSessionDAL.updateById(sessionId, {
status: PamSessionStatus.Active,
- startedAt: new Date()
+ startedAt: new Date(),
+ encryptedSessionKey,
+ gatewayUploadTokenHash: uploadTokenHash
});
sessionStarted = true;
+
+ sessionRecordingSecrets = {
+ sessionKeyBase64: sessionKey.toString("base64"),
+ uploadTokenBase64: uploadToken.toString("base64"),
+ storageBackend
+ };
}
// Handle SSH certificate-based authentication
@@ -1299,7 +1334,8 @@ export const pamAccountServiceFactory = ({
policyRules,
projectId: project.id,
account,
- sessionStarted
+ sessionStarted,
+ recording: sessionRecordingSecrets
};
}
}
@@ -1312,7 +1348,8 @@ export const pamAccountServiceFactory = ({
policyRules,
projectId: project.id,
account,
- sessionStarted
+ sessionStarted,
+ recording: sessionRecordingSecrets
};
};
diff --git a/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-dal.ts b/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-dal.ts
new file mode 100644
index 0000000000..185b9f0f87
--- /dev/null
+++ b/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-dal.ts
@@ -0,0 +1,15 @@
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { ormify } from "@app/lib/knex";
+
+export type TPamProjectRecordingConfigDALFactory = ReturnType<typeof pamProjectRecordingConfigDALFactory>;
+
+export const pamProjectRecordingConfigDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.PamProjectRecordingConfig);
+
+ const findByProjectId = async (projectId: string) => {
+ return db.replicaNode()(TableName.PamProjectRecordingConfig).where({ projectId }).first();
+ };
+
+ return { ...orm, findByProjectId };
+};
diff --git a/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-service.ts b/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-service.ts
new file mode 100644
index 0000000000..f0aa3779a0
--- /dev/null
+++ b/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-service.ts
@@ -0,0 +1,188 @@
+import { ForbiddenError } from "@casl/ability";
+
+import { ActionProjectType } from "@app/db/schemas";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { OrgServiceActor } from "@app/lib/types";
+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
+import { AppConnection, AWSRegion } from "@app/services/app-connection/app-connection-enums";
+import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";
+import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
+import { getAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-fns";
+import { TAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-types";
+import { ActorType } from "@app/services/auth/auth-type";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+
+import { PamRecordingStorageBackend } from "../pam-session-recording-storage/pam-session-recording-storage-enums";
+import { PAM_RECORDING_STORAGE_FACTORY_MAP } from "../pam-session-recording-storage/pam-session-recording-storage-factory";
+import { TPamRecordingResolvedConfig } from "../pam-session-recording-storage/pam-session-recording-storage-types";
+import { TPamProjectRecordingConfigDALFactory } from "./pam-project-recording-config-dal";
+import {
+ TDeletePamRecordingConfigDTO,
+ TGetPamRecordingConfigDTO,
+ TUpsertPamRecordingConfigDTO
+} from "./pam-project-recording-config-types";
+
+type TPamProjectRecordingConfigServiceFactoryDep = {
+ pamProjectRecordingConfigDAL: TPamProjectRecordingConfigDALFactory;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+ appConnectionService: Pick<TAppConnectionServiceFactory, "findAppConnectionById">;
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+};
+
+export type TPamProjectRecordingConfigServiceFactory = ReturnType<typeof pamProjectRecordingConfigServiceFactory>;
+
+export const pamProjectRecordingConfigServiceFactory = ({
+ pamProjectRecordingConfigDAL,
+ permissionService,
+ appConnectionService,
+ appConnectionDAL,
+ kmsService
+}: TPamProjectRecordingConfigServiceFactoryDep) => {
+ // Gateways: direct DAL lookup (getOrgPermission doesn't support GATEWAY actors).
+ // Users: permission-checked lookup via appConnectionService for playback.
+ const resolveConfigForProject = async (
+ projectId: string,
+ actor: OrgServiceActor
+ ): Promise<TPamRecordingResolvedConfig | null> => {
+ const row = await pamProjectRecordingConfigDAL.findByProjectId(projectId);
+ if (!row) return null;
+
+ if (row.storageBackend === PamRecordingStorageBackend.AwsS3) {
+ let appConnection;
+ if (actor.type === ActorType.GATEWAY) {
+ const raw = await appConnectionDAL.findById(row.connectionId);
+ if (!raw) throw new NotFoundError({ message: `AWS app connection ${row.connectionId} not found` });
+ appConnection = await decryptAppConnection(raw, kmsService);
+ } else {
+ appConnection = await appConnectionService.findAppConnectionById(AppConnection.AWS, row.connectionId, actor);
+ }
+
+ const awsConfig = await getAwsConnectionConfig(
+ appConnection as unknown as TAwsConnectionConfig,
+ row.region as never
+ );
+
+ return {
+ backend: PamRecordingStorageBackend.AwsS3,
+ bucket: row.bucket,
+ region: row.region as AWSRegion,
+ keyPrefix: row.keyPrefix ?? null,
+ awsCredentials: awsConfig.credentials
+ };
+ }
+
+ return {
+ backend: PamRecordingStorageBackend.Postgres,
+ keyPrefix: row.keyPrefix ?? null
+ };
+ };
+
+ const getConfig = async ({ projectId }: TGetPamRecordingConfigDTO, actor: OrgServiceActor) => {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorAuthMethod: actor.authMethod,
+ actorId: actor.id,
+ actorOrgId: actor.orgId,
+ projectId,
+ actionProjectType: ActionProjectType.PAM
+ });
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Settings);
+
+ const row = await pamProjectRecordingConfigDAL.findByProjectId(projectId);
+ return { config: row ?? null };
+ };
+
+ const testConfig = async (input: TUpsertPamRecordingConfigDTO, actor: OrgServiceActor) => {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorAuthMethod: actor.authMethod,
+ actorId: actor.id,
+ actorOrgId: actor.orgId,
+ projectId: input.projectId,
+ actionProjectType: ActionProjectType.PAM
+ });
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Settings);
+
+ if (input.storageBackend !== PamRecordingStorageBackend.AwsS3) {
+ throw new BadRequestError({ message: `Unsupported storage backend: ${input.storageBackend}` });
+ }
+
+ const appConnection = await appConnectionService.findAppConnectionById(
+ AppConnection.AWS,
+ input.connectionId,
+ actor
+ );
+ if (!appConnection) throw new NotFoundError({ message: `AWS app connection ${input.connectionId} not found` });
+
+ const awsConfig = await getAwsConnectionConfig(
+ appConnection as unknown as TAwsConnectionConfig,
+ input.region as never
+ );
+
+ const provider = PAM_RECORDING_STORAGE_FACTORY_MAP[input.storageBackend]();
+ await provider.validateConfig({
+ config: {
+ backend: PamRecordingStorageBackend.AwsS3,
+ bucket: input.bucket,
+ region: input.region,
+ keyPrefix: input.keyPrefix ?? null,
+ awsCredentials: awsConfig.credentials
+ }
+ });
+
+ return { ok: true as const };
+ };
+
+ const upsertConfig = async (input: TUpsertPamRecordingConfigDTO, actor: OrgServiceActor) => {
+ await testConfig(input, actor);
+
+ const existing = await pamProjectRecordingConfigDAL.findByProjectId(input.projectId);
+ if (existing) {
+ const updated = await pamProjectRecordingConfigDAL.updateById(existing.id, {
+ storageBackend: input.storageBackend,
+ connectionId: input.connectionId,
+ bucket: input.bucket,
+ region: input.region,
+ keyPrefix: input.keyPrefix ?? null
+ });
+ return { config: updated };
+ }
+
+ const created = await pamProjectRecordingConfigDAL.create({
+ projectId: input.projectId,
+ storageBackend: input.storageBackend,
+ connectionId: input.connectionId,
+ bucket: input.bucket,
+ region: input.region,
+ keyPrefix: input.keyPrefix ?? null
+ });
+ return { config: created };
+ };
+
+ const deleteConfig = async ({ projectId }: TDeletePamRecordingConfigDTO, actor: OrgServiceActor) => {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorAuthMethod: actor.authMethod,
+ actorId: actor.id,
+ actorOrgId: actor.orgId,
+ projectId,
+ actionProjectType: ActionProjectType.PAM
+ });
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Settings);
+
+ const existing = await pamProjectRecordingConfigDAL.findByProjectId(projectId);
+ if (!existing) return { ok: true as const };
+ await pamProjectRecordingConfigDAL.deleteById(existing.id);
+ return { ok: true as const };
+ };
+
+ return {
+ getConfig,
+ upsertConfig,
+ deleteConfig,
+ resolveConfigForProject
+ };
+};
diff --git a/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-types.ts b/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-types.ts
new file mode 100644
index 0000000000..5bb26165aa
--- /dev/null
+++ b/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-types.ts
@@ -0,0 +1,20 @@
+import { AWSRegion } from "@app/services/app-connection/app-connection-enums";
+
+import { PamRecordingStorageBackend } from "../pam-session-recording-storage/pam-session-recording-storage-enums";
+
+export type TUpsertPamRecordingConfigDTO = {
+ projectId: string;
+ storageBackend: PamRecordingStorageBackend;
+ connectionId: string;
+ bucket: string;
+ region: AWSRegion;
+ keyPrefix?: string | null;
+};
+
+export type TGetPamRecordingConfigDTO = {
+ projectId: string;
+};
+
+export type TDeletePamRecordingConfigDTO = {
+ projectId: string;
+};
diff --git a/backend/src/ee/services/pam-resource/pam-resource-service.ts b/backend/src/ee/services/pam-resource/pam-resource-service.ts
index ba43eb33e8..4110bc511c 100644
--- a/backend/src/ee/services/pam-resource/pam-resource-service.ts
+++ b/backend/src/ee/services/pam-resource/pam-resource-service.ts
@@ -60,6 +60,9 @@ type TPamResourceServiceFactoryDep = {
>;
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
+ pamProjectRecordingConfigDAL: {
+ findByProjectId: (projectId: string) => Promise<unknown>;
+ };
};
export type TPamResourceServiceFactory = ReturnType<typeof pamResourceServiceFactory>;
@@ -73,7 +76,8 @@ export const pamResourceServiceFactory = ({
kmsService,
gatewayV2Service,
resourceMetadataDAL,
- appConnectionDAL
+ appConnectionDAL,
+ pamProjectRecordingConfigDAL
}: TPamResourceServiceFactoryDep) => {
const assertDomainInProject = async (domainId: string, projectId: string) => {
const domain = await pamDomainDAL.findById(domainId);
@@ -191,6 +195,17 @@ export const pamResourceServiceFactory = ({
await assertDomainInProject(domainId, projectId);
}
+ // Windows (RDP) recordings are too large for Postgres-backed storage; require an external bucket
+ if (resourceType === PamResource.Windows) {
+ const recordingConfig = await pamProjectRecordingConfigDAL.findByProjectId(projectId);
+ if (!recordingConfig) {
+ throw new BadRequestError({
+ message:
+ "Windows resources require an external session recording configuration. Configure session recording in project settings before creating a Windows resource."
+ });
+ }
+ }
+
const factory = PAM_RESOURCE_FACTORY_MAP[resourceType](
resourceType,
connectionDetails,
diff --git a/backend/src/ee/services/pam-session-recording-storage/aws-s3/aws-s3-provider-factory.ts b/backend/src/ee/services/pam-session-recording-storage/aws-s3/aws-s3-provider-factory.ts
new file mode 100644
index 0000000000..023c031db8
--- /dev/null
+++ b/backend/src/ee/services/pam-session-recording-storage/aws-s3/aws-s3-provider-factory.ts
@@ -0,0 +1,160 @@
+import {
+ DeleteObjectsCommand,
+ GetObjectCommand,
+ HeadBucketCommand,
+ ListObjectsV2Command,
+ PutObjectCommand,
+ S3Client
+} from "@aws-sdk/client-s3";
+import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
+
+import { CustomAWSHasher } from "@app/lib/aws/hashing";
+import { crypto } from "@app/lib/crypto/cryptography";
+import { BadRequestError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+
+import {
+ PAM_RECORDING_MAX_CHUNK_BYTES,
+ PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS
+} from "../pam-session-recording-storage-constants";
+import {
+ buildExternalChunkObjectKey,
+ normalizeKeyPrefix,
+ TPamRecordingResolvedConfig,
+ TPamRecordingStorageProvider
+} from "../pam-session-recording-storage-types";
+
+const buildClient = (config: TPamRecordingResolvedConfig) => {
+ if (!config.region || !config.awsCredentials) {
+ throw new BadRequestError({ message: "AWS S3 storage backend requires region and credentials" });
+ }
+ return new S3Client({
+ region: config.region,
+ useFipsEndpoint: crypto.isFipsModeEnabled(),
+ sha256: CustomAWSHasher,
+ credentials: config.awsCredentials
+ });
+};
+
+export const AwsS3RecordingStorageProvider: TPamRecordingStorageProvider = () => ({
+ validateConfig: async ({ config }) => {
+ if (!config.bucket) {
+ throw new BadRequestError({ message: "Bucket is required for AWS S3 backend" });
+ }
+ const client = buildClient(config);
+ try {
+ await client.send(new HeadBucketCommand({ Bucket: config.bucket }));
+ } catch (err) {
+ logger.warn({ err, bucket: config.bucket }, `S3 HeadBucket failed [bucket=${config.bucket}]`);
+ throw new BadRequestError({
+ message: `Unable to access bucket. Verify region, credentials, and bucket policy [bucket=${config.bucket}]`
+ });
+ }
+
+ const testKey = `${normalizeKeyPrefix(config.keyPrefix)}.test/${crypto.nativeCrypto.randomUUID()}`;
+
+ try {
+ await client.send(
+ new PutObjectCommand({
+ Bucket: config.bucket,
+ Key: testKey,
+ Body: Buffer.from("infisical-pam-recording-config-test"),
+ ContentType: "application/octet-stream"
+ })
+ );
+ } catch (err) {
+ logger.warn({ err, bucket: config.bucket, testKey }, `S3 round-trip PutObject failed [bucket=${config.bucket}]`);
+ throw new BadRequestError({
+ message: "Bucket reachable but PutObject failed. Grant s3:PutObject on the configured key prefix"
+ });
+ }
+
+ try {
+ await client.send(
+ new DeleteObjectsCommand({
+ Bucket: config.bucket,
+ Delete: { Objects: [{ Key: testKey }], Quiet: true }
+ })
+ );
+ } catch (err) {
+ // Best-effort delete; the test object lives under .test/ and is harmless if it lingers
+ logger.warn({ err, bucket: config.bucket, testKey }, `S3 test object cleanup failed [testKey=${testKey}]`);
+ }
+ },
+
+ mintPresignedPut: async ({ config, projectId, sessionId, chunkIndex, ciphertextBytes, isKeyframe }) => {
+ if (ciphertextBytes <= 0 || ciphertextBytes > PAM_RECORDING_MAX_CHUNK_BYTES) {
+ throw new BadRequestError({
+ message: `Chunk size out of range [bytes=${ciphertextBytes}, max=${PAM_RECORDING_MAX_CHUNK_BYTES}]`
+ });
+ }
+ if (!config.bucket) throw new BadRequestError({ message: "Bucket is required" });
+
+ const client = buildClient(config);
+ const objectKey = buildExternalChunkObjectKey(
+ config.keyPrefix,
+ projectId,
+ sessionId,
+ chunkIndex,
+ Boolean(isKeyframe)
+ );
+
+ const command = new PutObjectCommand({
+ Bucket: config.bucket,
+ Key: objectKey,
+ ContentLength: ciphertextBytes,
+ ContentType: "application/octet-stream"
+ });
+
+ // unhoistableHeaders forces Content-Length into the signature so the gateway can't pad
+ const url = await getSignedUrl(client, command, {
+ expiresIn: PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS,
+ unhoistableHeaders: new Set(["content-length"])
+ });
+
+ return {
+ url,
+ objectKey,
+ method: "PUT",
+ expiresInSeconds: PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS
+ };
+ },
+
+ mintPresignedGet: async ({ config, objectKey }) => {
+ if (!config.bucket) throw new BadRequestError({ message: "Bucket is required" });
+ const client = buildClient(config);
+ const command = new GetObjectCommand({ Bucket: config.bucket, Key: objectKey });
+ const url = await getSignedUrl(client, command, { expiresIn: PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS });
+ return { url, expiresInSeconds: PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS };
+ },
+
+ deleteSession: async ({ config, projectId, sessionId }) => {
+ if (!config.bucket) throw new BadRequestError({ message: "Bucket is required" });
+ const client = buildClient(config);
+
+ const prefix = `${normalizeKeyPrefix(config.keyPrefix)}${projectId}/${sessionId}/`;
+
+ let continuationToken: string | undefined;
+ do {
+ // eslint-disable-next-line no-await-in-loop
+ const listed = await client.send(
+ new ListObjectsV2Command({
+ Bucket: config.bucket,
+ Prefix: prefix,
+ ContinuationToken: continuationToken
+ })
+ );
+ const keys = (listed.Contents ?? []).map((o) => o.Key).filter((k): k is string => Boolean(k));
+ if (keys.length > 0) {
+ // eslint-disable-next-line no-await-in-loop
+ await client.send(
+ new DeleteObjectsCommand({
+ Bucket: config.bucket,
+ Delete: { Objects: keys.map((Key) => ({ Key })), Quiet: true }
+ })
+ );
+ }
+ continuationToken = listed.IsTruncated ? listed.NextContinuationToken : undefined;
+ } while (continuationToken);
+ }
+});
diff --git a/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-constants.ts b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-constants.ts
new file mode 100644
index 0000000000..2f3582a796
--- /dev/null
+++ b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-constants.ts
@@ -0,0 +1,9 @@
+// Versioning suffix on AAD lets us swap binding scheme later without migrating ciphertext
+export const PAM_RECORDING_AAD_VERSION = "v1";
+
+// 5-minute presigned URL expiry for both PUT and GET URLs
+export const PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS = 300;
+
+// Hard ceiling on a single chunk's ciphertext size -- 256 MB
+// RDP can produce large keyframes; this protects backend, S3, and browser
+export const PAM_RECORDING_MAX_CHUNK_BYTES = 256 * 1024 * 1024;
diff --git a/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-enums.ts b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-enums.ts
new file mode 100644
index 0000000000..8c3051434b
--- /dev/null
+++ b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-enums.ts
@@ -0,0 +1,4 @@
+export enum PamRecordingStorageBackend {
+ Postgres = "postgres",
+ AwsS3 = "aws-s3"
+}
diff --git a/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-factory.ts b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-factory.ts
new file mode 100644
index 0000000000..cbc416293b
--- /dev/null
+++ b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-factory.ts
@@ -0,0 +1,9 @@
+import { AwsS3RecordingStorageProvider } from "./aws-s3/aws-s3-provider-factory";
+import { PamRecordingStorageBackend } from "./pam-session-recording-storage-enums";
+import { TPamRecordingStorageProvider } from "./pam-session-recording-storage-types";
+import { PostgresRecordingStorageProvider } from "./postgres/postgres-provider-factory";
+
+export const PAM_RECORDING_STORAGE_FACTORY_MAP: Record<PamRecordingStorageBackend, TPamRecordingStorageProvider> = {
+ [PamRecordingStorageBackend.Postgres]: PostgresRecordingStorageProvider,
+ [PamRecordingStorageBackend.AwsS3]: AwsS3RecordingStorageProvider
+};
diff --git a/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-types.ts b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-types.ts
new file mode 100644
index 0000000000..f67986f0e7
--- /dev/null
+++ b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-types.ts
@@ -0,0 +1,68 @@
+import { AWSRegion } from "@app/services/app-connection/app-connection-enums";
+
+import { PamRecordingStorageBackend } from "./pam-session-recording-storage-enums";
+
+export type TPamRecordingChunkRef = {
+ storageBackend: PamRecordingStorageBackend;
+ externalChunkObjectKey?: string | null;
+ encryptedEventsBlob?: Buffer | null;
+};
+
+export type TPamRecordingResolvedConfig = {
+ backend: PamRecordingStorageBackend;
+ bucket?: string;
+ region?: AWSRegion;
+ keyPrefix?: string | null;
+
+ // Pre-resolved AWS credentials when backend === AwsS3, otherwise undefined
+ awsCredentials?: {
+ accessKeyId: string;
+ secretAccessKey: string;
+ sessionToken?: string;
+ };
+};
+
+export type TPamRecordingValidateConfig = (input: { config: TPamRecordingResolvedConfig }) => Promise<void>;
+
+export type TPamRecordingMintPresignedPut = (input: {
+ config: TPamRecordingResolvedConfig;
+ projectId: string;
+ sessionId: string;
+ chunkIndex: number;
+ ciphertextBytes: number;
+ isKeyframe?: boolean;
+}) => Promise<{ url: string; objectKey: string; expiresInSeconds: number; method: "PUT" }>;
+
+export type TPamRecordingMintPresignedGet = (input: {
+ config: TPamRecordingResolvedConfig;
+ objectKey: string;
+}) => Promise<{ url: string; expiresInSeconds: number }>;
+
+export type TPamRecordingDeleteSession = (input: {
+ config: TPamRecordingResolvedConfig;
+ projectId: string;
+ sessionId: string;
+}) => Promise<void>;
+
+export type TPamRecordingStorageProvider = () => {
+ validateConfig: TPamRecordingValidateConfig;
+ mintPresignedPut: TPamRecordingMintPresignedPut;
+ mintPresignedGet: TPamRecordingMintPresignedGet;
+ deleteSession: TPamRecordingDeleteSession;
+};
+
+export const normalizeKeyPrefix = (keyPrefix: string | null | undefined): string =>
+ keyPrefix ? `${keyPrefix.replace(/^\/+|\/+$/g, "")}/` : "";
+
+export const buildExternalChunkObjectKey = (
+ keyPrefix: string | null | undefined,
+ projectId: string,
+ sessionId: string,
+ chunkIndex: number,
+ isKeyframe: boolean
+): string => {
+ const prefix = normalizeKeyPrefix(keyPrefix);
+ const suffix = isKeyframe ? "keyframe.png.enc" : "json.enc";
+ const padded = chunkIndex.toString().padStart(6, "0");
+ return `${prefix}${projectId}/${sessionId}/chunk-${padded}.${suffix}`;
+};
diff --git a/backend/src/ee/services/pam-session-recording-storage/postgres/postgres-provider-factory.ts b/backend/src/ee/services/pam-session-recording-storage/postgres/postgres-provider-factory.ts
new file mode 100644
index 0000000000..dbcdfe9923
--- /dev/null
+++ b/backend/src/ee/services/pam-session-recording-storage/postgres/postgres-provider-factory.ts
@@ -0,0 +1,20 @@
+import { TPamRecordingStorageProvider } from "../pam-session-recording-storage-types";
+
+// Postgres backend: chunks are stored inline in the chunks table
+// All upload/playback flows go through the backend (gateway POSTs ciphertext, browser GETs ciphertext)
+export const PostgresRecordingStorageProvider: TPamRecordingStorageProvider = () => ({
+ validateConfig: async () => {
+ // Postgres is always available; nothing to validate
+ },
+ mintPresignedPut: async () => {
+ throw new Error(
+ "Postgres recording backend does not support presigned PUT URLs; gateway must POST ciphertext directly to backend"
+ );
+ },
+ mintPresignedGet: async () => {
+ throw new Error("Postgres recording backend does not support presigned GET URLs; backend serves ciphertext inline");
+ },
+ deleteSession: async () => {
+ // Chunks cascade-delete with the session row
+ }
+});
diff --git a/backend/src/ee/services/pam-session/pam-session-chunk-service.ts b/backend/src/ee/services/pam-session/pam-session-chunk-service.ts
new file mode 100644
index 0000000000..b9d176b303
--- /dev/null
+++ b/backend/src/ee/services/pam-session/pam-session-chunk-service.ts
@@ -0,0 +1,320 @@
+import { ForbiddenError } from "@casl/ability";
+
+import { ActionProjectType } from "@app/db/schemas";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { OrgServiceActor } from "@app/lib/types";
+import { ActorType } from "@app/services/auth/auth-type";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+
+import { TPamProjectRecordingConfigServiceFactory } from "../pam-project-recording-config/pam-project-recording-config-service";
+import { PAM_RECORDING_MAX_CHUNK_BYTES } from "../pam-session-recording-storage/pam-session-recording-storage-constants";
+import { PamRecordingStorageBackend } from "../pam-session-recording-storage/pam-session-recording-storage-enums";
+import { PAM_RECORDING_STORAGE_FACTORY_MAP } from "../pam-session-recording-storage/pam-session-recording-storage-factory";
+import { buildExternalChunkObjectKey } from "../pam-session-recording-storage/pam-session-recording-storage-types";
+import { ProjectPermissionPamSessionActions, ProjectPermissionSub } from "../permission/project-permission";
+import { TPamSessionDALFactory } from "./pam-session-dal";
+import { TPamSessionEventChunkDALFactory } from "./pam-session-event-chunk-dal";
+import { decryptSessionKey, verifyGatewayUploadToken } from "./pam-session-recording-secrets";
+
+type TPamSessionChunkServiceFactoryDep = {
+ pamSessionDAL: TPamSessionDALFactory;
+ pamSessionEventChunkDAL: TPamSessionEventChunkDALFactory;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ pamProjectRecordingConfigService: Pick<TPamProjectRecordingConfigServiceFactory, "resolveConfigForProject">;
+};
+
+export type TPamSessionChunkServiceFactory = ReturnType<typeof pamSessionChunkServiceFactory>;
+
+function assertGatewayActor(actor: OrgServiceActor) {
+ if (actor.type !== ActorType.IDENTITY && actor.type !== ActorType.GATEWAY) {
+ throw new ForbiddenRequestError({ message: "Only gateways can perform this action" });
+ }
+}
+
+export const pamSessionChunkServiceFactory = ({
+ pamSessionDAL,
+ pamSessionEventChunkDAL,
+ permissionService,
+ kmsService,
+ pamProjectRecordingConfigService
+}: TPamSessionChunkServiceFactoryDep) => {
+ const requestPresignedPut = async (
+ {
+ sessionId,
+ chunkIndex,
+ ciphertextBytes,
+ isKeyframe,
+ uploadToken
+ }: {
+ sessionId: string;
+ chunkIndex: number;
+ ciphertextBytes: number;
+ isKeyframe?: boolean;
+ uploadToken: string;
+ },
+ actor: OrgServiceActor
+ ) => {
+ assertGatewayActor(actor);
+
+ if (ciphertextBytes <= 0 || ciphertextBytes > PAM_RECORDING_MAX_CHUNK_BYTES) {
+ throw new BadRequestError({
+ message: `Chunk size out of range [bytes=${ciphertextBytes}, max=${PAM_RECORDING_MAX_CHUNK_BYTES}]`
+ });
+ }
+
+ const session = await pamSessionDAL.findById(sessionId);
+ if (!session) throw new NotFoundError({ message: `Session ${sessionId} not found` });
+
+ if (actor.type === ActorType.GATEWAY && session.gatewayId && session.gatewayId !== actor.id) {
+ throw new ForbiddenRequestError({ message: "Gateway not authorized for this session" });
+ }
+ if (actor.type === ActorType.IDENTITY && session.gatewayIdentityId && session.gatewayIdentityId !== actor.id) {
+ throw new ForbiddenRequestError({ message: "Identity not authorized for this session" });
+ }
+
+ verifyGatewayUploadToken(uploadToken, session.gatewayUploadTokenHash ?? null);
+
+ const config = await pamProjectRecordingConfigService.resolveConfigForProject(session.projectId, actor);
+ if (!config || config.backend === PamRecordingStorageBackend.Postgres) {
+ throw new BadRequestError({
+ message:
+ "Project is not configured for object-storage recordings. Gateway should POST ciphertext to /chunks instead."
+ });
+ }
+
+ const provider = PAM_RECORDING_STORAGE_FACTORY_MAP[config.backend]();
+ const presigned = await provider.mintPresignedPut({
+ config,
+ projectId: session.projectId,
+ sessionId,
+ chunkIndex,
+ ciphertextBytes,
+ isKeyframe
+ });
+
+ return presigned;
+ };
+
+ const recordChunk = async (
+ {
+ sessionId,
+ chunkIndex,
+ startElapsedMs,
+ endElapsedMs,
+ ciphertextSha256Base64,
+ ciphertextBytes,
+ ivBase64,
+ keyframeObjectKey,
+ keyframeSizeBytes,
+ ciphertext,
+ uploadToken
+ }: {
+ sessionId: string;
+ chunkIndex: number;
+ startElapsedMs: number;
+ endElapsedMs: number;
+ ciphertextSha256Base64: string;
+ ciphertextBytes: number;
+ ivBase64: string;
+ keyframeObjectKey?: string;
+ keyframeSizeBytes?: number;
+
+ // For Postgres backend, the gateway POSTs the ciphertext bytes inline
+ ciphertext?: Buffer;
+ uploadToken: string;
+ },
+ actor: OrgServiceActor
+ ) => {
+ assertGatewayActor(actor);
+
+ const session = await pamSessionDAL.findById(sessionId);
+ if (!session) throw new NotFoundError({ message: `Session ${sessionId} not found` });
+
+ if (actor.type === ActorType.GATEWAY && session.gatewayId && session.gatewayId !== actor.id) {
+ throw new ForbiddenRequestError({ message: "Gateway not authorized for this session" });
+ }
+ if (actor.type === ActorType.IDENTITY && session.gatewayIdentityId && session.gatewayIdentityId !== actor.id) {
+ throw new ForbiddenRequestError({ message: "Identity not authorized for this session" });
+ }
+
+ verifyGatewayUploadToken(uploadToken, session.gatewayUploadTokenHash ?? null);
+
+ if (ciphertextBytes <= 0 || ciphertextBytes > PAM_RECORDING_MAX_CHUNK_BYTES) {
+ throw new BadRequestError({
+ message: `Chunk size out of range [bytes=${ciphertextBytes}, max=${PAM_RECORDING_MAX_CHUNK_BYTES}]`
+ });
+ }
+
+ let ciphertextSha256: Buffer;
+ let iv: Buffer;
+ try {
+ ciphertextSha256 = Buffer.from(ciphertextSha256Base64, "base64");
+ iv = Buffer.from(ivBase64, "base64");
+ } catch {
+ throw new BadRequestError({ message: "Invalid base64 in chunk metadata" });
+ }
+ if (ciphertextSha256.length !== 32) {
+ throw new BadRequestError({ message: "ciphertextSha256 must be 32 bytes (sha256 digest)" });
+ }
+ if (iv.length !== 12) {
+ throw new BadRequestError({ message: "iv must be 12 bytes (AES-GCM standard)" });
+ }
+
+ const config = await pamProjectRecordingConfigService.resolveConfigForProject(session.projectId, actor);
+ const backend = config?.backend ?? PamRecordingStorageBackend.Postgres;
+
+ if (backend === PamRecordingStorageBackend.Postgres) {
+ if (!ciphertext) {
+ throw new BadRequestError({
+ message: "Postgres backend requires the ciphertext bytes to be POSTed inline"
+ });
+ }
+ if (ciphertext.length !== ciphertextBytes) {
+ throw new BadRequestError({
+ message: `Declared ciphertextBytes does not match body length [declared=${ciphertextBytes}, actual=${ciphertext.length}]`
+ });
+ }
+ }
+
+ const externalChunkObjectKey =
+ backend === PamRecordingStorageBackend.AwsS3
+ ? buildExternalChunkObjectKey(config?.keyPrefix, session.projectId, sessionId, chunkIndex, false)
+ : null;
+
+ const externalKeyframeObjectKey =
+ backend === PamRecordingStorageBackend.AwsS3 && keyframeObjectKey
+ ? buildExternalChunkObjectKey(config?.keyPrefix, session.projectId, sessionId, chunkIndex, true)
+ : null;
+
+ try {
+ await pamSessionEventChunkDAL.create({
+ sessionId,
+ chunkIndex,
+ startElapsedMs,
+ endElapsedMs,
+ storageBackend: backend,
+ encryptedEventsBlob: backend === PamRecordingStorageBackend.Postgres ? (ciphertext ?? null) : null,
+ externalChunkObjectKey,
+ chunkSizeBytes: backend === PamRecordingStorageBackend.AwsS3 ? ciphertextBytes : null,
+ externalKeyframeObjectKey,
+ keyframeSizeBytes: keyframeSizeBytes ?? null,
+ ciphertextSha256,
+ ciphertextBytes,
+ iv
+ });
+ } catch (err) {
+ logger.error(
+ { sessionId, chunkIndex, err },
+ `Chunk insert failed [sessionId=${sessionId}] [chunkIndex=${chunkIndex}]`
+ );
+ throw err;
+ }
+
+ return { ok: true as const, projectId: session.projectId, storageBackend: backend };
+ };
+
+ const getPlaybackBundle = async (sessionId: string, actor: OrgServiceActor) => {
+ const session = await pamSessionDAL.findById(sessionId);
+ if (!session) throw new NotFoundError({ message: `Session ${sessionId} not found` });
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorAuthMethod: actor.authMethod,
+ actorId: actor.id,
+ actorOrgId: actor.orgId,
+ projectId: session.projectId,
+ actionProjectType: ActionProjectType.PAM
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPamSessionActions.Read,
+ ProjectPermissionSub.PamSessions
+ );
+
+ if (!session.encryptedSessionKey) {
+ // Legacy session fall through to legacy decrypt path
+ return { sessionKey: null, chunks: [], legacy: true as const };
+ }
+
+ const sessionKey = await decryptSessionKey({
+ projectId: session.projectId,
+ sessionId,
+ encryptedSessionKey: session.encryptedSessionKey,
+ kmsService
+ });
+
+ const chunks = await pamSessionEventChunkDAL.findAllBySessionId(sessionId);
+
+ let presignedGetByObjectKey: Record<string, { url: string }> = {};
+ const config = await pamProjectRecordingConfigService.resolveConfigForProject(session.projectId, actor);
+ if (config?.backend === PamRecordingStorageBackend.AwsS3) {
+ const provider = PAM_RECORDING_STORAGE_FACTORY_MAP[config.backend]();
+ const minted = await Promise.all(
+ chunks
+ .filter((c) => c.storageBackend === PamRecordingStorageBackend.AwsS3 && c.externalChunkObjectKey)
+ .map(async (c) => {
+ const presigned = await provider.mintPresignedGet({
+ config,
+ objectKey: c.externalChunkObjectKey as string
+ });
+ return [c.externalChunkObjectKey as string, { url: presigned.url }] as const;
+ })
+ );
+ presignedGetByObjectKey = Object.fromEntries(minted);
+ }
+
+ return {
+ sessionKey: sessionKey.toString("base64"),
+ legacy: false as const,
+ projectId: session.projectId,
+ storageBackend: config?.backend ?? PamRecordingStorageBackend.Postgres,
+ chunks: chunks.map((c) => ({
+ chunkIndex: c.chunkIndex,
+ startElapsedMs: Number(c.startElapsedMs),
+ endElapsedMs: Number(c.endElapsedMs),
+ storageBackend: c.storageBackend as PamRecordingStorageBackend,
+ externalChunkObjectKey: c.externalChunkObjectKey ?? null,
+ ciphertextSha256: c.ciphertextSha256.toString("base64"),
+ ciphertextBytes: Number(c.ciphertextBytes),
+ iv: c.iv.toString("base64"),
+ presignedGetUrl: c.externalChunkObjectKey
+ ? (presignedGetByObjectKey[c.externalChunkObjectKey]?.url ?? null)
+ : null
+ }))
+ };
+ };
+
+ const getChunkCiphertext = async (sessionId: string, chunkIndex: number, actor: OrgServiceActor) => {
+ const session = await pamSessionDAL.findById(sessionId);
+ if (!session) throw new NotFoundError({ message: `Session ${sessionId} not found` });
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorAuthMethod: actor.authMethod,
+ actorId: actor.id,
+ actorOrgId: actor.orgId,
+ projectId: session.projectId,
+ actionProjectType: ActionProjectType.PAM
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPamSessionActions.Read,
+ ProjectPermissionSub.PamSessions
+ );
+
+ const chunk = await pamSessionEventChunkDAL.findByChunkIndex(sessionId, chunkIndex);
+ if (!chunk) throw new NotFoundError({ message: `Chunk ${chunkIndex} not found` });
+ if (chunk.storageBackend !== PamRecordingStorageBackend.Postgres) {
+ throw new BadRequestError({
+ message: "Chunk is stored externally; use the presigned GET URL from the playback endpoint"
+ });
+ }
+ if (!chunk.encryptedEventsBlob) {
+ throw new BadRequestError({ message: "Chunk has no inline ciphertext" });
+ }
+ return { ciphertext: chunk.encryptedEventsBlob };
+ };
+
+ return { requestPresignedPut, recordChunk, getPlaybackBundle, getChunkCiphertext };
+};
diff --git a/backend/src/ee/services/pam-session/pam-session-event-chunk-dal.ts b/backend/src/ee/services/pam-session/pam-session-event-chunk-dal.ts
new file mode 100644
index 0000000000..2f5d5c052f
--- /dev/null
+++ b/backend/src/ee/services/pam-session/pam-session-event-chunk-dal.ts
@@ -0,0 +1,24 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { ormify } from "@app/lib/knex";
+
+export type TPamSessionEventChunkDALFactory = ReturnType<typeof pamSessionEventChunkDALFactory>;
+
+export const pamSessionEventChunkDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.PamSessionEventChunk);
+
+ const findAllBySessionId = async (sessionId: string, tx?: Knex) => {
+ return (tx || db.replicaNode())(TableName.PamSessionEventChunk)
+ .where("sessionId", sessionId)
+ .orderBy("chunkIndex", "asc")
+ .select("*");
+ };
+
+ const findByChunkIndex = async (sessionId: string, chunkIndex: number, tx?: Knex) => {
+ return (tx || db.replicaNode())(TableName.PamSessionEventChunk).where({ sessionId, chunkIndex }).first();
+ };
+
+ return { ...orm, findAllBySessionId, findByChunkIndex };
+};
diff --git a/backend/src/ee/services/pam-session/pam-session-recording-secrets.ts b/backend/src/ee/services/pam-session/pam-session-recording-secrets.ts
new file mode 100644
index 0000000000..f633f98d1d
--- /dev/null
+++ b/backend/src/ee/services/pam-session/pam-session-recording-secrets.ts
@@ -0,0 +1,104 @@
+import { crypto } from "@app/lib/crypto/cryptography";
+import { BadRequestError, InternalServerError } from "@app/lib/errors";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { KmsDataKey } from "@app/services/kms/kms-types";
+
+import { PAM_RECORDING_AAD_VERSION } from "../pam-session-recording-storage/pam-session-recording-storage-constants";
+
+const SESSION_KEY_LENGTH = 32; // AES-256
+const UPLOAD_TOKEN_LENGTH = 32; // 256 random bits
+
+const buildWrapAad = (projectId: string, sessionId: string) =>
+ crypto.nativeCrypto.createHash("sha256").update(`${projectId}|${sessionId}|${PAM_RECORDING_AAD_VERSION}`).digest();
+
+export const generateSessionRecordingSecrets = async ({
+ projectId,
+ sessionId,
+ kmsService
+}: {
+ projectId: string;
+ sessionId: string;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+}) => {
+ const sessionKey = crypto.randomBytes(SESSION_KEY_LENGTH);
+ const uploadToken = crypto.randomBytes(UPLOAD_TOKEN_LENGTH);
+
+ const wrapAad = buildWrapAad(projectId, sessionId);
+
+ const { encryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
+ // KMS createCipherPairWithDataKey doesn't expose a native AAD parameter, so we prepend the AAD bytes to the plaintext before wrapping
+ // Unwrap then verifies the prefix matches the expected AAD with a constant-time compare
+ const encryptionPayload = Buffer.concat([wrapAad, sessionKey]);
+ const { cipherTextBlob: encryptedSessionKey } = encryptor({ plainText: encryptionPayload });
+
+ const uploadTokenHash = crypto.nativeCrypto.createHash("sha256").update(uploadToken).digest();
+
+ return {
+ sessionKey,
+ uploadToken,
+ encryptedSessionKey,
+ uploadTokenHash
+ };
+};
+
+export const decryptSessionKey = async ({
+ projectId,
+ sessionId,
+ encryptedSessionKey,
+ kmsService
+}: {
+ projectId: string;
+ sessionId: string;
+ encryptedSessionKey: Buffer;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+}) => {
+ const { decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
+ const decrypted = decryptor({ cipherTextBlob: encryptedSessionKey });
+ if (decrypted.length !== 32 + SESSION_KEY_LENGTH) {
+ throw new InternalServerError({ message: "Encrypted session key has unexpected size" });
+ }
+ const recoveredAad = decrypted.subarray(0, 32);
+ const expectedAad = buildWrapAad(projectId, sessionId);
+ if (!crypto.nativeCrypto.timingSafeEqual(recoveredAad, expectedAad)) {
+ throw new InternalServerError({ message: "Session key AAD mismatch — refusing to unwrap" });
+ }
+ return decrypted.subarray(32, 32 + SESSION_KEY_LENGTH);
+};
+
+export const verifyGatewayUploadToken = (
+ presentedTokenBase64: string | undefined | null,
+ storedTokenHash: Buffer | null | undefined
+) => {
+ if (!presentedTokenBase64 || !storedTokenHash) {
+ throw new BadRequestError({
+ message: "Gateway upload token missing or session not configured for chunked uploads"
+ });
+ }
+ let presentedBuf: Buffer;
+ try {
+ presentedBuf = Buffer.from(presentedTokenBase64, "base64");
+ } catch {
+ throw new BadRequestError({ message: "Invalid upload token" });
+ }
+ if (presentedBuf.length !== UPLOAD_TOKEN_LENGTH) {
+ throw new BadRequestError({ message: "Invalid upload token" });
+ }
+ const presentedHash = crypto.nativeCrypto.createHash("sha256").update(presentedBuf).digest();
+ if (presentedHash.length !== storedTokenHash.length) {
+ throw new BadRequestError({ message: "Invalid upload token" });
+ }
+ if (!crypto.nativeCrypto.timingSafeEqual(presentedHash, storedTokenHash)) {
+ throw new BadRequestError({ message: "Invalid upload token" });
+ }
+};
+
+export const SESSION_KEY_BYTES = SESSION_KEY_LENGTH;
+export const UPLOAD_TOKEN_BYTES = UPLOAD_TOKEN_LENGTH;
diff --git a/backend/src/ee/services/pam-session/pam-session-schemas.ts b/backend/src/ee/services/pam-session/pam-session-schemas.ts
index c2e397494f..f6816ca146 100644
--- a/backend/src/ee/services/pam-session/pam-session-schemas.ts
+++ b/backend/src/ee/services/pam-session/pam-session-schemas.ts
@@ -64,6 +64,16 @@ export const SanitizedSessionSchema = PamSessionsSchema.omit({
aiInsights: AiInsightsSchema
});
+export const SanitizedSessionListItemSchema = PamSessionsSchema.omit({
+ encryptedLogsBlob: true,
+ encryptedAiInsights: true,
+ encryptedSessionKey: true,
+ gatewayUploadTokenHash: true
+}).extend({
+ gatewayIdentityId: z.string().nullable().optional(),
+ gatewayId: z.string().nullable().optional()
+});
+
export const SessionLogsPageSchema = z.object({
logs: z.array(z.union([PamSessionCommandLogSchema, TerminalEventSchema, HttpEventSchema])),
hasMore: z.boolean(),
diff --git a/backend/src/ee/services/pam-session/pam-session-service.ts b/backend/src/ee/services/pam-session/pam-session-service.ts
index 8c5e72fd86..c45a4f31ab 100644
--- a/backend/src/ee/services/pam-session/pam-session-service.ts
+++ b/backend/src/ee/services/pam-session/pam-session-service.ts
@@ -139,9 +139,7 @@ export const pamSessionServiceFactory = ({
const sessions = await pamSessionDAL.findByProjectId(projectId);
- return {
- sessions: await Promise.all(sessions.map((session) => decryptSession(session, projectId, kmsService)))
- };
+ return { sessions };
};
const updateLogsById = async ({ sessionId, logs }: TUpdateSessionLogsDTO, actor: OrgServiceActor) => {
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 68327ec00b..c42640868b 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -106,14 +106,18 @@ import { pamDomainDALFactory } from "@app/ee/services/pam-domain/pam-domain-dal"
import { pamDomainServiceFactory } from "@app/ee/services/pam-domain/pam-domain-service";
import { pamFolderDALFactory } from "@app/ee/services/pam-folder/pam-folder-dal";
import { pamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";
+import { pamProjectRecordingConfigDALFactory } from "@app/ee/services/pam-project-recording-config/pam-project-recording-config-dal";
+import { pamProjectRecordingConfigServiceFactory } from "@app/ee/services/pam-project-recording-config/pam-project-recording-config-service";
import { pamResourceDALFactory } from "@app/ee/services/pam-resource/pam-resource-dal";
import { pamResourceFavoriteDALFactory } from "@app/ee/services/pam-resource/pam-resource-favorite-dal";
import { pamResourceRotationRulesDALFactory } from "@app/ee/services/pam-resource/pam-resource-rotation-rules-dal";
import { pamResourceRotationRulesServiceFactory } from "@app/ee/services/pam-resource/pam-resource-rotation-rules-service";
import { pamResourceServiceFactory } from "@app/ee/services/pam-resource/pam-resource-service";
import { pamSessionAiSummaryServiceFactory } from "@app/ee/services/pam-session/pam-session-ai-summary-queue";
+import { pamSessionChunkServiceFactory } from "@app/ee/services/pam-session/pam-session-chunk-service";
import { pamSessionDALFactory } from "@app/ee/services/pam-session/pam-session-dal";
import { pamSessionEventBatchDALFactory } from "@app/ee/services/pam-session/pam-session-event-batch-dal";
+import { pamSessionEventChunkDALFactory } from "@app/ee/services/pam-session/pam-session-event-chunk-dal";
import { pamSessionServiceFactory } from "@app/ee/services/pam-session/pam-session-service";
import { pamWebAccessServiceFactory } from "@app/ee/services/pam-web-access/pam-web-access-service";
import { permissionDALFactory } from "@app/ee/services/permission/permission-dal";
@@ -2858,6 +2862,8 @@ export const registerRoutes = async (
const pamAccountPolicyDAL = pamAccountPolicyDALFactory(db);
const pamSessionDAL = pamSessionDALFactory(db);
const pamSessionEventBatchDAL = pamSessionEventBatchDALFactory(db);
+ const pamSessionEventChunkDAL = pamSessionEventChunkDALFactory(db);
+ const pamProjectRecordingConfigDAL = pamProjectRecordingConfigDALFactory(db);
const pamDiscoveryRunDAL = pamDiscoveryRunDALFactory(db);
const pamDiscoverySourceResourcesDAL = pamDiscoverySourceResourcesDALFactory(db);
const pamDiscoverySourceAccountsDAL = pamDiscoverySourceAccountsDALFactory(db);
@@ -2877,6 +2883,22 @@ export const registerRoutes = async (
permissionService
});
+ const pamProjectRecordingConfigService = pamProjectRecordingConfigServiceFactory({
+ pamProjectRecordingConfigDAL,
+ permissionService,
+ appConnectionService,
+ appConnectionDAL,
+ kmsService
+ });
+
+ const pamSessionChunkService = pamSessionChunkServiceFactory({
+ pamSessionDAL,
+ pamSessionEventChunkDAL,
+ permissionService,
+ kmsService,
+ pamProjectRecordingConfigService
+ });
+
const pamResourceService = pamResourceServiceFactory({
pamResourceDAL,
pamResourceFavoriteDAL,
@@ -2886,7 +2908,8 @@ export const registerRoutes = async (
kmsService,
gatewayV2Service,
resourceMetadataDAL,
- appConnectionDAL
+ appConnectionDAL,
+ pamProjectRecordingConfigDAL
});
const pamDomainService = pamDomainServiceFactory({
@@ -2953,7 +2976,8 @@ export const registerRoutes = async (
pamSessionExpirationService,
resourceMetadataDAL,
pamAccountDependenciesDAL,
- keyStore
+ keyStore,
+ pamProjectRecordingConfigService
});
const pamAccountRotation = pamAccountRotationServiceFactory({
@@ -3262,6 +3286,8 @@ export const registerRoutes = async (
pamAccount: pamAccountService,
pamAccountPolicy: pamAccountPolicyService,
pamSession: pamSessionService,
+ pamSessionChunk: pamSessionChunkService,
+ pamProjectRecordingConfig: pamProjectRecordingConfigService,
pamWebAccess: pamWebAccessService,
pamDiscoverySource: pamDiscoverySourceService,
mfaSession: mfaSessionService,
diff --git a/docs/integrations/app-connections/aws.mdx b/docs/integrations/app-connections/aws.mdx
index 6ad1e305e0..cc75a05ecf 100644
--- a/docs/integrations/app-connections/aws.mdx
+++ b/docs/integrations/app-connections/aws.mdx
@@ -394,6 +394,88 @@ Infisical supports two methods for connecting to AWS.
</Accordion>
</AccordionGroup>
</Tab>
+ <Tab title="PAM Session Recording">
+ <AccordionGroup>
+ <Accordion title="AWS S3 Bucket">
+ Use the following custom policy to grant the minimum permissions required by Infisical to store and play back PAM session recordings in your S3 bucket. Replace `your-pam-recordings-bucket` with the bucket name you configure in **Project Settings → Session Recording**.
+
+ ```json
+ {
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Sid": "AllowPamRecordingBucketAccess",
+ "Effect": "Allow",
+ "Action": [
+ "s3:PutObject",
+ "s3:GetObject"
+ ],
+ "Resource": "arn:aws:s3:::your-pam-recordings-bucket/*"
+ },
+ {
+ "Sid": "AllowPamRecordingBucketTest",
+ "Effect": "Allow",
+ "Action": [
+ "s3:ListBucket"
+ ],
+ "Resource": "arn:aws:s3:::your-pam-recordings-bucket"
+ },
+ {
+ "Sid": "AllowPamRecordingConnectionTestCleanup",
+ "Effect": "Allow",
+ "Action": [
+ "s3:DeleteObject"
+ ],
+ "Resource": "arn:aws:s3:::your-pam-recordings-bucket/.test/*"
+ }
+ ]
+ }
+ ```
+
+ If you scoped the recording config to a key prefix (for example `pam/prod`), update all three `Resource` ARNs to include the prefix:
+
+ ```json
+ "Resource": "arn:aws:s3:::your-pam-recordings-bucket/pam/prod/*"
+ ```
+
+ ```json
+ "Resource": "arn:aws:s3:::your-pam-recordings-bucket/pam/prod/.test/*"
+ ```
+
+ <Note>
+ **S3 Permissions:**
+ - **PutObject**: Lets the gateway upload encrypted recording chunks via presigned PUT URLs. Also used by the connection test to write a probe object under `{prefix}/.test/{uuid}`.
+ - **GetObject**: Lets the browser fetch encrypted chunks during playback via presigned GET URLs. Decryption happens locally in the browser; Infisical only ever sees ciphertext.
+ - **ListBucket**: Required by `HeadBucket`, which Infisical calls during the connection test to confirm the bucket exists and the credentials can reach it.
+ - **DeleteObject** (scoped to `.test/*`): Used **only** to clean up the probe object after the connection test. Infisical never deletes recording chunks. Your bucket lifecycle policy owns retention. When using a key prefix, the test object is written under `{prefix}/.test/`, so the `DeleteObject` resource must include the prefix.
+ </Note>
+
+ <Note>
+ Recording chunks are encrypted with a per-session AES-256-GCM key on the gateway before they leave your network, and the session key is wrapped with Infisical's KMS using session-bound AAD. Even if the bucket policy is wider than the principle of least privilege suggests, the ciphertext is not readable without an authenticated session-key unwrap.
+ </Note>
+
+ #### Bucket CORS Configuration
+
+ During playback the browser fetches encrypted chunks directly from S3 using presigned GET URLs. For this to work the bucket needs a CORS policy that allows requests from your Infisical domain.
+
+ Open the bucket in the AWS console, go to **Permissions → Cross-origin resource sharing (CORS)**, and add:
+
+ ```json
+ [
+ {
+ "AllowedHeaders": ["*"],
+ "AllowedMethods": ["GET", "PUT"],
+ "AllowedOrigins": ["https://app.infisical.com"],
+ "ExposeHeaders": [],
+ "MaxAgeSeconds": 3600
+ }
+ ]
+ ```
+
+ Replace `https://app.infisical.com` with the origin where your Infisical dashboard is served (for example `https://eu.infisical.com` or `http://localhost:8080` during development). You can list multiple origins if needed.
+ </Accordion>
+ </AccordionGroup>
+ </Tab>
</Tabs>
</Step>
@@ -786,6 +868,88 @@ Infisical supports two methods for connecting to AWS.
</Accordion>
</AccordionGroup>
</Tab>
+ <Tab title="PAM Session Recording">
+ <AccordionGroup>
+ <Accordion title="AWS S3 Bucket">
+ Use the following custom policy to grant the minimum permissions required by Infisical to store and play back PAM session recordings in your S3 bucket. Replace `your-pam-recordings-bucket` with the bucket name you configure in **Project Settings → Session Recording**.
+
+ ```json
+ {
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Sid": "AllowPamRecordingBucketAccess",
+ "Effect": "Allow",
+ "Action": [
+ "s3:PutObject",
+ "s3:GetObject"
+ ],
+ "Resource": "arn:aws:s3:::your-pam-recordings-bucket/*"
+ },
+ {
+ "Sid": "AllowPamRecordingBucketTest",
+ "Effect": "Allow",
+ "Action": [
+ "s3:ListBucket"
+ ],
+ "Resource": "arn:aws:s3:::your-pam-recordings-bucket"
+ },
+ {
+ "Sid": "AllowPamRecordingConnectionTestCleanup",
+ "Effect": "Allow",
+ "Action": [
+ "s3:DeleteObject"
+ ],
+ "Resource": "arn:aws:s3:::your-pam-recordings-bucket/.test/*"
+ }
+ ]
+ }
+ ```
+
+ If you scoped the recording config to a key prefix (for example `pam/prod`), update all three `Resource` ARNs to include the prefix:
+
+ ```json
+ "Resource": "arn:aws:s3:::your-pam-recordings-bucket/pam/prod/*"
+ ```
+
+ ```json
+ "Resource": "arn:aws:s3:::your-pam-recordings-bucket/pam/prod/.test/*"
+ ```
+
+ <Note>
+ **S3 Permissions:**
+ - **PutObject**: Lets the gateway upload encrypted recording chunks via presigned PUT URLs. Also used by the connection test to write a probe object under `{prefix}/.test/{uuid}`.
+ - **GetObject**: Lets the browser fetch encrypted chunks during playback via presigned GET URLs. Decryption happens locally in the browser; Infisical only ever sees ciphertext.
+ - **ListBucket**: Required by `HeadBucket`, which Infisical calls during the connection test to confirm the bucket exists and the credentials can reach it.
+ - **DeleteObject** (scoped to `.test/*`): Used **only** to clean up the probe object after the connection test. Infisical never deletes recording chunks. Your bucket lifecycle policy owns retention. When using a key prefix, the test object is written under `{prefix}/.test/`, so the `DeleteObject` resource must include the prefix.
+ </Note>
+
+ <Note>
+ Recording chunks are encrypted with a per-session AES-256-GCM key on the gateway before they leave your network, and the session key is wrapped with Infisical's KMS using session-bound AAD. Even if the bucket policy is wider than the principle of least privilege suggests, the ciphertext is not readable without an authenticated session-key unwrap.
+ </Note>
+
+ #### Bucket CORS Configuration
+
+ During playback the browser fetches encrypted chunks directly from S3 using presigned GET URLs. For this to work the bucket needs a CORS policy that allows requests from your Infisical domain.
+
+ Open the bucket in the AWS console, go to **Permissions → Cross-origin resource sharing (CORS)**, and add:
+
+ ```json
+ [
+ {
+ "AllowedHeaders": ["*"],
+ "AllowedMethods": ["GET", "PUT"],
+ "AllowedOrigins": ["https://app.infisical.com"],
+ "ExposeHeaders": [],
+ "MaxAgeSeconds": 3600
+ }
+ ]
+ ```
+
+ Replace `https://app.infisical.com` with the origin where your Infisical dashboard is served (for example `https://eu.infisical.com` or `http://localhost:8080` during development). You can list multiple origins if needed.
+ </Accordion>
+ </AccordionGroup>
+ </Tab>
</Tabs>
</Step>
<Step title="Obtain Access Key ID and Secret Access Key">
diff --git a/frontend/index.html b/frontend/index.html
index 1e384f0142..2a66cba2ab 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -12,7 +12,7 @@
style-src 'self' 'unsafe-inline' https://hcaptcha.com https://*.hcaptcha.com https://tags.srv.stackadapt.com;
child-src https://api.stripe.com;
frame-src https://js.stripe.com/ https://api.stripe.com https://www.youtube.com/ https://hcaptcha.com https://*.hcaptcha.com https://www.googletagmanager.com;
- connect-src 'self' wss://nexus-websocket-a.intercom.io https://api-iam.intercom.io https://api.heroku.com/ https://id.heroku.com/oauth/authorize https://id.heroku.com/oauth/token https://checkout.stripe.com https://app.posthog.com https://*.posthog.com https://api.stripe.com https://api.pwnedpasswords.com http://127.0.0.1:* https://hcaptcha.com https://*.hcaptcha.com https://www.googletagmanager.com https://www.google-analytics.com https://region1.google-analytics.com https://analytics.google.com https://stats.g.doubleclick.net https://googleads.g.doubleclick.net https://forms.hscollectedforms.net https://forms.hubspot.com https://api.hubapi.com https://*.ads.linkedin.com https://tags.srv.stackadapt.com https://api.unifyintent.com https://pixel-config.reddit.com https://cdn.jsdelivr.net/npm/@lottiefiles/[email protected]/dist/dotlottie-player.wasm;
+ connect-src 'self' wss://nexus-websocket-a.intercom.io https://api-iam.intercom.io https://api.heroku.com/ https://id.heroku.com/oauth/authorize https://id.heroku.com/oauth/token https://checkout.stripe.com https://app.posthog.com https://*.posthog.com https://api.stripe.com https://api.pwnedpasswords.com http://127.0.0.1:* https://hcaptcha.com https://*.hcaptcha.com https://www.googletagmanager.com https://www.google-analytics.com https://region1.google-analytics.com https://analytics.google.com https://stats.g.doubleclick.net https://googleads.g.doubleclick.net https://forms.hscollectedforms.net https://forms.hubspot.com https://api.hubapi.com https://*.ads.linkedin.com https://tags.srv.stackadapt.com https://api.unifyintent.com https://pixel-config.reddit.com https://cdn.jsdelivr.net/npm/@lottiefiles/[email protected]/dist/dotlottie-player.wasm https://*.s3.amazonaws.com https://*.s3.us-east-1.amazonaws.com https://*.s3.us-east-2.amazonaws.com https://*.s3.us-west-1.amazonaws.com https://*.s3.us-west-2.amazonaws.com https://*.s3.af-south-1.amazonaws.com https://*.s3.ap-east-1.amazonaws.com https://*.s3.ap-south-1.amazonaws.com https://*.s3.ap-south-2.amazonaws.com https://*.s3.ap-southeast-1.amazonaws.com https://*.s3.ap-southeast-2.amazonaws.com https://*.s3.ap-southeast-3.amazonaws.com https://*.s3.ap-southeast-4.amazonaws.com https://*.s3.ap-northeast-1.amazonaws.com https://*.s3.ap-northeast-2.amazonaws.com https://*.s3.ap-northeast-3.amazonaws.com https://*.s3.ca-central-1.amazonaws.com https://*.s3.eu-central-1.amazonaws.com https://*.s3.eu-central-2.amazonaws.com https://*.s3.eu-west-1.amazonaws.com https://*.s3.eu-west-2.amazonaws.com https://*.s3.eu-west-3.amazonaws.com https://*.s3.eu-south-1.amazonaws.com https://*.s3.eu-south-2.amazonaws.com https://*.s3.eu-north-1.amazonaws.com https://*.s3.me-south-1.amazonaws.com https://*.s3.me-central-1.amazonaws.com https://*.s3.sa-east-1.amazonaws.com https://*.s3.us-gov-east-1.amazonaws.com https://*.s3.us-gov-west-1.amazonaws.com;
img-src 'self' https://static.intercomassets.com https://js.intercomcdn.com https://downloads.intercomcdn.com https://*.stripe.com https://i.ytimg.com/ data: https://www.googletagmanager.com https://www.google-analytics.com https://www.google.com https://googleads.g.doubleclick.net https://www.googleadservices.com https://track.hubspot.com https://forms.hubspot.com https://forms.hsforms.com https://alb.reddit.com https://*.ads.linkedin.com;
media-src 'self' https://js.intercomcdn.com;
font-src 'self' https://fonts.intercomcdn.com/ https://fonts.gstatic.com;
diff --git a/frontend/src/const/routes.ts b/frontend/src/const/routes.ts
index 425cbb7bb3..ce16ebc2ab 100644
--- a/frontend/src/const/routes.ts
+++ b/frontend/src/const/routes.ts
@@ -373,6 +373,10 @@ export const ROUTE_PATHS = Object.freeze({
"/organizations/$orgId/projects/pam/$projectId/resources/",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/"
),
+ SettingsPage: setRoute(
+ "/organizations/$orgId/projects/pam/$projectId/settings",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/settings"
+ ),
SessionsPage: setRoute(
"/organizations/$orgId/projects/pam/$projectId/sessions",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/sessions/"
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index de623df749..9b42ae3a74 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -295,6 +295,12 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.PAM_ACCOUNT_POLICY_GET]: "Get PAM Account Policy",
[EventType.PAM_ACCOUNT_READ_CREDENTIALS]: "Read PAM Account Credentials",
[EventType.PAM_WEB_ACCESS_SESSION_TICKET_CREATED]: "Create PAM Web Access Session Ticket",
+ [EventType.PAM_SESSION_CHUNK_UPLOAD]: "PAM Session Chunk Upload",
+ [EventType.PAM_SESSION_UPLOAD_TOKEN_INVALID]: "PAM Session Upload Token Invalid",
+ [EventType.PAM_RECORDING_CONFIG_UPDATE]: "Update PAM Recording Config",
+ [EventType.PAM_RECORDING_CONFIG_DELETE]: "Delete PAM Recording Config",
+ [EventType.PAM_RECORDING_BUCKET_CONNECTION_TEST_FAILED]:
+ "PAM Recording Bucket Connection Test Failed",
[EventType.PAM_RESOURCE_LIST]: "List PAM Resources",
[EventType.PAM_RESOURCE_GET]: "Get PAM Resource",
[EventType.PAM_RESOURCE_CREATE]: "Create PAM Resource",
@@ -477,7 +483,12 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {
EventType.PAM_RESOURCE_ROTATION_RULE_CREATE,
EventType.PAM_RESOURCE_ROTATION_RULE_UPDATE,
EventType.PAM_RESOURCE_ROTATION_RULE_DELETE,
- EventType.PAM_RESOURCE_ROTATION_RULE_REORDER
+ EventType.PAM_RESOURCE_ROTATION_RULE_REORDER,
+ EventType.PAM_SESSION_CHUNK_UPLOAD,
+ EventType.PAM_SESSION_UPLOAD_TOKEN_INVALID,
+ EventType.PAM_RECORDING_CONFIG_UPDATE,
+ EventType.PAM_RECORDING_CONFIG_DELETE,
+ EventType.PAM_RECORDING_BUCKET_CONNECTION_TEST_FAILED
],
[ProjectType.AI]: [
...sharedProjectEvents,
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index 69456eba0d..1c4427c516 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -308,6 +308,11 @@ export enum EventType {
PAM_RESOURCE_ROTATION_RULE_UPDATE = "pam-resource-rotation-rule-update",
PAM_RESOURCE_ROTATION_RULE_DELETE = "pam-resource-rotation-rule-delete",
PAM_RESOURCE_ROTATION_RULE_REORDER = "pam-resource-rotation-rule-reorder",
+ PAM_SESSION_CHUNK_UPLOAD = "pam-session-chunk-upload",
+ PAM_SESSION_UPLOAD_TOKEN_INVALID = "pam-session-upload-token-invalid",
+ PAM_RECORDING_CONFIG_UPDATE = "pam-recording-config-update",
+ PAM_RECORDING_CONFIG_DELETE = "pam-recording-config-delete",
+ PAM_RECORDING_BUCKET_CONNECTION_TEST_FAILED = "pam-recording-bucket-connection-test-failed",
CREATE_CERTIFICATE_PROFILE = "create-certificate-profile",
UPDATE_CERTIFICATE_PROFILE = "update-certificate-profile",
diff --git a/frontend/src/hooks/api/pam/recording-config/index.ts b/frontend/src/hooks/api/pam/recording-config/index.ts
new file mode 100644
index 0000000000..177955438b
--- /dev/null
+++ b/frontend/src/hooks/api/pam/recording-config/index.ts
@@ -0,0 +1,3 @@
+export * from "./mutations";
+export * from "./queries";
+export * from "./types";
diff --git a/frontend/src/hooks/api/pam/recording-config/mutations.tsx b/frontend/src/hooks/api/pam/recording-config/mutations.tsx
new file mode 100644
index 0000000000..139f4ff025
--- /dev/null
+++ b/frontend/src/hooks/api/pam/recording-config/mutations.tsx
@@ -0,0 +1,41 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { pamRecordingConfigKeys } from "./queries";
+import { TPamRecordingConfig, TUpsertPamRecordingConfigDTO } from "./types";
+
+export const useUpsertPamRecordingConfig = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ projectId, ...body }: TUpsertPamRecordingConfigDTO) => {
+ const { data } = await apiRequest.post<{ config: TPamRecordingConfig }>(
+ `/api/v1/pam/projects/${projectId}/recording-config`,
+ body
+ );
+ return data.config;
+ },
+ onSuccess: async (_data, vars) => {
+ await queryClient.invalidateQueries({
+ queryKey: pamRecordingConfigKeys.byProject(vars.projectId)
+ });
+ }
+ });
+};
+
+export const useDeletePamRecordingConfig = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ projectId }: { projectId: string }) => {
+ const { data } = await apiRequest.delete<{ ok: true }>(
+ `/api/v1/pam/projects/${projectId}/recording-config`
+ );
+ return data;
+ },
+ onSuccess: async (_data, vars) => {
+ await queryClient.invalidateQueries({
+ queryKey: pamRecordingConfigKeys.byProject(vars.projectId)
+ });
+ }
+ });
+};
diff --git a/frontend/src/hooks/api/pam/recording-config/queries.tsx b/frontend/src/hooks/api/pam/recording-config/queries.tsx
new file mode 100644
index 0000000000..dae0c12e4e
--- /dev/null
+++ b/frontend/src/hooks/api/pam/recording-config/queries.tsx
@@ -0,0 +1,23 @@
+import { useQuery } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { TPamRecordingConfig } from "./types";
+
+export const pamRecordingConfigKeys = {
+ all: ["pam", "recording-config"] as const,
+ byProject: (projectId: string) =>
+ [...pamRecordingConfigKeys.all, "by-project", projectId] as const
+};
+
+export const useGetPamRecordingConfig = (projectId: string, enabled = true) =>
+ useQuery({
+ queryKey: pamRecordingConfigKeys.byProject(projectId),
+ enabled: Boolean(projectId) && enabled,
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ config: TPamRecordingConfig | null }>(
+ `/api/v1/pam/projects/${projectId}/recording-config`
+ );
+ return data.config;
+ }
+ });
diff --git a/frontend/src/hooks/api/pam/recording-config/types.ts b/frontend/src/hooks/api/pam/recording-config/types.ts
new file mode 100644
index 0000000000..51d0e022d2
--- /dev/null
+++ b/frontend/src/hooks/api/pam/recording-config/types.ts
@@ -0,0 +1,24 @@
+import { TPamRecordingStorageBackend } from "../session-playback/types";
+
+export type { TPamRecordingStorageBackend };
+
+export type TPamRecordingConfig = {
+ id: string;
+ projectId: string;
+ storageBackend: TPamRecordingStorageBackend;
+ connectionId: string;
+ bucket: string;
+ region: string;
+ keyPrefix: string | null;
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type TUpsertPamRecordingConfigDTO = {
+ projectId: string;
+ storageBackend: TPamRecordingStorageBackend;
+ connectionId: string;
+ bucket: string;
+ region: string;
+ keyPrefix?: string | null;
+};
diff --git a/frontend/src/hooks/api/pam/session-playback/decrypt.ts b/frontend/src/hooks/api/pam/session-playback/decrypt.ts
new file mode 100644
index 0000000000..d5f2bf1d59
--- /dev/null
+++ b/frontend/src/hooks/api/pam/session-playback/decrypt.ts
@@ -0,0 +1,224 @@
+// Web Crypto AES-GCM playback decrypt for PAM session recordings
+//
+// Each chunk is encrypted with the per-session key under
+// chunkAad = SHA-256( "{projectId}|{sessionId}|{chunkIndex}|{storageBackend}|v1" )
+// Cross-position or cross-session swaps fail the GCM tag check before we render anything
+//
+// Verification chain:
+// 1. body length matches chunk.ciphertextBytes
+// 2. SHA-256(body) matches chunk.ciphertextSha256 (catches unauthenticated tampering early)
+// 3. AES-GCM decrypt under chunkAad -- final integrity gate
+//
+// Any failure renders a placeholder for that chunk in the player UI
+
+import { TPamPlaybackChunk, TPamRecordingStorageBackend } from "./types";
+
+const PAM_RECORDING_AAD_VERSION = "v1";
+
+const base64ToBytes = (b64: string): Uint8Array => {
+ const bin = atob(b64);
+ const out = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i += 1) out[i] = bin.charCodeAt(i);
+ return out;
+};
+
+const bytesToHex = (bytes: Uint8Array): string =>
+ Array.from(bytes)
+ .map((b) => b.toString(16).padStart(2, "0"))
+ .join("");
+
+const timingSafeEqual = (a: Uint8Array, b: Uint8Array): boolean => {
+ if (a.length !== b.length) return false;
+ let diff = 0;
+ for (let i = 0; i < a.length; i += 1) {
+ // eslint-disable-next-line no-bitwise
+ diff |= a[i] ^ b[i];
+ }
+ return diff === 0;
+};
+
+export type ChunkAadInput = {
+ projectId: string;
+ sessionId: string;
+ chunkIndex: number;
+ storageBackend: TPamRecordingStorageBackend;
+};
+
+export const buildChunkAad = async ({
+ projectId,
+ sessionId,
+ chunkIndex,
+ storageBackend
+}: ChunkAadInput): Promise<Uint8Array> => {
+ const enc = new TextEncoder();
+ const material = enc.encode(
+ `${projectId}|${sessionId}|${chunkIndex}|${storageBackend}|${PAM_RECORDING_AAD_VERSION}`
+ );
+ const digest = await crypto.subtle.digest("SHA-256", material);
+ return new Uint8Array(digest);
+};
+
+const importSessionKey = (rawKey: Uint8Array): Promise<CryptoKey> =>
+ crypto.subtle.importKey("raw", rawKey, { name: "AES-GCM" }, false, ["decrypt"]);
+
+export type DecryptedChunkResult =
+ | { ok: true; chunkIndex: number; plaintext: Uint8Array; events: unknown[] }
+ | {
+ ok: false;
+ chunkIndex: number;
+ reason: "size" | "sha256" | "gcm" | "fetch" | "json";
+ message: string;
+ };
+
+const fetchCiphertext = async (
+ chunk: TPamPlaybackChunk,
+ fallbackUrlBuilder: (chunkIndex: number) => string
+): Promise<Uint8Array> => {
+ const url = chunk.presignedGetUrl ?? fallbackUrlBuilder(chunk.chunkIndex);
+ const resp = await fetch(url, { credentials: chunk.presignedGetUrl ? "omit" : "include" });
+ if (!resp.ok) {
+ throw new Error(`fetch failed: ${resp.status}`);
+ }
+ const buf = await resp.arrayBuffer();
+ return new Uint8Array(buf);
+};
+
+export type DecryptChunkInput = {
+ chunk: TPamPlaybackChunk;
+ sessionKey: CryptoKey;
+ projectId: string;
+ sessionId: string;
+ fallbackUrlBuilder: (chunkIndex: number) => string;
+};
+
+export const decryptOneChunk = async ({
+ chunk,
+ sessionKey,
+ projectId,
+ sessionId,
+ fallbackUrlBuilder
+}: DecryptChunkInput): Promise<DecryptedChunkResult> => {
+ let body: Uint8Array;
+ try {
+ body = await fetchCiphertext(chunk, fallbackUrlBuilder);
+ } catch (err) {
+ return {
+ ok: false,
+ chunkIndex: chunk.chunkIndex,
+ reason: "fetch",
+ message: (err as Error)?.message ?? "fetch failed"
+ };
+ }
+
+ if (body.length !== chunk.ciphertextBytes) {
+ return {
+ ok: false,
+ chunkIndex: chunk.chunkIndex,
+ reason: "size",
+ message: `body length ${body.length} does not match declared ${chunk.ciphertextBytes}`
+ };
+ }
+
+ let expectedSha: Uint8Array;
+ try {
+ expectedSha = base64ToBytes(chunk.ciphertextSha256);
+ } catch {
+ return {
+ ok: false,
+ chunkIndex: chunk.chunkIndex,
+ reason: "sha256",
+ message: "invalid base64 in ciphertextSha256"
+ };
+ }
+
+ const actualShaBuf = await crypto.subtle.digest("SHA-256", body);
+ const actualSha = new Uint8Array(actualShaBuf);
+ if (!timingSafeEqual(expectedSha, actualSha)) {
+ return {
+ ok: false,
+ chunkIndex: chunk.chunkIndex,
+ reason: "sha256",
+ message: `sha256 mismatch (expected ${bytesToHex(expectedSha).slice(0, 16)}…, got ${bytesToHex(actualSha).slice(0, 16)}…)`
+ };
+ }
+
+ let iv: Uint8Array;
+ try {
+ iv = base64ToBytes(chunk.iv);
+ } catch {
+ return {
+ ok: false,
+ chunkIndex: chunk.chunkIndex,
+ reason: "gcm",
+ message: "invalid base64 in iv"
+ };
+ }
+ const aad = await buildChunkAad({
+ projectId,
+ sessionId,
+ chunkIndex: chunk.chunkIndex,
+ storageBackend: chunk.storageBackend
+ });
+
+ let plaintextBuf: ArrayBuffer;
+ try {
+ plaintextBuf = await crypto.subtle.decrypt(
+ { name: "AES-GCM", iv, additionalData: aad },
+ sessionKey,
+ body
+ );
+ } catch (err) {
+ return {
+ ok: false,
+ chunkIndex: chunk.chunkIndex,
+ reason: "gcm",
+ message: (err as Error)?.message ?? "AES-GCM decrypt failed"
+ };
+ }
+
+ const plaintext = new Uint8Array(plaintextBuf);
+ let events: unknown[];
+ try {
+ const decoder = new TextDecoder();
+ const parsed = JSON.parse(decoder.decode(plaintext));
+ if (!Array.isArray(parsed)) {
+ return {
+ ok: false,
+ chunkIndex: chunk.chunkIndex,
+ reason: "json",
+ message: "plaintext is not a JSON array"
+ };
+ }
+ events = parsed;
+ } catch (err) {
+ return {
+ ok: false,
+ chunkIndex: chunk.chunkIndex,
+ reason: "json",
+ message: (err as Error)?.message ?? "plaintext is not valid JSON"
+ };
+ }
+
+ return { ok: true, chunkIndex: chunk.chunkIndex, plaintext, events };
+};
+
+export const importSessionKeyFromBase64 = async (b64: string): Promise<CryptoKey> => {
+ const raw = base64ToBytes(b64);
+ if (raw.length !== 32) throw new Error(`expected 32-byte session key, got ${raw.length}`);
+ return importSessionKey(raw);
+};
+
+// detectChunkGaps walks the chunkIndex sequence and returns the indices of any missing chunks
+export const detectChunkGaps = (chunks: TPamPlaybackChunk[]): number[] => {
+ const present = new Set(chunks.map((c) => c.chunkIndex));
+ if (present.size === 0) return [];
+ let max = 0;
+ present.forEach((idx) => {
+ if (idx > max) max = idx;
+ });
+ const gaps: number[] = [];
+ for (let i = 0; i <= max; i += 1) {
+ if (!present.has(i)) gaps.push(i);
+ }
+ return gaps;
+};
diff --git a/frontend/src/hooks/api/pam/session-playback/index.ts b/frontend/src/hooks/api/pam/session-playback/index.ts
new file mode 100644
index 0000000000..d8d57871fd
--- /dev/null
+++ b/frontend/src/hooks/api/pam/session-playback/index.ts
@@ -0,0 +1,3 @@
+export * from "./decrypt";
+export * from "./queries";
+export * from "./types";
diff --git a/frontend/src/hooks/api/pam/session-playback/queries.tsx b/frontend/src/hooks/api/pam/session-playback/queries.tsx
new file mode 100644
index 0000000000..6ec5114c07
--- /dev/null
+++ b/frontend/src/hooks/api/pam/session-playback/queries.tsx
@@ -0,0 +1,192 @@
+import { useEffect, useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { decryptOneChunk, detectChunkGaps, importSessionKeyFromBase64 } from "./decrypt";
+import { TBrokenChunkMarker, TPamPlaybackBundle } from "./types";
+
+export const pamPlaybackKeys = {
+ all: ["pam", "playback"] as const,
+ bundle: (sessionId: string) => [...pamPlaybackKeys.all, "bundle", sessionId] as const
+};
+
+const fetchBundle = async (sessionId: string): Promise<TPamPlaybackBundle> => {
+ const { data } = await apiRequest.get<TPamPlaybackBundle>(
+ `/api/v1/pam/sessions/${sessionId}/playback`
+ );
+ return data;
+};
+
+export const useGetPamSessionPlaybackBundle = (sessionId: string, enabled = true) =>
+ useQuery({
+ queryKey: pamPlaybackKeys.bundle(sessionId),
+ enabled: Boolean(sessionId) && enabled,
+ queryFn: () => fetchBundle(sessionId),
+ staleTime: 0,
+ gcTime: 0
+ });
+
+export type DecryptedChunkRecord = {
+ chunkIndex: number;
+ events: unknown[];
+};
+
+export type PlaybackDecryptState = {
+ legacy: boolean;
+ loading: boolean;
+ error?: string;
+ events: unknown[];
+ brokenChunks: { chunkIndex: number; reason: string; message: string }[];
+ missingChunks: number[];
+ totalChunks: number;
+};
+
+const fallbackUrlBuilderFor = (sessionId: string) => (chunkIndex: number) =>
+ `/api/v1/pam/sessions/${sessionId}/chunks/${chunkIndex}/ciphertext`;
+
+export const useDecryptedSessionLogs = (
+ sessionId: string,
+ enabled = true
+): PlaybackDecryptState => {
+ const bundleQuery = useGetPamSessionPlaybackBundle(sessionId, enabled);
+ const bundle = bundleQuery.data;
+ const [state, setState] = useState<PlaybackDecryptState>({
+ legacy: false,
+ loading: true,
+ events: [],
+ brokenChunks: [],
+ missingChunks: [],
+ totalChunks: 0
+ });
+
+ const fallbackUrlBuilder = useMemo(() => fallbackUrlBuilderFor(sessionId), [sessionId]);
+
+ useEffect(() => {
+ if (!enabled || !bundle) return undefined;
+ let cancelled = false;
+
+ const run = async () => {
+ // Legacy path: backend has not been upgraded for this session, so we have no session key
+ // Fall back to the existing /logs endpoint via the consumer
+ if (bundle.legacy) {
+ if (!cancelled) {
+ setState({
+ legacy: true,
+ loading: false,
+ events: [],
+ brokenChunks: [],
+ missingChunks: [],
+ totalChunks: 0
+ });
+ }
+ return;
+ }
+
+ if (!bundle.sessionKey) {
+ if (!cancelled) {
+ setState((s) => ({
+ ...s,
+ loading: false,
+ error: "Missing session key in playback bundle"
+ }));
+ }
+ return;
+ }
+
+ let sessionKey: CryptoKey;
+ try {
+ sessionKey = await importSessionKeyFromBase64(bundle.sessionKey);
+ } catch (err) {
+ if (!cancelled) {
+ setState((s) => ({
+ ...s,
+ loading: false,
+ error: `Invalid session key: ${(err as Error).message}`
+ }));
+ }
+ return;
+ }
+
+ const projectId = bundle.projectId ?? "";
+ const sortedChunks = [...bundle.chunks].sort((a, b) => a.chunkIndex - b.chunkIndex);
+ const missingChunks = detectChunkGaps(sortedChunks);
+ const missingSet = new Set(missingChunks);
+
+ const events: unknown[] = [];
+ const brokenChunks: PlaybackDecryptState["brokenChunks"] = [];
+ let chunkIdx = 0;
+
+ const maxIndex = sortedChunks.length ? sortedChunks[sortedChunks.length - 1].chunkIndex : 0;
+
+ for (let i = 0; i <= maxIndex; i += 1) {
+ if (cancelled) return;
+
+ if (missingSet.has(i)) {
+ const marker: TBrokenChunkMarker = {
+ __brokenChunk: true,
+ chunkIndex: i,
+ reason: "missing",
+ message: "This chunk was not found in the recording"
+ };
+ events.push(marker);
+ brokenChunks.push(marker);
+ } else {
+ // eslint-disable-next-line no-await-in-loop
+ const r = await decryptOneChunk({
+ chunk: sortedChunks[chunkIdx],
+ sessionKey,
+ projectId,
+ sessionId,
+ fallbackUrlBuilder
+ });
+ chunkIdx += 1;
+ if (r.ok) {
+ events.push(...r.events);
+ } else {
+ const marker: TBrokenChunkMarker = {
+ __brokenChunk: true,
+ chunkIndex: r.chunkIndex,
+ reason: r.reason,
+ message: r.message
+ };
+ events.push(marker);
+ brokenChunks.push(marker);
+ }
+ }
+
+ setState({
+ legacy: false,
+ loading: true,
+ events: [...events],
+ brokenChunks: [...brokenChunks],
+ missingChunks,
+ totalChunks: sortedChunks.length
+ });
+ }
+
+ if (cancelled) return;
+
+ setState({
+ legacy: false,
+ loading: false,
+ events,
+ brokenChunks,
+ missingChunks,
+ totalChunks: sortedChunks.length
+ });
+ };
+
+ run().catch((err) => {
+ if (!cancelled) {
+ setState((s) => ({ ...s, loading: false, error: (err as Error).message }));
+ }
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [bundle, enabled, sessionId, fallbackUrlBuilder]);
+
+ return state;
+};
diff --git a/frontend/src/hooks/api/pam/session-playback/types.ts b/frontend/src/hooks/api/pam/session-playback/types.ts
new file mode 100644
index 0000000000..0a734c5160
--- /dev/null
+++ b/frontend/src/hooks/api/pam/session-playback/types.ts
@@ -0,0 +1,36 @@
+export type TPamRecordingStorageBackend = "postgres" | "aws-s3";
+
+export type TPamPlaybackChunk = {
+ chunkIndex: number;
+ startElapsedMs: number;
+ endElapsedMs: number;
+ storageBackend: TPamRecordingStorageBackend;
+ externalChunkObjectKey: string | null;
+ ciphertextSha256: string;
+ ciphertextBytes: number;
+ iv: string;
+ presignedGetUrl: string | null;
+};
+
+export type TPamPlaybackBundle = {
+ legacy: boolean;
+ sessionKey: string | null;
+ projectId?: string;
+ storageBackend?: TPamRecordingStorageBackend;
+ chunks: TPamPlaybackChunk[];
+};
+
+export type TBrokenChunkMarker = {
+ __brokenChunk: true;
+ chunkIndex: number;
+ reason: string;
+ message: string;
+};
+
+export const isBrokenChunkMarker = (event: unknown): event is TBrokenChunkMarker =>
+ typeof event === "object" &&
+ event !== null &&
+ // eslint-disable-next-line no-underscore-dangle
+ (event as Record<string, unknown>).__brokenChunk === true &&
+ typeof (event as Record<string, unknown>).chunkIndex === "number" &&
+ typeof (event as Record<string, unknown>).reason === "string";
diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.ts
index ca88f6117d..f30e170d2a 100644
--- a/frontend/src/hooks/api/pam/types/index.ts
+++ b/frontend/src/hooks/api/pam/types/index.ts
@@ -122,7 +122,6 @@ export type TPamSession = {
endedAt?: string | null;
createdAt: string;
updatedAt: string;
- logs: TPamSessionLog[];
gatewayIdentityId?: string | null;
gatewayId?: string | null;
aiInsightsStatus?: string | null;
diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/PamNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/PamNav.tsx
index 2c43ce3110..e6031de665 100644
--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/PamNav.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/PamNav.tsx
@@ -11,7 +11,11 @@ import {
} from "lucide-react";
import { ProjectNavList } from "./ProjectNavLink";
-import { PAM_APPROVALS_SUBMENU, PROJECT_ACCESS_CONTROL_SUBMENU } from "./submenus";
+import {
+ PAM_APPROVALS_SUBMENU,
+ PAM_SETTINGS_SUBMENU,
+ PROJECT_ACCESS_CONTROL_SUBMENU
+} from "./submenus";
import type { NavItem, Submenu } from "./types";
export const PamNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: Submenu) => void }) => {
@@ -36,7 +40,12 @@ export const PamNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: Submenu) =>
submenu: PROJECT_ACCESS_CONTROL_SUBMENU
},
{ label: "Audit Logs", icon: FileText, pathSuffix: "audit-logs" },
- { label: "Settings", icon: Settings, pathSuffix: "settings" }
+ {
+ label: "Settings",
+ icon: Settings,
+ pathSuffix: "settings",
+ submenu: PAM_SETTINGS_SUBMENU
+ }
];
return <ProjectNavList items={items} onSubmenuOpen={onSubmenuOpen} />;
};
diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNav.tsx
index 399e4e6ed5..7203d2a48f 100644
--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNav.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNav.tsx
@@ -23,6 +23,7 @@ import {
INTEGRATIONS_SUBMENU,
MCP_SUBMENU,
PAM_APPROVALS_SUBMENU,
+ PAM_SETTINGS_SUBMENU,
PROJECT_ACCESS_CONTROL_SUBMENU,
SECRET_MANAGER_ACCESS_CONTROL_SUBMENU,
SECRET_SCANNING_SETTINGS_SUBMENU,
@@ -86,6 +87,7 @@ export const ProjectNav = () => {
if (isOnProjectSettings && isCertManager) return CERT_SETTINGS_SUBMENU;
if (isOnProjectSettings && currentProject.type === ProjectType.SecretScanning)
return SECRET_SCANNING_SETTINGS_SUBMENU;
+ if (isOnProjectSettings && currentProject.type === ProjectType.PAM) return PAM_SETTINGS_SUBMENU;
if (isOnMcpOverview) return MCP_SUBMENU;
if (isOnCertPolicies) return CERT_CERTIFICATES_SUBMENU;
if (isOnCertDiscovery) return CERT_DISCOVERY_SUBMENU;
diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/submenus.ts b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/submenus.ts
index a514b31095..b814da5e15 100644
--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/submenus.ts
+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/submenus.ts
@@ -29,7 +29,8 @@ import {
ShieldUser,
Trash2,
User,
- Users
+ Users,
+ Video
} from "lucide-react";
import { SubOrgIcon } from "@app/components/v3";
@@ -244,6 +245,16 @@ export const PAM_APPROVALS_SUBMENU: Submenu = {
]
};
+export const PAM_SETTINGS_SUBMENU: Submenu = {
+ title: "Settings",
+ pathSuffix: "settings",
+ defaultTab: "tab-project-general",
+ items: [
+ { label: "General", icon: Cog, tab: "tab-project-general" },
+ { label: "Session Recording", icon: Video, tab: "tab-pam-session-recording" }
+ ]
+};
+
// --- AI submenus ---
export const MCP_SUBMENU: Submenu = {
diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/CommandLogView.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/CommandLogView.tsx
index c3fea74399..a9418e48f7 100644
--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/CommandLogView.tsx
+++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/CommandLogView.tsx
@@ -7,11 +7,12 @@ import { createNotification } from "@app/components/notifications";
import { Input } from "@app/components/v2";
import { HighlightText } from "@app/components/v2/HighlightText";
import { TPamCommandLog } from "@app/hooks/api/pam";
+import { isBrokenChunkMarker, TBrokenChunkMarker } from "@app/hooks/api/pam/session-playback";
import { formatLogContent } from "./PamSessionLogsSection.utils";
type Props = {
- logs: TPamCommandLog[];
+ logs: (TPamCommandLog | TBrokenChunkMarker)[];
scrollToLogIndex?: number;
};
@@ -41,7 +42,9 @@ export const CommandLogView = ({ logs, scrollToLogIndex }: Props) => {
}
handledScrollIndexRef.current = scrollToLogIndex;
setSearch("");
- setExpandedLogTimestamps(new Set([target.timestamp]));
+ if (!isBrokenChunkMarker(target)) {
+ setExpandedLogTimestamps(new Set([target.timestamp]));
+ }
setTimeout(() => {
document
.getElementById(`log-${scrollToLogIndex}`)
@@ -61,6 +64,7 @@ export const CommandLogView = ({ logs, scrollToLogIndex }: Props) => {
const filteredLogs = useMemo(
() =>
logs.filter((log) => {
+ if (isBrokenChunkMarker(log)) return true;
const searchValue = search.trim().toLowerCase();
return (
log.input.toLowerCase().includes(searchValue) ||
@@ -85,11 +89,25 @@ export const CommandLogView = ({ logs, scrollToLogIndex }: Props) => {
<div className="flex grow flex-col gap-2 overflow-y-auto text-xs">
{filteredLogs.length > 0 ? (
- filteredLogs.map((log) => {
+ filteredLogs.map((log, idx) => {
+ if (isBrokenChunkMarker(log)) {
+ return (
+ <div
+ key={`broken-${log.chunkIndex}`}
+ className="flex items-center gap-2 rounded-md border border-warning/30 bg-warning/5 px-3 py-2 text-xs text-warning"
+ >
+ <span>
+ Chunk {log.chunkIndex} is unavailable ({log.reason}). Some log entries may be
+ missing here.
+ </span>
+ </div>
+ );
+ }
+
const originalIndex = logs.indexOf(log) + 1;
const isExpanded = search.length || expandedLogTimestamps.has(log.timestamp);
const formattedInput = formatLogContent(log.input);
- const logKey = `${log.timestamp}-${originalIndex}`;
+ const logKey = `${log.timestamp}-${idx}`;
return (
<button
diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/HttpEventView.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/HttpEventView.tsx
index 56ee82fc65..9403159985 100644
--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/HttpEventView.tsx
+++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/HttpEventView.tsx
@@ -5,9 +5,10 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Input } from "@app/components/v2";
import { HighlightText } from "@app/components/v2/HighlightText";
import { THttpEvent } from "@app/hooks/api/pam";
+import { isBrokenChunkMarker, TBrokenChunkMarker } from "@app/hooks/api/pam/session-playback";
type Props = {
- events: THttpEvent[];
+ events: (THttpEvent | TBrokenChunkMarker)[];
};
export const HttpEventView = ({ events }: Props) => {
@@ -59,6 +60,7 @@ export const HttpEventView = ({ events }: Props) => {
const filteredEvents = useMemo(
() =>
events.filter((event) => {
+ if (isBrokenChunkMarker(event)) return true;
const searchValue = search.trim().toLowerCase();
if (!searchValue) return true;
@@ -175,6 +177,20 @@ export const HttpEventView = ({ events }: Props) => {
<div className="flex grow flex-col gap-2 overflow-y-auto text-xs">
{filteredEvents.length > 0 ? (
filteredEvents.map((event, index) => {
+ if (isBrokenChunkMarker(event)) {
+ return (
+ <div
+ key={`broken-${event.chunkIndex}`}
+ className="flex items-center gap-2 rounded-md border border-warning/30 bg-warning/5 px-3 py-2 text-xs text-warning"
+ >
+ <span>
+ Chunk {event.chunkIndex} is unavailable ({event.reason}). Some events may be
+ missing here.
+ </span>
+ </div>
+ );
+ }
+
const eventKey = `${event.timestamp}-${event.requestId}-${index}`;
const isRequest = event.eventType === "request";
const kubectlCommand = getKubectlCommand(event.headers);
diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx
index 2be0bfd058..f0814957a5 100644
--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx
+++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx
@@ -1,7 +1,6 @@
-import { faUpRightFromSquare } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { ExternalLinkIcon, Loader2Icon } from "lucide-react";
-import { Button } from "@app/components/v2";
+import { Button } from "@app/components/v3";
import {
PamResourceType,
PamSessionStatus,
@@ -11,6 +10,7 @@ import {
TTerminalEvent,
useGetPamSessionLogs
} from "@app/hooks/api/pam";
+import { useDecryptedSessionLogs } from "@app/hooks/api/pam/session-playback";
import { CommandLogView } from "./CommandLogView";
import { HttpEventView } from "./HttpEventView";
@@ -25,10 +25,16 @@ export const PamSessionLogsSection = ({ session, scrollToLogIndex }: Props) => {
const isActive =
session.status === PamSessionStatus.Active || session.status === PamSessionStatus.Starting;
- const { logs, isLoading, hasMore, loadMore, isLoadingMore } = useGetPamSessionLogs(
- session.id,
- isActive
- );
+ const playback = useDecryptedSessionLogs(session.id, true);
+ const isLegacyOrNoChunks = playback.legacy || (!playback.loading && playback.totalChunks === 0);
+
+ const legacy = useGetPamSessionLogs(session.id, isActive && isLegacyOrNoChunks);
+
+ const logs = isLegacyOrNoChunks ? legacy.logs : (playback.events as typeof legacy.logs);
+ const isLoading = isLegacyOrNoChunks ? legacy.isLoading : playback.loading;
+ const hasMore = isLegacyOrNoChunks ? legacy.hasMore : false;
+ const loadMore = isLegacyOrNoChunks ? legacy.loadMore : () => {};
+ const isLoadingMore = isLegacyOrNoChunks ? legacy.isLoadingMore : false;
const isSSHSession = session.resourceType === PamResourceType.SSH;
const isDatabaseSession =
@@ -42,47 +48,56 @@ export const PamSessionLogsSection = ({ session, scrollToLogIndex }: Props) => {
const hasLogs = logs.length > 0;
return (
- <div className="flex h-full w-full flex-col gap-4 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <div className="flex items-center gap-3 border-b border-mineshaft-400 pb-4">
- <h3 className="text-lg font-medium text-mineshaft-100">Session Logs</h3>
+ <div className="flex h-full w-full flex-col gap-4 rounded-lg border border-border bg-container p-4">
+ <div className="flex items-center gap-3 border-b border-border pb-4">
+ <h3 className="text-lg font-medium text-foreground">Session Logs</h3>
{isActive && (
- <span className="flex animate-pulse items-center gap-1.5 rounded-full bg-green-900/40 px-2.5 py-1 text-xs font-medium text-green-400">
- <span className="size-1.5 animate-pulse rounded-full bg-green-400" />
+ <span className="flex animate-pulse items-center gap-1.5 rounded-full bg-success/10 px-2.5 py-1 text-xs font-medium text-success">
+ <span className="size-1.5 animate-pulse rounded-full bg-success" />
LIVE
</span>
)}
</div>
+ {isLoading && !hasLogs && (
+ <div className="flex grow items-center justify-center">
+ <div className="flex items-center gap-2 text-sm text-muted">
+ <Loader2Icon className="size-4 animate-spin" />
+ <span>Fetching and decrypting logs...</span>
+ </div>
+ </div>
+ )}
+
{isDatabaseSession && hasLogs && (
<CommandLogView logs={logs as TPamCommandLog[]} scrollToLogIndex={scrollToLogIndex} />
)}
{isSSHSession && hasLogs && <TerminalEventView events={logs as TTerminalEvent[]} />}
{isHttpSession && hasLogs && <HttpEventView events={logs as THttpEvent[]} />}
{isAwsIamSession && (
- <div className="flex grow items-center justify-center text-bunker-300">
+ <div className="flex grow items-center justify-center text-muted">
<div className="text-center">
<div className="mb-2">AWS Console session activity is logged in AWS CloudTrail</div>
- <div className="text-xs text-bunker-400">
+ <div className="text-xs text-muted">
View detailed activity logs for this session in your AWS CloudTrail console.
<br />
<a
href="https://console.aws.amazon.com/cloudtrail"
target="_blank"
rel="noopener noreferrer"
- className="mt-2 inline-flex items-center gap-1 text-primary-400 hover:text-primary-300"
+ className="mt-2 inline-flex items-center gap-1 text-info hover:text-info/80"
>
Open AWS CloudTrail
- <FontAwesomeIcon icon={faUpRightFromSquare} className="size-3" />
+ <ExternalLinkIcon className="size-3" />
</a>
</div>
</div>
</div>
)}
{!hasLogs && !isAwsIamSession && !isLoading && (
- <div className="flex grow items-center justify-center text-bunker-300">
+ <div className="flex grow items-center justify-center text-muted">
<div className="text-center">
<div className="mb-2">Session logs are not yet available</div>
- <div className="text-xs text-bunker-400">
+ <div className="text-xs text-muted">
Logs will be uploaded after the session duration has elapsed.
<br />
If logs do not appear after some time, please contact your Gateway administrators.
@@ -93,7 +108,7 @@ export const PamSessionLogsSection = ({ session, scrollToLogIndex }: Props) => {
{!isActive && hasMore && !isAwsIamSession && (
<div className="flex justify-center pt-2">
- <Button variant="outline_bg" size="xs" isLoading={isLoadingMore} onClick={loadMore}>
+ <Button variant="outline" size="xs" isPending={isLoadingMore} onClick={loadMore}>
Load more
</Button>
</div>
diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/TerminalEventView.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/TerminalEventView.tsx
index 3ed77e1fc6..f290e8c811 100644
--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/TerminalEventView.tsx
+++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/TerminalEventView.tsx
@@ -5,6 +5,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Input } from "@app/components/v2";
import { HighlightText } from "@app/components/v2/HighlightText";
import { TerminalChannelType, TTerminalEvent } from "@app/hooks/api/pam";
+import { isBrokenChunkMarker, TBrokenChunkMarker } from "@app/hooks/api/pam/session-playback";
import { aggregateTerminalEvents } from "./terminal-utils";
@@ -14,13 +15,20 @@ const CHANNEL_LABEL_MAP: Record<string, string> = {
};
type Props = {
- events: TTerminalEvent[];
+ events: (TTerminalEvent | TBrokenChunkMarker)[];
};
export const TerminalEventView = ({ events }: Props) => {
const [search, setSearch] = useState("");
- const aggregatedEvents = useMemo(() => aggregateTerminalEvents(events), [events]);
+ const markers = useMemo(() => events.filter(isBrokenChunkMarker), [events]);
+
+ const realEvents = useMemo(
+ () => events.filter((e): e is TTerminalEvent => !isBrokenChunkMarker(e)),
+ [events]
+ );
+
+ const aggregatedEvents = useMemo(() => aggregateTerminalEvents(realEvents), [realEvents]);
const filteredEvents = useMemo(
() =>
@@ -46,6 +54,15 @@ export const TerminalEventView = ({ events }: Props) => {
</div>
<div className="flex grow flex-col gap-2 overflow-y-auto text-xs">
+ {markers.length > 0 && (
+ <div className="flex items-center gap-2 rounded-md border border-warning/30 bg-warning/5 px-3 py-2 text-xs text-warning">
+ <span>
+ {markers.length} chunk(s) unavailable (
+ {Array.from(new Set(markers.map((m) => m.reason))).join(", ")}). Some terminal output
+ may be missing.
+ </span>
+ </div>
+ )}
{filteredEvents.length > 0 ? (
filteredEvents.map((event, index) => {
const eventKey = `${event.timestamp}-${index}`;
diff --git a/frontend/src/pages/pam/PamSessionsPage/PamSessionsPage.tsx b/frontend/src/pages/pam/PamSessionsPage/PamSessionsPage.tsx
index 198d6f42e6..18a6d05ef5 100644
--- a/frontend/src/pages/pam/PamSessionsPage/PamSessionsPage.tsx
+++ b/frontend/src/pages/pam/PamSessionsPage/PamSessionsPage.tsx
@@ -27,7 +27,7 @@ export const PamSessionPage = () => {
<PageHeader
scope={ProjectType.PAM}
title="Sessions"
- description="Filter and search through account sessions."
+ description="View and filter account sessions."
/>
<PamSessionSection />
</div>
diff --git a/frontend/src/pages/pam/PamSessionsPage/components/PamSessionRow.tsx b/frontend/src/pages/pam/PamSessionsPage/components/PamSessionRow.tsx
index f66377a9c5..ca07661bc6 100644
--- a/frontend/src/pages/pam/PamSessionsPage/components/PamSessionRow.tsx
+++ b/frontend/src/pages/pam/PamSessionsPage/components/PamSessionRow.tsx
@@ -1,12 +1,5 @@
-import { useMemo, useState } from "react";
-import {
- faBoxOpen,
- faChevronDown,
- faChevronUp,
- faEdit,
- faEllipsisV,
- faTerminal
-} from "@fortawesome/free-solid-svg-icons";
+import { useState } from "react";
+import { faBoxOpen, faEdit, faEllipsisV } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useNavigate } from "@tanstack/react-router";
import { GavelIcon } from "lucide-react";
@@ -14,7 +7,6 @@ import { twMerge } from "tailwind-merge";
import { ProjectPermissionCan } from "@app/components/permissions";
import {
- Button,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
@@ -24,35 +16,24 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
-import { HighlightText } from "@app/components/v2/HighlightText";
import {
ProjectPermissionActions,
ProjectPermissionPamSessionActions,
ProjectPermissionSub,
useOrganization
} from "@app/context";
-import {
- PAM_RESOURCE_TYPE_MAP,
- PamSessionStatus,
- TPamSession,
- TTerminalEvent
-} from "@app/hooks/api/pam";
+import { PAM_RESOURCE_TYPE_MAP, PamSessionStatus, TPamSession } from "@app/hooks/api/pam";
import { PamTerminateSessionModal } from "../../components/PamTerminateSessionModal";
-import { formatLogContent } from "../../PamSessionsByIDPage/components/PamSessionLogsSection.utils";
-import { aggregateTerminalEvents } from "../../PamSessionsByIDPage/components/terminal-utils";
import { PamSessionStatusBadge } from "./PamSessionStatusBadge";
type Props = {
session: TPamSession;
- search: string;
- filteredLogs: TPamSession["logs"];
};
-export const PamSessionRow = ({ session, search, filteredLogs }: Props) => {
+export const PamSessionRow = ({ session }: Props) => {
const navigate = useNavigate();
const { currentOrg } = useOrganization();
- const [showAllLogs, setShowAllLogs] = useState(false);
const [isTerminateDialogOpen, setIsTerminateDialogOpen] = useState(false);
const {
@@ -75,25 +56,6 @@ export const PamSessionRow = ({ session, search, filteredLogs }: Props) => {
const { image, name: resourceTypeName } = PAM_RESOURCE_TYPE_MAP[resourceType];
- // Check if logs are terminal events and aggregate them
- const processedLogs = useMemo(() => {
- if (filteredLogs.length === 0) return [];
-
- // Check if first log is a terminal event
- const isTerminalEvents = "data" in filteredLogs[0];
-
- if (isTerminalEvents) {
- // Aggregate terminal events for better display
- return aggregateTerminalEvents(filteredLogs as TTerminalEvent[]);
- }
-
- // Return command logs as-is
- return filteredLogs;
- }, [filteredLogs]);
-
- const LOGS_TO_SHOW = 5;
- const logsToShow = showAllLogs ? processedLogs : processedLogs.slice(0, LOGS_TO_SHOW);
-
return (
<>
<Tr
@@ -116,14 +78,10 @@ export const PamSessionRow = ({ session, search, filteredLogs }: Props) => {
</div>
<div className="flex items-center gap-2">
<div className="flex flex-col">
- <span>
- <HighlightText text={accountName} highlight={search} />
- </span>
+ <span>{accountName}</span>
<div className="flex items-center gap-1 text-xs text-bunker-300">
<FontAwesomeIcon icon={faBoxOpen} className="size-3" />
- <span>
- <HighlightText text={resourceName} highlight={search} />
- </span>
+ <span>{resourceName}</span>
</div>
</div>
</div>
@@ -131,12 +89,8 @@ export const PamSessionRow = ({ session, search, filteredLogs }: Props) => {
</Td>
<Td>
<div className="flex flex-col">
- <span>
- <HighlightText text={actorName} highlight={search} />
- </span>
- <span className="text-xs text-bunker-300">
- <HighlightText text={actorEmail} highlight={search} />
- </span>
+ <span>{actorName}</span>
+ <span className="text-xs text-bunker-300">{actorEmail}</span>
</div>
</Td>
<Td>
@@ -227,74 +181,6 @@ export const PamSessionRow = ({ session, search, filteredLogs }: Props) => {
isOpen={isTerminateDialogOpen}
onOpenChange={setIsTerminateDialogOpen}
/>
-
- {filteredLogs.length > 0 && (
- <Tr>
- <Td colSpan={5} className="py-3 text-xs">
- {logsToShow.map((log) => {
- // Handle command logs (database sessions)
- if ("input" in log && "output" in log) {
- const formattedInput = formatLogContent(log.input);
-
- return (
- <div
- key={`${id}-log-${log.timestamp}`}
- className="mb-4 flex flex-col gap-1 last:mb-0"
- >
- <div className="flex items-center gap-1.5 text-bunker-400">
- <FontAwesomeIcon icon={faTerminal} className="size-3" />
- <span>{new Date(log.timestamp).toLocaleString()}</span>
- </div>
-
- <div className="font-mono break-all whitespace-pre-wrap">
- <HighlightText text={formattedInput} highlight={search} />
- </div>
- <div className="font-mono text-bunker-300">
- <HighlightText text={log.output.trim()} highlight={search} />
- </div>
- </div>
- );
- }
-
- // Handle aggregated terminal events (SSH sessions)
- if ("data" in log && typeof log.data === "string") {
- return (
- <div
- key={`${id}-log-${log.timestamp}`}
- className="mb-4 flex flex-col gap-1 last:mb-0"
- >
- <div className="flex items-center gap-1.5 text-bunker-400">
- <FontAwesomeIcon icon={faTerminal} className="size-3" />
- <span>{new Date(log.timestamp).toLocaleString()}</span>
- </div>
-
- <div className="font-mono break-all whitespace-pre-wrap text-bunker-300">
- <HighlightText text={log.data.trim()} highlight={search} />
- </div>
- </div>
- );
- }
-
- return null;
- })}
- {filteredLogs.length > LOGS_TO_SHOW && (
- <div className="mt-2">
- <Button
- variant="link"
- size="xs"
- leftIcon={<FontAwesomeIcon icon={showAllLogs ? faChevronUp : faChevronDown} />}
- onClick={() => setShowAllLogs(!showAllLogs)}
- className="p-0 text-mineshaft-300 hover:text-primary"
- >
- {showAllLogs
- ? "Show less"
- : `Show ${filteredLogs.length - LOGS_TO_SHOW} more log${filteredLogs.length - LOGS_TO_SHOW === 1 ? "" : "s"}`}
- </Button>
- </div>
- )}
- </Td>
- </Tr>
- )}
</>
);
};
diff --git a/frontend/src/pages/pam/PamSessionsPage/components/PamSessionsTable.tsx b/frontend/src/pages/pam/PamSessionsPage/components/PamSessionsTable.tsx
index 63cc226511..e38a622a63 100644
--- a/frontend/src/pages/pam/PamSessionsPage/components/PamSessionsTable.tsx
+++ b/frontend/src/pages/pam/PamSessionsPage/components/PamSessionsTable.tsx
@@ -1,26 +1,13 @@
import { useEffect, useMemo, useState } from "react";
import { faCircleXmark } from "@fortawesome/free-regular-svg-icons";
-import {
- faArrowDown,
- faArrowUp,
- faCheckCircle,
- faFilter,
- faMagnifyingGlass,
- faSearch
-} from "@fortawesome/free-solid-svg-icons";
+import { faArrowDown, faArrowUp, faSearch } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { useNavigate, useSearch } from "@tanstack/react-router";
+import { FilterIcon } from "lucide-react";
import { twMerge } from "tailwind-merge";
import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuTrigger,
EmptyState,
- IconButton,
- Input,
+ IconButton as IconButtonV2,
Pagination,
Table,
TableContainer,
@@ -29,7 +16,18 @@ import {
THead,
Tr
} from "@app/components/v2";
-import { ROUTE_PATHS } from "@app/const/routes";
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ IconButton,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
import { usePagination, useResetPageHelper } from "@app/hooks";
import { OrderByDirection } from "@app/hooks/api/generic/types";
import {
@@ -58,20 +56,12 @@ type Props = {
};
export const PamSessionsTable = ({ sessions }: Props) => {
- const navigate = useNavigate({ from: ROUTE_PATHS.Pam.SessionsPage.path });
-
- const { search: initSearch } = useSearch({
- from: ROUTE_PATHS.Pam.SessionsPage.id
- });
-
const [filters, setFilters] = useState<Filters>({
resourceType: [],
status: []
});
const {
- search,
- setSearch,
setPage,
page,
perPage,
@@ -83,90 +73,18 @@ export const PamSessionsTable = ({ sessions }: Props) => {
setOrderDirection,
setOrderBy
} = usePagination<OrderBy>(OrderBy.CreatedAt, {
- initPerPage: 20,
- initSearch
+ initPerPage: 20
});
useEffect(() => {
setOrderDirection(OrderByDirection.DESC);
}, []);
- const sessionsWithMatches = useMemo(() => {
- const searchValue = search.trim().toLowerCase();
-
- if (!searchValue) {
- return sessions.map((session) => ({
- session,
- isMatch: true,
- filteredLogs: []
- }));
- }
-
- return sessions.map((session) => {
- const {
- resourceType,
- accountName,
- actorEmail,
- actorIp,
- actorName,
- actorUserAgent,
- id,
- resourceName,
- userId,
- logs
- } = session;
-
- const { name: resourceTypeName } = PAM_RESOURCE_TYPE_MAP[resourceType];
-
- const isMetaMatch =
- resourceTypeName.toLowerCase().includes(searchValue) ||
- accountName.toLowerCase().includes(searchValue) ||
- actorEmail.toLowerCase().includes(searchValue) ||
- actorIp.toLowerCase().includes(searchValue) ||
- actorName.toLowerCase().includes(searchValue) ||
- actorUserAgent.toLowerCase().includes(searchValue) ||
- id.toLowerCase().includes(searchValue) ||
- (userId ?? "").toLowerCase().includes(searchValue) ||
- resourceName.toLowerCase().includes(searchValue);
-
- const filteredLogs =
- searchValue.length >= 2
- ? logs.filter((log) => {
- // Handle command logs (database sessions)
- if ("input" in log && "output" in log) {
- return (
- log.input.toLowerCase().includes(searchValue) ||
- log.output.toLowerCase().includes(searchValue)
- );
- }
- // Handle terminal events (SSH sessions)
- if ("data" in log) {
- try {
- const decodedData = atob(log.data);
- return decodedData.toLowerCase().includes(searchValue);
- } catch {
- return false;
- }
- }
- return false;
- })
- : [];
-
- return {
- session,
- isMatch: isMetaMatch || filteredLogs.length > 0,
- filteredLogs
- };
- });
- }, [sessions, search]);
-
const filteredSessions = useMemo(
() =>
- sessionsWithMatches
- .filter((item) => {
- if (!item.isMatch) return false;
-
- const { resourceType, status } = item.session;
+ sessions
+ .filter((session) => {
+ const { resourceType, status } = session;
if (
(filters.resourceType.length && !filters.resourceType.includes(resourceType)) ||
(filters.status.length && !filters.status.includes(status))
@@ -176,10 +94,7 @@ export const PamSessionsTable = ({ sessions }: Props) => {
return true;
})
.sort((a, b) => {
- const [one, two] =
- orderDirection === OrderByDirection.ASC
- ? [a.session, b.session]
- : [b.session, a.session];
+ const [one, two] = orderDirection === OrderByDirection.ASC ? [a, b] : [b, a];
switch (orderBy) {
case OrderBy.Account:
@@ -199,7 +114,7 @@ export const PamSessionsTable = ({ sessions }: Props) => {
}
}
}),
- [sessionsWithMatches, orderDirection, orderBy, filters]
+ [sessions, orderDirection, orderBy, filters]
);
useResetPageHelper({
@@ -230,76 +145,62 @@ export const PamSessionsTable = ({ sessions }: Props) => {
const isTableFiltered = Boolean(filters.resourceType.length || filters.status.length);
const isContentEmpty = !filteredSessions.length;
- const isSearchEmpty = isContentEmpty && (Boolean(search) || isTableFiltered);
+ const isFilteredEmpty = isContentEmpty && isTableFiltered;
+
+ const availableStatuses = [...new Set(sessions.map(({ status }) => status))];
+ const availableResourceTypes = [...new Set(sessions.map(({ resourceType }) => resourceType))];
return (
<div>
- <div className="flex gap-2">
- <Input
- value={search}
- onChange={(e) => {
- const newSearch = e.target.value;
- setSearch(newSearch);
- navigate({
- search: (prev) => ({ ...prev, search: newSearch || undefined }),
- replace: true
- });
- }}
- leftIcon={<FontAwesomeIcon icon={faMagnifyingGlass} />}
- placeholder="Search sessions and logs..."
- className="flex-1"
- />
+ <div className="flex justify-end">
<DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton
- ariaLabel="Filter sessions"
- variant="plain"
- size="sm"
- className={twMerge(
- "flex h-10 w-11 items-center justify-center overflow-hidden border border-mineshaft-600 bg-mineshaft-800 p-0 transition-all hover:border-primary/60 hover:bg-primary/10",
- isTableFiltered && "border-primary/50 text-primary"
- )}
- >
- <FontAwesomeIcon icon={faFilter} />
- </IconButton>
+ <DropdownMenuTrigger className="outline-0">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <IconButton
+ className="relative"
+ size="md"
+ variant={isTableFiltered ? "project" : "outline"}
+ >
+ <FilterIcon />
+ </IconButton>
+ </TooltipTrigger>
+ <TooltipContent>Filter sessions</TooltipContent>
+ </Tooltip>
</DropdownMenuTrigger>
<DropdownMenuContent className="max-h-[70vh] thin-scrollbar overflow-y-auto" align="end">
- <DropdownMenuLabel>Session Status</DropdownMenuLabel>
- {sessions.length ? (
- [...new Set(sessions.map(({ status }) => status))].map((status) => {
- return (
- <DropdownMenuItem
- onClick={(e) => {
- e.preventDefault();
- setFilters((prev) => ({
- ...prev,
- status: prev.status.includes(status)
- ? prev.status.filter((a) => a !== status)
- : [...prev.status, status]
- }));
- }}
- key={status}
- icon={
- filters.status.includes(status) && (
- <FontAwesomeIcon className="text-primary" icon={faCheckCircle} />
- )
- }
- iconPos="right"
- >
- {status[0].toUpperCase() + status.slice(1)}
- </DropdownMenuItem>
- );
- })
+ <DropdownMenuLabel>Status</DropdownMenuLabel>
+ {availableStatuses.length ? (
+ availableStatuses.map((status) => (
+ <DropdownMenuCheckboxItem
+ key={status}
+ checked={filters.status.includes(status)}
+ onClick={(e) => {
+ e.preventDefault();
+ setFilters((prev) => ({
+ ...prev,
+ status: prev.status.includes(status)
+ ? prev.status.filter((a) => a !== status)
+ : [...prev.status, status]
+ }));
+ }}
+ >
+ {status[0].toUpperCase() + status.slice(1)}
+ </DropdownMenuCheckboxItem>
+ ))
) : (
- <DropdownMenuItem isDisabled>No Sessions</DropdownMenuItem>
+ <p className="px-2 py-1.5 text-sm text-muted">No sessions</p>
)}
+ <DropdownMenuSeparator />
<DropdownMenuLabel>Resource Type</DropdownMenuLabel>
- {sessions.length ? (
- [...new Set(sessions.map(({ resourceType }) => resourceType))].map((type) => {
+ {availableResourceTypes.length ? (
+ availableResourceTypes.map((type) => {
const { name, image } = PAM_RESOURCE_TYPE_MAP[type];
return (
- <DropdownMenuItem
+ <DropdownMenuCheckboxItem
+ key={type}
+ checked={filters.resourceType.includes(type)}
onClick={(e) => {
e.preventDefault();
setFilters((prev) => ({
@@ -309,27 +210,18 @@ export const PamSessionsTable = ({ sessions }: Props) => {
: [...prev.resourceType, type]
}));
}}
- key={type}
- icon={
- filters.resourceType.includes(type) && (
- <FontAwesomeIcon className="text-primary" icon={faCheckCircle} />
- )
- }
- iconPos="right"
>
- <div className="flex items-center gap-2">
- <img
- alt={`${name} resource type`}
- src={`/images/integrations/${image}`}
- className="h-4 w-4"
- />
- <span>{name}</span>
- </div>
- </DropdownMenuItem>
+ <img
+ alt={`${name} resource type`}
+ src={`/images/integrations/${image}`}
+ className="h-4 w-4"
+ />
+ {name}
+ </DropdownMenuCheckboxItem>
);
})
) : (
- <DropdownMenuItem isDisabled>No Sessions</DropdownMenuItem>
+ <p className="px-2 py-1.5 text-sm text-muted">No sessions</p>
)}
</DropdownMenuContent>
</DropdownMenu>
@@ -341,66 +233,61 @@ export const PamSessionsTable = ({ sessions }: Props) => {
<Th>
<div className="flex items-center">
Account
- <IconButton
+ <IconButtonV2
variant="plain"
className={getClassName(OrderBy.Account)}
- ariaLabel="sort"
+ ariaLabel="Sort"
onClick={() => handleSort(OrderBy.Account)}
>
<FontAwesomeIcon icon={getColSortIcon(OrderBy.Account)} />
- </IconButton>
+ </IconButtonV2>
</div>
</Th>
<Th>
<div className="flex items-center">
Actor
- <IconButton
+ <IconButtonV2
variant="plain"
className={getClassName(OrderBy.Actor)}
- ariaLabel="sort"
+ ariaLabel="Sort"
onClick={() => handleSort(OrderBy.Actor)}
>
<FontAwesomeIcon icon={getColSortIcon(OrderBy.Actor)} />
- </IconButton>
+ </IconButtonV2>
</div>
</Th>
<Th>
<div className="flex items-center">
Created At
- <IconButton
+ <IconButtonV2
variant="plain"
className={getClassName(OrderBy.CreatedAt)}
- ariaLabel="sort"
+ ariaLabel="Sort"
onClick={() => handleSort(OrderBy.CreatedAt)}
>
<FontAwesomeIcon icon={getColSortIcon(OrderBy.CreatedAt)} />
- </IconButton>
+ </IconButtonV2>
</div>
</Th>
<Th>
<div className="flex items-center">
Ended At
- <IconButton
+ <IconButtonV2
variant="plain"
className={getClassName(OrderBy.EndedAt)}
- ariaLabel="sort"
+ ariaLabel="Sort"
onClick={() => handleSort(OrderBy.EndedAt)}
>
<FontAwesomeIcon icon={getColSortIcon(OrderBy.EndedAt)} />
- </IconButton>
+ </IconButtonV2>
</div>
</Th>
<Th className="w-5" />
</Tr>
</THead>
<TBody>
- {currentPageData.map(({ session, filteredLogs }) => (
- <PamSessionRow
- key={session.id}
- session={session}
- search={search.trim().toLowerCase()}
- filteredLogs={filteredLogs}
- />
+ {currentPageData.map((session) => (
+ <PamSessionRow key={session.id} session={session} />
))}
</TBody>
</Table>
@@ -415,8 +302,8 @@ export const PamSessionsTable = ({ sessions }: Props) => {
)}
{isContentEmpty && (
<EmptyState
- title={isSearchEmpty ? "No sessions match search" : "No sessions"}
- icon={isSearchEmpty ? faSearch : faCircleXmark}
+ title={isFilteredEmpty ? "No sessions match filters" : "No sessions"}
+ icon={isFilteredEmpty ? faSearch : faCircleXmark}
/>
)}
</TableContainer>
diff --git a/frontend/src/pages/pam/PamSessionsPage/route.tsx b/frontend/src/pages/pam/PamSessionsPage/route.tsx
index a97f92e8eb..52d5c7d153 100644
--- a/frontend/src/pages/pam/PamSessionsPage/route.tsx
+++ b/frontend/src/pages/pam/PamSessionsPage/route.tsx
@@ -1,17 +1,10 @@
import { createFileRoute } from "@tanstack/react-router";
-import { zodValidator } from "@tanstack/zod-adapter";
-import { z } from "zod";
import { PamSessionPage } from "./PamSessionsPage";
export const Route = createFileRoute(
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/sessions/"
)({
- validateSearch: zodValidator(
- z.object({
- search: z.string().optional()
- })
- ),
beforeLoad: ({ context }) => {
return {
breadcrumbs: [
diff --git a/frontend/src/pages/pam/SettingsPage/SettingsPage.tsx b/frontend/src/pages/pam/SettingsPage/SettingsPage.tsx
index efcd362139..a81cbb5734 100644
--- a/frontend/src/pages/pam/SettingsPage/SettingsPage.tsx
+++ b/frontend/src/pages/pam/SettingsPage/SettingsPage.tsx
@@ -1,18 +1,24 @@
import { Helmet } from "react-helmet";
import { useTranslation } from "react-i18next";
-import { Link } from "@tanstack/react-router";
+import { Link, useSearch } from "@tanstack/react-router";
import { InfoIcon } from "lucide-react";
-import { PageHeader, TabPanel, Tabs } from "@app/components/v2";
+import { PageHeader } from "@app/components/v2";
+import { ROUTE_PATHS } from "@app/const/routes";
import { useOrganization } from "@app/context";
import { ProjectType } from "@app/hooks/api/projects/types";
import { ProjectGeneralTab } from "@app/pages/project/SettingsPage/components/ProjectGeneralTab";
+import { PamRecordingConfigTab } from "./components/PamRecordingConfigTab";
+
export const SettingsPage = () => {
const { t } = useTranslation();
-
const { currentOrg, isSubOrganization } = useOrganization();
+ const { selectedTab } = useSearch({
+ from: ROUTE_PATHS.Pam.SettingsPage.id
+ });
+
return (
<div className="flex h-full w-full justify-center bg-bunker-800 text-white">
<Helmet>
@@ -35,11 +41,8 @@ export const SettingsPage = () => {
settings?
</Link>
</PageHeader>
- <Tabs orientation="vertical" defaultValue="tab-project-general">
- <TabPanel value="tab-project-general">
- <ProjectGeneralTab />
- </TabPanel>
- </Tabs>
+ {selectedTab === "tab-project-general" && <ProjectGeneralTab />}
+ {selectedTab === "tab-pam-session-recording" && <PamRecordingConfigTab />}
</div>
</div>
);
diff --git a/frontend/src/pages/pam/SettingsPage/components/PamRecordingConfigTab.tsx b/frontend/src/pages/pam/SettingsPage/components/PamRecordingConfigTab.tsx
new file mode 100644
index 0000000000..e5be77c51c
--- /dev/null
+++ b/frontend/src/pages/pam/SettingsPage/components/PamRecordingConfigTab.tsx
@@ -0,0 +1,287 @@
+import { useEffect, useState } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { AlertTriangleIcon, TrashIcon } from "lucide-react";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Alert,
+ AlertDescription,
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogMedia,
+ AlertDialogTitle,
+ AlertTitle,
+ Button,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ Input,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3";
+import { useProject } from "@app/context";
+import { AWS_REGIONS } from "@app/helpers/appConnections";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import { useListAvailableAppConnections } from "@app/hooks/api/appConnections/queries";
+import {
+ useDeletePamRecordingConfig,
+ useGetPamRecordingConfig,
+ useUpsertPamRecordingConfig
+} from "@app/hooks/api/pam/recording-config";
+
+const formSchema = z.object({
+ storageBackend: z.literal("aws-s3"),
+ connectionId: z.string().uuid({ message: "Select an AWS connection" }),
+ bucket: z.string().trim().min(1, "Bucket is required").max(255),
+ region: z.string().trim().min(1, "Region is required").max(64),
+ keyPrefix: z.string().trim().max(512).optional()
+});
+
+type FormData = z.infer<typeof formSchema>;
+
+export const PamRecordingConfigTab = () => {
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id ?? "";
+ const recordingConfig = useGetPamRecordingConfig(projectId);
+ const [isDisableDialogOpen, setIsDisableDialogOpen] = useState(false);
+
+ const { data: awsConnections, isLoading: connectionsLoading } = useListAvailableAppConnections(
+ AppConnection.AWS,
+ projectId
+ );
+
+ const upsertMutation = useUpsertPamRecordingConfig();
+ const deleteMutation = useDeletePamRecordingConfig();
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ formState: { isSubmitting, isDirty }
+ } = useForm<FormData>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ storageBackend: "aws-s3",
+ connectionId: "",
+ bucket: "",
+ region: "us-east-1",
+ keyPrefix: ""
+ }
+ });
+
+ // Defer the reset until BOTH the saved config and the available-connections list have loaded
+ useEffect(() => {
+ if (recordingConfig.data && awsConnections) {
+ reset({
+ storageBackend: "aws-s3",
+ connectionId: recordingConfig.data.connectionId,
+ bucket: recordingConfig.data.bucket,
+ region: recordingConfig.data.region,
+ keyPrefix: recordingConfig.data.keyPrefix ?? ""
+ });
+ }
+ }, [recordingConfig.data, awsConnections, reset]);
+
+ const onSave = handleSubmit(async (values) => {
+ await upsertMutation.mutateAsync({
+ projectId,
+ ...values,
+ keyPrefix: values.keyPrefix?.trim() ? values.keyPrefix : null
+ });
+ createNotification({ type: "success", text: "Session recording configuration saved" });
+ });
+
+ const onDelete = async () => {
+ if (!projectId) return;
+ await deleteMutation.mutateAsync({ projectId });
+ reset({
+ storageBackend: "aws-s3",
+ connectionId: "",
+ bucket: "",
+ region: "us-east-1",
+ keyPrefix: ""
+ });
+ setIsDisableDialogOpen(false);
+ createNotification({
+ type: "success",
+ text: "Session recording configuration removed"
+ });
+ };
+
+ return (
+ <div className="rounded-lg border border-border bg-container p-6">
+ <h2 className="text-xl font-semibold text-foreground">Session Recording</h2>
+ <p className="mt-1 text-sm text-muted">Store PAM session recordings in your own S3 bucket.</p>
+
+ <Alert variant="warning" className="mt-4">
+ <AlertTriangleIcon />
+ <AlertTitle>Changing bucket affects existing recordings</AlertTitle>
+ <AlertDescription>
+ Changing the bucket on a project with existing recordings makes those recordings
+ inaccessible unless you manually migrate the objects. Keep the same bucket and key prefix
+ when rotating credentials.
+ </AlertDescription>
+ </Alert>
+
+ <form className="mt-6 space-y-4" onSubmit={onSave}>
+ <Controller
+ control={control}
+ name="connectionId"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>AWS Connection</FieldLabel>
+ <FieldContent>
+ <Select
+ disabled={connectionsLoading}
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue
+ placeholder={
+ connectionsLoading ? "Loading connections…" : "Select connection"
+ }
+ />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {(awsConnections ?? []).map((conn) => (
+ <SelectItem key={conn.id} value={conn.id}>
+ {conn.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldError>{error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ control={control}
+ name="bucket"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>Bucket</FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ placeholder="my-pam-recordings"
+ autoComplete="off"
+ isError={Boolean(error)}
+ />
+ <FieldError>{error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ control={control}
+ name="region"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>Region</FieldLabel>
+ <FieldContent>
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select a region" />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {AWS_REGIONS.map(({ name, slug }) => (
+ <SelectItem key={slug} value={slug}>
+ {name} ({slug})
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldError>{error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ control={control}
+ name="keyPrefix"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel className="inline-flex flex-wrap items-baseline gap-1.5">
+ Key Prefix
+ <span className="text-xs font-normal text-muted">(optional)</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ value={field.value ?? ""}
+ placeholder="pam/prod"
+ autoComplete="off"
+ isError={Boolean(error)}
+ />
+ <FieldDescription>
+ Prepended to every object key. Useful for sharing one bucket across multiple
+ projects or environments.
+ </FieldDescription>
+ <FieldError>{error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <div className="flex items-center gap-x-3 pt-2">
+ <Button
+ variant="project"
+ type="submit"
+ isPending={upsertMutation.isPending || isSubmitting}
+ isDisabled={!isDirty && !!recordingConfig.data}
+ >
+ {recordingConfig.data ? "Update" : "Save"}
+ </Button>
+ {recordingConfig.data && (
+ <Button
+ variant="danger"
+ type="button"
+ onClick={() => setIsDisableDialogOpen(true)}
+ isPending={deleteMutation.isPending}
+ >
+ Disable Recording
+ </Button>
+ )}
+ </div>
+ </form>
+
+ <AlertDialog open={isDisableDialogOpen} onOpenChange={setIsDisableDialogOpen}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogMedia>
+ <TrashIcon />
+ </AlertDialogMedia>
+ <AlertDialogTitle>Disable Session Recording</AlertDialogTitle>
+ <AlertDialogDescription>
+ Existing recordings will become inaccessible until you reconfigure with the same
+ bucket. Are you sure you want to disable session recording for this project?
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction variant="danger" onClick={onDelete}>
+ Disable
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+};
diff --git a/frontend/src/pages/pam/SettingsPage/route.tsx b/frontend/src/pages/pam/SettingsPage/route.tsx
index cf90be4d34..a2b70c13ba 100644
--- a/frontend/src/pages/pam/SettingsPage/route.tsx
+++ b/frontend/src/pages/pam/SettingsPage/route.tsx
@@ -1,11 +1,21 @@
-import { createFileRoute } from "@tanstack/react-router";
+import { createFileRoute, stripSearchParams } from "@tanstack/react-router";
+import { zodValidator } from "@tanstack/zod-adapter";
+import { z } from "zod";
import { SettingsPage } from "./SettingsPage";
+const SettingsPageQueryParams = z.object({
+ selectedTab: z.string().catch("tab-project-general")
+});
+
export const Route = createFileRoute(
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/settings"
)({
component: SettingsPage,
+ validateSearch: zodValidator(SettingsPageQueryParams),
+ search: {
+ middlewares: [stripSearchParams({ selectedTab: "" })]
+ },
beforeLoad: ({ context }) => {
return {
breadcrumbs: [