Skip to content

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

base backend CRUD

x0322052cfe894582a9
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 9675201718..4a238b9260 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -33,7 +33,11 @@ import { TKmipServiceFactory } from "@app/ee/services/kmip/kmip-service";
import { TLdapConfigServiceFactory } from "@app/ee/services/ldap-config/ldap-config-service";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TOidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-service";
+import { TPamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-service";
+import { TPamAccountTemplateServiceFactory } from "@app/ee/services/pam-account-template/pam-account-template-service";
+import { TPamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";
import { TPamProjectResolverFactory } from "@app/ee/services/pam-instance/pam-project-resolver";
+import { TPamMembershipServiceFactory } from "@app/ee/services/pam-membership/pam-membership-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { TPitServiceFactory } from "@app/ee/services/pit/pit-service";
import { TPkiAcmeServiceFactory } from "@app/ee/services/pki-acme/pki-acme-types";
@@ -402,6 +406,10 @@ declare module "fastify" {
announcement: TAnnouncementServiceFactory;
offlineUsageReport: TOfflineUsageReportServiceFactory;
orgProductStats: TOrgProductStatsServiceFactory;
+ pamAccountTemplate: TPamAccountTemplateServiceFactory;
+ pamFolder: TPamFolderServiceFactory;
+ pamAccount: TPamAccountServiceFactory;
+ pamMembership: TPamMembershipServiceFactory;
mfaSession: TMfaSessionServiceFactory;
membershipUser: TMembershipUserServiceFactory;
membershipIdentity: TMembershipIdentityServiceFactory;
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index 840cfed220..ab4da527b3 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -719,6 +719,11 @@ import {
TPamAccountPoliciesInsert,
TPamAccountPoliciesUpdate
} from "@app/db/schemas/pam-account-policies";
+import {
+ TPamAccountTemplates,
+ TPamAccountTemplatesInsert,
+ TPamAccountTemplatesUpdate
+} from "@app/db/schemas/pam-account-templates";
import { TPamAccounts, TPamAccountsInsert, TPamAccountsUpdate } from "@app/db/schemas/pam-accounts";
import {
TPamDiscoverySourceAccounts,
@@ -1691,6 +1696,11 @@ declare module "knex/types/tables" {
TKeyValueStoreInsert,
TKeyValueStoreUpdate
>;
+ [TableName.PamAccountTemplate]: KnexOriginal.CompositeTableType<
+ TPamAccountTemplates,
+ TPamAccountTemplatesInsert,
+ TPamAccountTemplatesUpdate
+ >;
[TableName.PamFolder]: KnexOriginal.CompositeTableType<TPamFolders, TPamFoldersInsert, TPamFoldersUpdate>;
[TableName.PamResource]: KnexOriginal.CompositeTableType<TPamResources, TPamResourcesInsert, TPamResourcesUpdate>;
[TableName.PamResourceFavorite]: KnexOriginal.CompositeTableType<
diff --git a/backend/src/db/migrations/20260603030053_pam-revamp.ts b/backend/src/db/migrations/20260603030053_pam-revamp.ts
index 8241fdf317..b72fc2aec7 100644
--- a/backend/src/db/migrations/20260603030053_pam-revamp.ts
+++ b/backend/src/db/migrations/20260603030053_pam-revamp.ts
@@ -2,7 +2,7 @@
import slugify from "@sindresorhus/slugify";
import { Knex } from "knex";
-import { PamFolderRole, PamProductRole } from "@app/ee/services/pam/pam-enums";
+import { PamProductRole, PamResourceRole } from "@app/ee/services/pam/pam-enums";
import { DEFAULT_ACCOUNT_TEMPLATES } from "@app/ee/services/pam-instance/pam-project-bootstrap";
import { inMemoryKeyStore } from "@app/keystore/memory";
import { crypto } from "@app/lib/crypto/cryptography";
@@ -355,7 +355,7 @@ export async function up(knex: Knex): Promise<void> {
const roles = await knex(TableName.MembershipRole).where("membershipId", member.id).select("role");
const isAdmin = roles.some((r: { role: string }) => r.role === ProjectMembershipRole.Admin);
- const folderRole = isAdmin ? PamFolderRole.Admin : PamFolderRole.Requester;
+ const resourceRole = isAdmin ? PamResourceRole.Admin : PamResourceRole.Requester;
const [folderMembership] = await knex(TableName.Membership)
.insert({
@@ -371,7 +371,7 @@ export async function up(knex: Knex): Promise<void> {
await knex(TableName.MembershipRole).insert({
membershipId: folderMembership.id,
- role: folderRole
+ role: resourceRole
});
}
}
@@ -402,6 +402,11 @@ export async function up(knex: Knex): Promise<void> {
t.uuid("templateId").notNullable().alter();
t.binary("encryptedConnectionDetails").notNullable().alter();
t.unique(["folderId", "name"]);
+ // Make retained old columns nullable so new accounts can be created without them
+ t.string("projectId", 36).nullable().alter();
+ t.uuid("resourceId").nullable().alter();
+ t.uuid("domainId").nullable().alter();
+ t.uuid("policyId").nullable().alter();
});
// Sessions
diff --git a/backend/src/db/schemas/pam-accounts.ts b/backend/src/db/schemas/pam-accounts.ts
index 1d39f85424..1a8ae71a19 100644
--- a/backend/src/db/schemas/pam-accounts.ts
+++ b/backend/src/db/schemas/pam-accounts.ts
@@ -11,7 +11,7 @@ import { TImmutableDBKeys } from "./models";
export const PamAccountsSchema = z.object({
id: z.string().uuid(),
- projectId: z.string(),
+ projectId: z.string().nullable().optional(),
folderId: z.string().uuid().nullable().optional(),
resourceId: z.string().uuid().nullable().optional(),
name: z.string(),
diff --git a/backend/src/ee/routes/v1/index.ts b/backend/src/ee/routes/v1/index.ts
index 3e0e6c6a15..cecb5118a0 100644
--- a/backend/src/ee/routes/v1/index.ts
+++ b/backend/src/ee/routes/v1/index.ts
@@ -32,6 +32,7 @@ import { registerLdapRouter } from "./ldap-router";
import { registerLicenseRouter } from "./license-router";
import { registerOidcRouter } from "./oidc-router";
import { registerOrgRoleRouter } from "./org-role-router";
+import { registerPamRouters } from "./pam-routers";
import { registerPITRouter } from "./pit-router";
import { registerPkiAcmeRouter } from "./pki-acme-router";
import { registerPkiDiscoveryRouter } from "./pki-discovery-router";
@@ -203,4 +204,6 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {
},
{ prefix: "/ai" }
);
+
+ await server.register(registerPamRouters, { prefix: "/pam" });
};
diff --git a/backend/src/ee/routes/v1/pam-routers/index.ts b/backend/src/ee/routes/v1/pam-routers/index.ts
new file mode 100644
index 0000000000..d92d52e7ea
--- /dev/null
+++ b/backend/src/ee/routes/v1/pam-routers/index.ts
@@ -0,0 +1,13 @@
+import { registerPamAccountRouter } from "./pam-account-router";
+import { registerPamAccountTemplateRouter } from "./pam-account-template-router";
+import { registerPamFolderRouter } from "./pam-folder-router";
+import { registerPamMembershipRouter } from "./pam-membership-router";
+import { registerPamResourceRoleRouter } from "./pam-resource-role-router";
+
+export const registerPamRouters = async (server: FastifyZodProvider) => {
+ await server.register(registerPamAccountTemplateRouter, { prefix: "/account-templates" });
+ await server.register(registerPamFolderRouter, { prefix: "/folders" });
+ await server.register(registerPamAccountRouter, { prefix: "/accounts" });
+ await server.register(registerPamMembershipRouter, { prefix: "/members" });
+ await server.register(registerPamResourceRoleRouter, { prefix: "/resource-roles" });
+};
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts
new file mode 100644
index 0000000000..aae10a9a2a
--- /dev/null
+++ b/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts
@@ -0,0 +1,331 @@
+import z from "zod";
+
+import { PamAccountsSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { PamAccountType } from "@app/ee/services/pam/pam-enums";
+import { ACCOUNT_TYPE_CONFIGS } from "@app/ee/services/pam-account/pam-account-schemas";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+
+type TSupportedConfigs = typeof ACCOUNT_TYPE_CONFIGS;
+type TSupportedAccountType = keyof TSupportedConfigs;
+type TSupportedConfigValue = TSupportedConfigs[TSupportedAccountType];
+
+const BaseAccountFields = PamAccountsSchema.pick({
+ id: true,
+ name: true,
+ description: true,
+ folderId: true,
+ projectId: true,
+ templateId: true,
+ gatewayId: true,
+ gatewayPoolId: true,
+ recordingConnectionId: true,
+ createdAt: true,
+ updatedAt: true
+});
+
+const SanitizedAccountListItemSchema = BaseAccountFields.extend({
+ folderName: z.string().nullable().optional(),
+ templateName: z.string(),
+ accountType: z.string()
+});
+
+const toPascalCase = (s: string) =>
+ s
+ .split("-")
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
+ .join("");
+
+const registerPerTypeEndpoints = (
+ server: FastifyZodProvider,
+ accountType: PamAccountType,
+ config: TSupportedConfigValue
+) => {
+ const typeId = toPascalCase(accountType);
+
+ server.route({
+ method: "POST",
+ url: "/",
+ schema: {
+ operationId: `create${typeId}PamAccount`,
+ body: z.object({
+ name: z.string().trim().min(1).max(64),
+ description: z.string().trim().max(256).optional(),
+ folderId: z.string().uuid(),
+ templateId: z.string().uuid(),
+ connectionDetails: config.connectionDetails,
+ credentials: config.credentials,
+ gatewayId: z.string().uuid().optional(),
+ gatewayPoolId: z.string().uuid().optional(),
+ recordingConnectionId: z.string().uuid().optional()
+ }),
+ response: {
+ 200: BaseAccountFields.extend({
+ accountType: z.string(),
+ folderName: z.string(),
+ templateName: z.string(),
+ connectionDetails: z.unknown()
+ })
+ }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const account = await server.services.pamAccount.create({
+ accountType,
+ ...req.body,
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.PAM_ACCOUNT_CREATE,
+ metadata: {
+ accountId: account.id,
+ accountType,
+ folderId: req.body.folderId,
+ templateId: req.body.templateId,
+ name: req.body.name,
+ description: req.body.description
+ }
+ }
+ });
+
+ void server.services.telemetry
+ .sendPostHogEvents({
+ event: PostHogEventTypes.PamAccountCreated,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ accountType,
+ orgId: req.permission.orgId
+ }
+ })
+ .catch(() => {});
+
+ return account;
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:accountId",
+ schema: {
+ operationId: `update${typeId}PamAccount`,
+ params: z.object({ accountId: z.string().uuid() }),
+ body: z.object({
+ name: z.string().trim().min(1).max(64).optional(),
+ description: z.string().trim().max(256).nullable().optional(),
+ folderId: z.string().uuid().optional(),
+ templateId: z.string().uuid().optional(),
+ connectionDetails: config.connectionDetails.optional(),
+ credentials: config.credentials.optional(),
+ gatewayId: z.string().uuid().nullable().optional(),
+ gatewayPoolId: z.string().uuid().nullable().optional(),
+ recordingConnectionId: z.string().uuid().nullable().optional()
+ }),
+ response: {
+ 200: BaseAccountFields
+ }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const account = await server.services.pamAccount.update({
+ accountId: req.params.accountId,
+ accountType,
+ ...req.body,
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.PAM_ACCOUNT_UPDATE,
+ metadata: {
+ accountId: account.id,
+ accountType,
+ name: req.body.name,
+ description: req.body.description
+ }
+ }
+ });
+
+ return account;
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:accountId",
+ schema: {
+ operationId: `get${typeId}PamAccount`,
+ params: z.object({ accountId: z.string().uuid() }),
+ response: {
+ 200: SanitizedAccountListItemSchema.extend({
+ templateAccessPolicy: z.unknown().nullable().optional(),
+ templateSettings: z.unknown().nullable().optional(),
+ connectionDetails: z.unknown()
+ })
+ }
+ },
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ return server.services.pamAccount.getById({
+ accountId: req.params.accountId,
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:accountId",
+ schema: {
+ operationId: `delete${typeId}PamAccount`,
+ params: z.object({ accountId: z.string().uuid() }),
+ response: {
+ 200: BaseAccountFields
+ }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const account = await server.services.pamAccount.deleteAccount({
+ accountId: req.params.accountId,
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.PAM_ACCOUNT_DELETE,
+ metadata: {
+ accountId: account.id,
+ accountType,
+ accountName: account.name
+ }
+ }
+ });
+
+ void server.services.telemetry
+ .sendPostHogEvents({
+ event: PostHogEventTypes.PamAccountDeleted,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ accountType,
+ orgId: req.permission.orgId
+ }
+ })
+ .catch(() => {});
+
+ return account;
+ }
+ });
+};
+
+export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/",
+ schema: {
+ operationId: "listPamAccounts",
+ querystring: z.object({
+ folderId: z.string().uuid().optional(),
+ templateId: z.string().uuid().optional(),
+ search: z.string().optional()
+ }),
+ response: {
+ 200: z.array(SanitizedAccountListItemSchema)
+ }
+ },
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ return server.services.pamAccount.list({
+ projectId: req.internalPamProjectId,
+ folderId: req.query.folderId,
+ templateId: req.query.templateId,
+ search: req.query.search,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/accessible",
+ schema: {
+ operationId: "listAccessiblePamAccounts",
+ response: {
+ 200: z.array(
+ SanitizedAccountListItemSchema.pick({
+ id: true,
+ name: true,
+ description: true,
+ folderId: true,
+ projectId: true,
+ templateId: true,
+ createdAt: true,
+ updatedAt: true,
+ folderName: true,
+ templateName: true,
+ accountType: true
+ })
+ )
+ }
+ },
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ return server.services.pamAccount.listAccessible({
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+ }
+ });
+
+ await Promise.all(
+ (Object.entries(ACCOUNT_TYPE_CONFIGS) as [TSupportedAccountType, TSupportedConfigValue][]).map(
+ ([accountType, config]) =>
+ server.register(
+ async (typeRouter) => {
+ registerPerTypeEndpoints(typeRouter as unknown as FastifyZodProvider, accountType, config);
+ },
+ { prefix: `/${accountType}` }
+ )
+ )
+ );
+};
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-account-template-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-account-template-router.ts
new file mode 100644
index 0000000000..2023c6a8f3
--- /dev/null
+++ b/backend/src/ee/routes/v1/pam-routers/pam-account-template-router.ts
@@ -0,0 +1,249 @@
+import z from "zod";
+
+import { PamAccountTemplatesSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { PamAccountType } from "@app/ee/services/pam/pam-enums";
+import {
+ PamTemplateAccessPolicySchema,
+ PamTemplateSettingsSchema
+} from "@app/ee/services/pam/pam-template-config-schemas";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+
+const SanitizedTemplateSchema = PamAccountTemplatesSchema.pick({
+ id: true,
+ projectId: true,
+ name: true,
+ description: true,
+ type: true,
+ accessPolicy: true,
+ settings: true,
+ gatewayId: true,
+ gatewayPoolId: true,
+ recordingConnectionId: true,
+ createdAt: true,
+ updatedAt: true
+});
+
+export const registerPamAccountTemplateRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/",
+ schema: {
+ operationId: "listPamAccountTemplates",
+ querystring: z.object({
+ search: z.string().optional(),
+ type: z.nativeEnum(PamAccountType).optional()
+ }),
+ response: {
+ 200: z.array(SanitizedTemplateSchema)
+ }
+ },
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ return server.services.pamAccountTemplate.list({
+ projectId: req.internalPamProjectId,
+ search: req.query.search,
+ type: req.query.type,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:templateId",
+ schema: {
+ operationId: "getPamAccountTemplateById",
+ params: z.object({
+ templateId: z.string().uuid()
+ }),
+ response: {
+ 200: SanitizedTemplateSchema.extend({
+ accountCount: z.number()
+ })
+ }
+ },
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ return server.services.pamAccountTemplate.getById({
+ templateId: req.params.templateId,
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/",
+ schema: {
+ operationId: "createPamAccountTemplate",
+ body: z.object({
+ name: z.string().trim().min(1).max(64),
+ description: z.string().trim().max(256).optional(),
+ type: z.nativeEnum(PamAccountType),
+ accessPolicy: PamTemplateAccessPolicySchema.optional(),
+ settings: PamTemplateSettingsSchema.optional(),
+ gatewayId: z.string().uuid().optional(),
+ gatewayPoolId: z.string().uuid().optional(),
+ recordingConnectionId: z.string().uuid().optional()
+ }),
+ response: {
+ 200: SanitizedTemplateSchema
+ }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const template = await server.services.pamAccountTemplate.create({
+ ...req.body,
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.PAM_ACCOUNT_TEMPLATE_CREATE,
+ metadata: {
+ templateId: template.id,
+ name: template.name,
+ accountType: req.body.type
+ }
+ }
+ });
+
+ void server.services.telemetry
+ .sendPostHogEvents({
+ event: PostHogEventTypes.PamAccountTemplateCreated,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ accountType: req.body.type,
+ orgId: req.permission.orgId
+ }
+ })
+ .catch(() => {});
+
+ return template;
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:templateId",
+ schema: {
+ operationId: "updatePamAccountTemplate",
+ params: z.object({
+ templateId: z.string().uuid()
+ }),
+ body: z.object({
+ name: z.string().trim().min(1).max(64).optional(),
+ description: z.string().trim().max(256).nullable().optional(),
+ accessPolicy: PamTemplateAccessPolicySchema.optional(),
+ settings: PamTemplateSettingsSchema.optional(),
+ gatewayId: z.string().uuid().nullable().optional(),
+ gatewayPoolId: z.string().uuid().nullable().optional(),
+ recordingConnectionId: z.string().uuid().nullable().optional()
+ }),
+ response: {
+ 200: SanitizedTemplateSchema
+ }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const template = await server.services.pamAccountTemplate.update({
+ templateId: req.params.templateId,
+ ...req.body,
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.PAM_ACCOUNT_TEMPLATE_UPDATE,
+ metadata: {
+ templateId: template.id,
+ name: req.body.name
+ }
+ }
+ });
+
+ return template;
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:templateId",
+ schema: {
+ operationId: "deletePamAccountTemplate",
+ params: z.object({
+ templateId: z.string().uuid()
+ }),
+ response: {
+ 200: SanitizedTemplateSchema
+ }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const template = await server.services.pamAccountTemplate.deleteTemplate({
+ templateId: req.params.templateId,
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.PAM_ACCOUNT_TEMPLATE_DELETE,
+ metadata: {
+ templateId: template.id,
+ name: template.name
+ }
+ }
+ });
+
+ void server.services.telemetry
+ .sendPostHogEvents({
+ event: PostHogEventTypes.PamAccountTemplateDeleted,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ accountType: template.type,
+ orgId: req.permission.orgId
+ }
+ })
+ .catch(() => {});
+
+ return template;
+ }
+ });
+};
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-folder-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-folder-router.ts
new file mode 100644
index 0000000000..097f99495c
--- /dev/null
+++ b/backend/src/ee/routes/v1/pam-routers/pam-folder-router.ts
@@ -0,0 +1,228 @@
+import z from "zod";
+
+import { PamFoldersSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+
+const SanitizedFolderSchema = PamFoldersSchema.pick({
+ id: true,
+ projectId: true,
+ name: true,
+ description: true,
+ createdAt: true,
+ updatedAt: true
+});
+
+export const registerPamFolderRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/",
+ schema: {
+ operationId: "listPamFolders",
+ querystring: z.object({
+ search: z.string().optional()
+ }),
+ response: {
+ 200: z.array(
+ SanitizedFolderSchema.extend({
+ accountCount: z.number()
+ })
+ )
+ }
+ },
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ return server.services.pamFolder.list({
+ projectId: req.internalPamProjectId,
+ search: req.query.search,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:folderId",
+ schema: {
+ operationId: "getPamFolderById",
+ params: z.object({
+ folderId: z.string().uuid()
+ }),
+ response: {
+ 200: SanitizedFolderSchema.extend({
+ accountCount: z.number()
+ })
+ }
+ },
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ return server.services.pamFolder.getById({
+ folderId: req.params.folderId,
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/",
+ schema: {
+ operationId: "createPamFolder",
+ body: z.object({
+ name: z.string().trim().min(1).max(64),
+ description: z.string().trim().max(256).optional()
+ }),
+ response: {
+ 200: SanitizedFolderSchema
+ }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const folder = await server.services.pamFolder.create({
+ ...req.body,
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.PAM_FOLDER_CREATE,
+ metadata: {
+ folderId: folder.id,
+ name: folder.name,
+ description: folder.description
+ }
+ }
+ });
+
+ void server.services.telemetry
+ .sendPostHogEvents({
+ event: PostHogEventTypes.PamFolderCreated,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ orgId: req.permission.orgId
+ }
+ })
+ .catch(() => {});
+
+ return folder;
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:folderId",
+ schema: {
+ operationId: "updatePamFolder",
+ params: z.object({
+ folderId: z.string().uuid()
+ }),
+ body: z.object({
+ name: z.string().trim().min(1).max(64).optional(),
+ description: z.string().trim().max(256).nullable().optional()
+ }),
+ response: {
+ 200: SanitizedFolderSchema
+ }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const folder = await server.services.pamFolder.update({
+ folderId: req.params.folderId,
+ ...req.body,
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.PAM_FOLDER_UPDATE,
+ metadata: {
+ folderId: folder.id,
+ name: req.body.name,
+ description: req.body.description
+ }
+ }
+ });
+
+ return folder;
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:folderId",
+ schema: {
+ operationId: "deletePamFolder",
+ params: z.object({
+ folderId: z.string().uuid()
+ }),
+ response: {
+ 200: SanitizedFolderSchema
+ }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const folder = await server.services.pamFolder.deleteFolder({
+ folderId: req.params.folderId,
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.PAM_FOLDER_DELETE,
+ metadata: {
+ folderId: folder.id,
+ folderName: folder.name
+ }
+ }
+ });
+
+ void server.services.telemetry
+ .sendPostHogEvents({
+ event: PostHogEventTypes.PamFolderDeleted,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ orgId: req.permission.orgId
+ }
+ })
+ .catch(() => {});
+
+ return folder;
+ }
+ });
+};
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-membership-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-membership-router.ts
new file mode 100644
index 0000000000..55c8d28ceb
--- /dev/null
+++ b/backend/src/ee/routes/v1/pam-routers/pam-membership-router.ts
@@ -0,0 +1,500 @@
+import { FastifyRequest } from "fastify";
+import z from "zod";
+
+import { EventType, TCreateAuditLogDTO } from "@app/ee/services/audit-log/audit-log-types";
+import { PamProductRole, PamResourceRole } from "@app/ee/services/pam/pam-enums";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { ActorAuthMethod, ActorType, AuthMode } from "@app/services/auth/auth-type";
+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+
+const MemberSchema = z.object({
+ membershipId: z.string().uuid(),
+ userId: z.string().uuid().nullable().optional(),
+ identityId: z.string().uuid().nullable().optional(),
+ groupId: z.string().uuid().nullable().optional(),
+ role: z.string(),
+ isActive: z.boolean(),
+ createdAt: z.date()
+});
+
+const MemberResultSchema = z.object({
+ membershipId: z.string().uuid(),
+ userId: z.string().uuid().optional(),
+ groupId: z.string().uuid().optional(),
+ role: z.string(),
+ createdAt: z.date()
+});
+
+const actorCtx = (req: {
+ internalPamProjectId: string;
+ permission: { id: string; type: ActorType; orgId: string; authMethod: ActorAuthMethod };
+}) => ({
+ projectId: req.internalPamProjectId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+});
+
+type ResourceMemberConfig = {
+ scopeKey: "folderId" | "accountId";
+ urlPrefix: string;
+ operationPrefix: string;
+ resultSchema: z.ZodObject<z.ZodRawShape>;
+ listMembers: string;
+ addMember: string;
+ updateMemberRole: string;
+ removeMember: string;
+ events: {
+ add: EventType;
+ update: EventType;
+ remove: EventType;
+ };
+ telemetry: {
+ add: PostHogEventTypes;
+ update: PostHogEventTypes;
+ remove: PostHogEventTypes;
+ };
+};
+
+const emitAuditLog = async (
+ server: FastifyZodProvider,
+ req: FastifyRequest & {
+ auditLogInfo: Pick<TCreateAuditLogDTO, "userAgent" | "userAgentType" | "ipAddress" | "actor">;
+ permission: { orgId: string };
+ },
+ type: EventType,
+ metadata: Record<string, unknown>
+) => {
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+ event: { type, metadata } as TCreateAuditLogDTO["event"]
+ });
+};
+
+const emitTelemetry = (
+ server: FastifyZodProvider,
+ req: FastifyRequest & { permission: { orgId: string } },
+ event: PostHogEventTypes
+) => {
+ void server.services.telemetry.sendPostHogEvents({
+ event,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: { orgId: req.permission.orgId }
+ } as Parameters<typeof server.services.telemetry.sendPostHogEvents>[0]);
+};
+
+/* eslint-disable @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any */
+const registerResourceMemberRoutes = (server: FastifyZodProvider, cfg: ResourceMemberConfig) => {
+ const scopeParam = z.object({ [cfg.scopeKey]: z.string().uuid() });
+ const svc: Record<string, (...args: any[]) => any> = server.services.pamMembership as never;
+
+ server.route({
+ method: "GET",
+ url: `${cfg.urlPrefix}/users`,
+ schema: {
+ operationId: `list${cfg.operationPrefix}Members`,
+ params: scopeParam,
+ response: { 200: z.array(MemberSchema) }
+ },
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ return svc[cfg.listMembers]({
+ ...actorCtx(req),
+ [cfg.scopeKey]: req.params[cfg.scopeKey]
+ });
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: `${cfg.urlPrefix}/users`,
+ schema: {
+ operationId: `add${cfg.operationPrefix}UserMember`,
+ params: scopeParam,
+ body: z.object({ userId: z.string().uuid(), role: z.nativeEnum(PamResourceRole) }),
+ response: { 200: cfg.resultSchema }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const scopeId = req.params[cfg.scopeKey];
+ const membership = await svc[cfg.addMember]({
+ ...actorCtx(req),
+ [cfg.scopeKey]: scopeId,
+ userId: req.body.userId,
+ role: req.body.role
+ });
+
+ await emitAuditLog(server, req, cfg.events.add, {
+ [cfg.scopeKey]: scopeId,
+ userId: req.body.userId,
+ role: req.body.role
+ });
+ emitTelemetry(server, req, cfg.telemetry.add);
+ return membership;
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: `${cfg.urlPrefix}/users/:userId`,
+ schema: {
+ operationId: `update${cfg.operationPrefix}UserMemberRole`,
+ params: scopeParam.extend({ userId: z.string().uuid() }),
+ body: z.object({ role: z.nativeEnum(PamResourceRole) }),
+ response: { 200: cfg.resultSchema.omit({ createdAt: true }) }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const scopeId = req.params[cfg.scopeKey];
+ const membership = await svc[cfg.updateMemberRole]({
+ ...actorCtx(req),
+ [cfg.scopeKey]: scopeId,
+ userId: req.params.userId,
+ role: req.body.role
+ });
+ await emitAuditLog(server, req, cfg.events.update, {
+ [cfg.scopeKey]: scopeId,
+ userId: req.params.userId,
+ role: req.body.role
+ });
+ emitTelemetry(server, req, cfg.telemetry.update);
+ return membership;
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: `${cfg.urlPrefix}/users/:userId`,
+ schema: {
+ operationId: `remove${cfg.operationPrefix}UserMember`,
+ params: scopeParam.extend({ userId: z.string().uuid() }),
+ response: {
+ 200: cfg.resultSchema.pick({ membershipId: true, [cfg.scopeKey]: true, userId: true } as Record<string, true>)
+ }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const scopeId = req.params[cfg.scopeKey];
+ const membership = await svc[cfg.removeMember]({
+ ...actorCtx(req),
+ [cfg.scopeKey]: scopeId,
+ userId: req.params.userId
+ });
+ await emitAuditLog(server, req, cfg.events.remove, { [cfg.scopeKey]: scopeId, userId: req.params.userId });
+ emitTelemetry(server, req, cfg.telemetry.remove);
+ return membership;
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: `${cfg.urlPrefix}/groups/:groupId`,
+ schema: {
+ operationId: `add${cfg.operationPrefix}GroupMember`,
+ params: scopeParam.extend({ groupId: z.string().uuid() }),
+ body: z.object({ role: z.nativeEnum(PamResourceRole) }),
+ response: { 200: cfg.resultSchema }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const scopeId = req.params[cfg.scopeKey];
+ const membership = await svc[cfg.addMember]({
+ ...actorCtx(req),
+ [cfg.scopeKey]: scopeId,
+ groupId: req.params.groupId,
+ role: req.body.role
+ });
+ await emitAuditLog(server, req, cfg.events.add, {
+ [cfg.scopeKey]: scopeId,
+ groupId: req.params.groupId,
+ role: req.body.role
+ });
+ emitTelemetry(server, req, cfg.telemetry.add);
+ return membership;
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: `${cfg.urlPrefix}/groups/:groupId`,
+ schema: {
+ operationId: `update${cfg.operationPrefix}GroupMemberRole`,
+ params: scopeParam.extend({ groupId: z.string().uuid() }),
+ body: z.object({ role: z.nativeEnum(PamResourceRole) }),
+ response: { 200: cfg.resultSchema.omit({ createdAt: true }) }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const scopeId = req.params[cfg.scopeKey];
+ const membership = await svc[cfg.updateMemberRole]({
+ ...actorCtx(req),
+ [cfg.scopeKey]: scopeId,
+ groupId: req.params.groupId,
+ role: req.body.role
+ });
+ await emitAuditLog(server, req, cfg.events.update, {
+ [cfg.scopeKey]: scopeId,
+ groupId: req.params.groupId,
+ role: req.body.role
+ });
+ emitTelemetry(server, req, cfg.telemetry.update);
+ return membership;
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: `${cfg.urlPrefix}/groups/:groupId`,
+ schema: {
+ operationId: `remove${cfg.operationPrefix}GroupMember`,
+ params: scopeParam.extend({ groupId: z.string().uuid() }),
+ response: {
+ 200: cfg.resultSchema.pick({ membershipId: true, [cfg.scopeKey]: true, groupId: true } as Record<string, true>)
+ }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const scopeId = req.params[cfg.scopeKey];
+ const membership = await svc[cfg.removeMember]({
+ ...actorCtx(req),
+ [cfg.scopeKey]: scopeId,
+ groupId: req.params.groupId
+ });
+ await emitAuditLog(server, req, cfg.events.remove, { [cfg.scopeKey]: scopeId, groupId: req.params.groupId });
+ emitTelemetry(server, req, cfg.telemetry.remove);
+ return membership;
+ }
+ });
+};
+/* eslint-enable @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any */
+
+export const registerPamMembershipRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/users",
+ schema: {
+ operationId: "listPamProductMembers",
+ response: { 200: z.array(MemberSchema) }
+ },
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ return server.services.pamMembership.listProductMembers(actorCtx(req));
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/users",
+ schema: {
+ operationId: "addPamProductUserMember",
+ body: z.object({ userId: z.string().uuid(), role: z.nativeEnum(PamProductRole) }),
+ response: { 200: MemberResultSchema }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const membership = await server.services.pamMembership.addProductMember({
+ ...actorCtx(req),
+ userId: req.body.userId,
+ role: req.body.role
+ });
+
+ await emitAuditLog(server, req, EventType.PAM_PRODUCT_MEMBER_ADD, {
+ userId: req.body.userId,
+ role: req.body.role
+ });
+ emitTelemetry(server, req, PostHogEventTypes.PamProductMemberAdded);
+
+ return membership;
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/users/:userId",
+ schema: {
+ operationId: "updatePamProductUserMemberRole",
+ params: z.object({ userId: z.string().uuid() }),
+ body: z.object({ role: z.nativeEnum(PamProductRole) }),
+ response: { 200: MemberResultSchema.omit({ createdAt: true }) }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const membership = await server.services.pamMembership.updateProductMemberRole({
+ ...actorCtx(req),
+ userId: req.params.userId,
+ role: req.body.role
+ });
+
+ await emitAuditLog(server, req, EventType.PAM_PRODUCT_MEMBER_UPDATE, {
+ userId: req.params.userId,
+ role: req.body.role
+ });
+ emitTelemetry(server, req, PostHogEventTypes.PamProductMemberUpdated);
+
+ return membership;
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/users/:userId",
+ schema: {
+ operationId: "removePamProductUserMember",
+ params: z.object({ userId: z.string().uuid() }),
+ response: { 200: MemberResultSchema.pick({ membershipId: true, userId: true }) }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const membership = await server.services.pamMembership.removeProductMember({
+ ...actorCtx(req),
+ userId: req.params.userId
+ });
+
+ await emitAuditLog(server, req, EventType.PAM_PRODUCT_MEMBER_REMOVE, { userId: req.params.userId });
+ emitTelemetry(server, req, PostHogEventTypes.PamProductMemberRemoved);
+
+ return membership;
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/groups/:groupId",
+ schema: {
+ operationId: "addPamProductGroupMember",
+ params: z.object({ groupId: z.string().uuid() }),
+ body: z.object({ role: z.nativeEnum(PamProductRole) }),
+ response: { 200: MemberResultSchema }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const membership = await server.services.pamMembership.addProductMember({
+ ...actorCtx(req),
+ groupId: req.params.groupId,
+ role: req.body.role
+ });
+
+ await emitAuditLog(server, req, EventType.PAM_PRODUCT_MEMBER_ADD, {
+ groupId: req.params.groupId,
+ role: req.body.role
+ });
+ emitTelemetry(server, req, PostHogEventTypes.PamProductMemberAdded);
+
+ return membership;
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/groups/:groupId",
+ schema: {
+ operationId: "updatePamProductGroupMemberRole",
+ params: z.object({ groupId: z.string().uuid() }),
+ body: z.object({ role: z.nativeEnum(PamProductRole) }),
+ response: { 200: MemberResultSchema.omit({ createdAt: true }) }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const membership = await server.services.pamMembership.updateProductMemberRole({
+ ...actorCtx(req),
+ groupId: req.params.groupId,
+ role: req.body.role
+ });
+
+ await emitAuditLog(server, req, EventType.PAM_PRODUCT_MEMBER_UPDATE, {
+ groupId: req.params.groupId,
+ role: req.body.role
+ });
+ emitTelemetry(server, req, PostHogEventTypes.PamProductMemberUpdated);
+
+ return membership;
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/groups/:groupId",
+ schema: {
+ operationId: "removePamProductGroupMember",
+ params: z.object({ groupId: z.string().uuid() }),
+ response: { 200: MemberResultSchema.pick({ membershipId: true, groupId: true }) }
+ },
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const membership = await server.services.pamMembership.removeProductMember({
+ ...actorCtx(req),
+ groupId: req.params.groupId
+ });
+
+ await emitAuditLog(server, req, EventType.PAM_PRODUCT_MEMBER_REMOVE, { groupId: req.params.groupId });
+ emitTelemetry(server, req, PostHogEventTypes.PamProductMemberRemoved);
+
+ return membership;
+ }
+ });
+
+ const FolderMemberResultSchema = MemberResultSchema.extend({ folderId: z.string().uuid() });
+ const AccountMemberResultSchema = MemberResultSchema.extend({ accountId: z.string().uuid() });
+
+ registerResourceMemberRoutes(server, {
+ scopeKey: "folderId",
+ urlPrefix: "/folders/:folderId",
+ operationPrefix: "PamFolder",
+ resultSchema: FolderMemberResultSchema,
+ listMembers: "listFolderMembers",
+ addMember: "addFolderMember",
+ updateMemberRole: "updateFolderMemberRole",
+ removeMember: "removeFolderMember",
+ events: {
+ add: EventType.PAM_FOLDER_MEMBER_ADD,
+ update: EventType.PAM_FOLDER_MEMBER_UPDATE,
+ remove: EventType.PAM_FOLDER_MEMBER_REMOVE
+ },
+ telemetry: {
+ add: PostHogEventTypes.PamFolderMemberAdded,
+ update: PostHogEventTypes.PamFolderMemberUpdated,
+ remove: PostHogEventTypes.PamFolderMemberRemoved
+ }
+ });
+
+ registerResourceMemberRoutes(server, {
+ scopeKey: "accountId",
+ urlPrefix: "/accounts/:accountId",
+ operationPrefix: "PamAccount",
+ resultSchema: AccountMemberResultSchema,
+ listMembers: "listAccountMembers",
+ addMember: "addAccountMember",
+ updateMemberRole: "updateAccountMemberRole",
+ removeMember: "removeAccountMember",
+ events: {
+ add: EventType.PAM_ACCOUNT_MEMBER_ADD,
+ update: EventType.PAM_ACCOUNT_MEMBER_UPDATE,
+ remove: EventType.PAM_ACCOUNT_MEMBER_REMOVE
+ },
+ telemetry: {
+ add: PostHogEventTypes.PamAccountMemberAdded,
+ update: PostHogEventTypes.PamAccountMemberUpdated,
+ remove: PostHogEventTypes.PamAccountMemberRemoved
+ }
+ });
+};
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-resource-role-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-resource-role-router.ts
new file mode 100644
index 0000000000..cad999852d
--- /dev/null
+++ b/backend/src/ee/routes/v1/pam-routers/pam-resource-role-router.ts
@@ -0,0 +1,50 @@
+import z from "zod";
+
+import { PamResourceRole } from "@app/ee/services/pam/pam-enums";
+import { readLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+const DEFAULT_RESOURCE_ROLES = [
+ {
+ slug: PamResourceRole.Admin,
+ name: "Admin",
+ isDefault: true,
+ description: "Full control of accounts, folders, sessions, and grants"
+ },
+ {
+ slug: PamResourceRole.Requester,
+ name: "Requester",
+ isDefault: true,
+ description: "Submit access requests; cannot view credentials directly"
+ },
+ {
+ slug: PamResourceRole.Auditor,
+ name: "Auditor",
+ isDefault: true,
+ description: "View audit logs and session recordings; no access changes"
+ }
+];
+
+const ResourceRoleSchema = z.object({
+ slug: z.string(),
+ name: z.string(),
+ isDefault: z.boolean(),
+ description: z.string()
+});
+
+export const registerPamResourceRoleRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/",
+ schema: {
+ operationId: "listPamResourceRoles",
+ response: { 200: z.array(ResourceRoleSchema) }
+ },
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async () => {
+ return DEFAULT_RESOURCE_ROLES;
+ }
+ });
+};
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 2179d4b357..344682deed 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -1,6 +1,5 @@
import { ProjectType } from "@app/db/schemas";
import { HoneyTokenType } from "@app/ee/services/honey-token/honey-token-enums";
-import { PamParentType } from "@app/ee/services/pam-account/pam-account-enums";
import { ScepChallengeType } from "@app/ee/services/pki-scep/challenge";
import {
TCreateProjectTemplateDTO,
@@ -695,9 +694,21 @@ export enum EventType {
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_ACCOUNT_TEMPLATE_CREATE = "pam-account-template-create",
+ PAM_ACCOUNT_TEMPLATE_UPDATE = "pam-account-template-update",
+ PAM_ACCOUNT_TEMPLATE_DELETE = "pam-account-template-delete",
PAM_FOLDER_CREATE = "pam-folder-create",
PAM_FOLDER_UPDATE = "pam-folder-update",
PAM_FOLDER_DELETE = "pam-folder-delete",
+ PAM_PRODUCT_MEMBER_ADD = "pam-product-member-add",
+ PAM_PRODUCT_MEMBER_UPDATE = "pam-product-member-update",
+ PAM_PRODUCT_MEMBER_REMOVE = "pam-product-member-remove",
+ PAM_FOLDER_MEMBER_ADD = "pam-folder-member-add",
+ PAM_FOLDER_MEMBER_UPDATE = "pam-folder-member-update",
+ PAM_FOLDER_MEMBER_REMOVE = "pam-folder-member-remove",
+ PAM_ACCOUNT_MEMBER_ADD = "pam-account-member-add",
+ PAM_ACCOUNT_MEMBER_UPDATE = "pam-account-member-update",
+ PAM_ACCOUNT_MEMBER_REMOVE = "pam-account-member-remove",
PAM_ACCOUNT_LIST = "pam-account-list",
PAM_ACCOUNT_GET = "pam-account-get",
PAM_ACCOUNT_ACCESS = "pam-account-access",
@@ -714,31 +725,6 @@ export enum EventType {
PAM_ACCOUNT_POLICY_GET = "pam-account-policy-get",
PAM_ACCOUNT_READ_CREDENTIALS = "pam-account-read-credentials",
PAM_WEB_ACCESS_SESSION_TICKET_CREATED = "pam-web-access-session-ticket-created",
- PAM_RESOURCE_LIST = "pam-resource-list",
- PAM_RESOURCE_GET = "pam-resource-get",
- PAM_RESOURCE_CREATE = "pam-resource-create",
- PAM_RESOURCE_UPDATE = "pam-resource-update",
- PAM_RESOURCE_DELETE = "pam-resource-delete",
- PAM_DOMAIN_LIST = "pam-domain-list",
- PAM_DOMAIN_GET = "pam-domain-get",
- PAM_DOMAIN_CREATE = "pam-domain-create",
- PAM_DOMAIN_UPDATE = "pam-domain-update",
- PAM_DOMAIN_DELETE = "pam-domain-delete",
- PAM_DISCOVERY_SOURCE_LIST = "pam-discovery-source-list",
- PAM_DISCOVERY_SOURCE_GET = "pam-discovery-source-get",
- PAM_DISCOVERY_SOURCE_CREATE = "pam-discovery-source-create",
- PAM_DISCOVERY_SOURCE_UPDATE = "pam-discovery-source-update",
- PAM_DISCOVERY_SOURCE_DELETE = "pam-discovery-source-delete",
- PAM_DISCOVERY_SCAN = "pam-discovery-scan",
- PAM_DISCOVERY_SOURCE_RUN_LIST = "pam-discovery-source-run-list",
- PAM_DISCOVERY_SOURCE_RUN_GET = "pam-discovery-source-run-get",
- PAM_DISCOVERY_SOURCE_RESOURCE_LIST = "pam-discovery-source-resource-list",
- PAM_DISCOVERY_SOURCE_ACCOUNT_LIST = "pam-discovery-source-account-list",
- PAM_RESOURCE_ROTATION_RULE_LIST = "pam-resource-rotation-rule-list",
- PAM_RESOURCE_ROTATION_RULE_CREATE = "pam-resource-rotation-rule-create",
- 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",
APPROVAL_POLICY_CREATE = "approval-policy-create",
APPROVAL_POLICY_UPDATE = "approval-policy-update",
APPROVAL_POLICY_DELETE = "approval-policy-delete",
@@ -5830,10 +5816,35 @@ interface PamRecordingBucketConnectionTestFailedEvent {
};
}
+interface PamAccountTemplateCreateEvent {
+ type: EventType.PAM_ACCOUNT_TEMPLATE_CREATE;
+ metadata: {
+ templateId: string;
+ name: string;
+ accountType: string;
+ };
+}
+
+interface PamAccountTemplateUpdateEvent {
+ type: EventType.PAM_ACCOUNT_TEMPLATE_UPDATE;
+ metadata: {
+ templateId: string;
+ name?: string;
+ };
+}
+
+interface PamAccountTemplateDeleteEvent {
+ type: EventType.PAM_ACCOUNT_TEMPLATE_DELETE;
+ metadata: {
+ templateId: string;
+ name: string;
+ };
+}
+
interface PamFolderCreateEvent {
type: EventType.PAM_FOLDER_CREATE;
metadata: {
- parentId?: string | null;
+ folderId: string;
name: string;
description?: string | null;
};
@@ -5856,6 +5867,90 @@ interface PamFolderDeleteEvent {
};
}
+interface PamProductMemberAddEvent {
+ type: EventType.PAM_PRODUCT_MEMBER_ADD;
+ metadata: {
+ userId?: string;
+ groupId?: string;
+ role: string;
+ };
+}
+
+interface PamProductMemberUpdateEvent {
+ type: EventType.PAM_PRODUCT_MEMBER_UPDATE;
+ metadata: {
+ userId?: string;
+ groupId?: string;
+ role: string;
+ };
+}
+
+interface PamProductMemberRemoveEvent {
+ type: EventType.PAM_PRODUCT_MEMBER_REMOVE;
+ metadata: {
+ userId?: string;
+ groupId?: string;
+ };
+}
+
+interface PamFolderMemberAddEvent {
+ type: EventType.PAM_FOLDER_MEMBER_ADD;
+ metadata: {
+ folderId: string;
+ userId?: string;
+ groupId?: string;
+ role: string;
+ };
+}
+
+interface PamFolderMemberUpdateEvent {
+ type: EventType.PAM_FOLDER_MEMBER_UPDATE;
+ metadata: {
+ folderId: string;
+ userId?: string;
+ groupId?: string;
+ role: string;
+ };
+}
+
+interface PamFolderMemberRemoveEvent {
+ type: EventType.PAM_FOLDER_MEMBER_REMOVE;
+ metadata: {
+ folderId: string;
+ userId?: string;
+ groupId?: string;
+ };
+}
+
+interface PamAccountMemberAddEvent {
+ type: EventType.PAM_ACCOUNT_MEMBER_ADD;
+ metadata: {
+ accountId: string;
+ userId?: string;
+ groupId?: string;
+ role: string;
+ };
+}
+
+interface PamAccountMemberUpdateEvent {
+ type: EventType.PAM_ACCOUNT_MEMBER_UPDATE;
+ metadata: {
+ accountId: string;
+ userId?: string;
+ groupId?: string;
+ role: string;
+ };
+}
+
+interface PamAccountMemberRemoveEvent {
+ type: EventType.PAM_ACCOUNT_MEMBER_REMOVE;
+ metadata: {
+ accountId: string;
+ userId?: string;
+ groupId?: string;
+ };
+}
+
interface PamAccountListEvent {
type: EventType.PAM_ACCOUNT_LIST;
metadata: {
@@ -5904,13 +5999,12 @@ interface PamAccountAwsConsoleUrlGeneratedEvent {
interface PamAccountCreateEvent {
type: EventType.PAM_ACCOUNT_CREATE;
metadata: {
- resourceId?: string | null;
- domainId?: string | null;
- parentType: PamParentType;
- folderId?: string | null;
+ accountId: string;
+ accountType: string;
+ folderId: string;
+ templateId: string;
name: string;
description?: string | null;
- requireMfa?: boolean | null;
};
}
@@ -5918,23 +6012,18 @@ interface PamAccountUpdateEvent {
type: EventType.PAM_ACCOUNT_UPDATE;
metadata: {
accountId: string;
- resourceId?: string | null;
- domainId?: string | null;
- parentType: PamParentType;
+ accountType: string;
name?: string;
description?: string | null;
- requireMfa?: boolean | null;
};
}
interface PamAccountDeleteEvent {
type: EventType.PAM_ACCOUNT_DELETE;
metadata: {
- accountName: string;
accountId: string;
- resourceId?: string | null;
- domainId?: string | null;
- parentType: PamParentType;
+ accountType: string;
+ accountName: string;
};
}
@@ -6014,243 +6103,6 @@ interface PamAccountReadCredentialsEvent {
};
}
-interface PamResourceListEvent {
- type: EventType.PAM_RESOURCE_LIST;
- metadata: {
- count: number;
- };
-}
-
-interface PamResourceGetEvent {
- type: EventType.PAM_RESOURCE_GET;
- metadata: {
- resourceId: string;
- resourceType: string;
- name: string;
- };
-}
-
-interface PamResourceCreateEvent {
- type: EventType.PAM_RESOURCE_CREATE;
- metadata: {
- resourceType: string;
- gatewayId?: string;
- name: string;
- };
-}
-
-interface PamResourceUpdateEvent {
- type: EventType.PAM_RESOURCE_UPDATE;
- metadata: {
- resourceId: string;
- resourceType: string;
- gatewayId?: string;
- name?: string;
- };
-}
-
-interface PamResourceDeleteEvent {
- type: EventType.PAM_RESOURCE_DELETE;
- metadata: {
- resourceId: string;
- resourceType: string;
- };
-}
-
-interface PamDomainListEvent {
- type: EventType.PAM_DOMAIN_LIST;
- metadata: {
- count: number;
- };
-}
-
-interface PamDomainGetEvent {
- type: EventType.PAM_DOMAIN_GET;
- metadata: {
- domainId: string;
- domainType: string;
- name: string;
- };
-}
-
-interface PamDomainCreateEvent {
- type: EventType.PAM_DOMAIN_CREATE;
- metadata: {
- domainType: string;
- gatewayId?: string;
- name: string;
- };
-}
-
-interface PamDomainUpdateEvent {
- type: EventType.PAM_DOMAIN_UPDATE;
- metadata: {
- domainId: string;
- domainType: string;
- gatewayId?: string;
- name?: string;
- };
-}
-
-interface PamDomainDeleteEvent {
- type: EventType.PAM_DOMAIN_DELETE;
- metadata: {
- domainId: string;
- domainType: string;
- };
-}
-
-interface PamDiscoverySourceListEvent {
- type: EventType.PAM_DISCOVERY_SOURCE_LIST;
- metadata: {
- count: number;
- };
-}
-
-interface PamDiscoverySourceGetEvent {
- type: EventType.PAM_DISCOVERY_SOURCE_GET;
- metadata: {
- sourceId: string;
- sourceName: string;
- discoveryType: string;
- name: string;
- };
-}
-
-interface PamDiscoverySourceCreateEvent {
- type: EventType.PAM_DISCOVERY_SOURCE_CREATE;
- metadata: {
- sourceName: string;
- discoveryType: string;
- gatewayId?: string | null;
- name: string;
- };
-}
-
-interface PamDiscoverySourceUpdateEvent {
- type: EventType.PAM_DISCOVERY_SOURCE_UPDATE;
- metadata: {
- sourceId: string;
- sourceName: string;
- discoveryType: string;
- gatewayId?: string | null;
- newSourceName?: string;
- };
-}
-
-interface PamDiscoverySourceDeleteEvent {
- type: EventType.PAM_DISCOVERY_SOURCE_DELETE;
- metadata: {
- sourceId: string;
- sourceName: string;
- discoveryType: string;
- };
-}
-
-interface PamDiscoveryScanEvent {
- type: EventType.PAM_DISCOVERY_SCAN;
- metadata: {
- sourceId: string;
- sourceName: string;
- discoveryType: string;
- };
-}
-
-interface PamDiscoverySourceRunListEvent {
- type: EventType.PAM_DISCOVERY_SOURCE_RUN_LIST;
- metadata: {
- sourceId: string;
- sourceName: string;
- discoveryType: string;
- count: number;
- };
-}
-
-interface PamDiscoverySourceRunGetEvent {
- type: EventType.PAM_DISCOVERY_SOURCE_RUN_GET;
- metadata: {
- sourceId: string;
- sourceName: string;
- discoveryType: string;
- runId: string;
- };
-}
-
-interface PamDiscoverySourceResourceListEvent {
- type: EventType.PAM_DISCOVERY_SOURCE_RESOURCE_LIST;
- metadata: {
- sourceId: string;
- sourceName: string;
- discoveryType: string;
- count: number;
- };
-}
-
-interface PamDiscoverySourceAccountListEvent {
- type: EventType.PAM_DISCOVERY_SOURCE_ACCOUNT_LIST;
- metadata: {
- sourceId: string;
- sourceName: string;
- discoveryType: string;
- count: number;
- };
-}
-
-interface PamResourceRotationRuleListEvent {
- type: EventType.PAM_RESOURCE_ROTATION_RULE_LIST;
- metadata: {
- resourceId: string;
- resourceName: string;
- count: number;
- };
-}
-
-interface PamResourceRotationRuleCreateEvent {
- type: EventType.PAM_RESOURCE_ROTATION_RULE_CREATE;
- metadata: {
- resourceId: string;
- resourceName: string;
- ruleId: string;
- ruleName?: string;
- namePattern: string;
- enabled: boolean;
- intervalSeconds?: number | null;
- };
-}
-
-interface PamResourceRotationRuleUpdateEvent {
- type: EventType.PAM_RESOURCE_ROTATION_RULE_UPDATE;
- metadata: {
- resourceId: string;
- resourceName: string;
- ruleId: string;
- ruleName?: string | null;
- namePattern?: string;
- enabled?: boolean;
- intervalSeconds?: number | null;
- };
-}
-
-interface PamResourceRotationRuleDeleteEvent {
- type: EventType.PAM_RESOURCE_ROTATION_RULE_DELETE;
- metadata: {
- resourceId: string;
- resourceName: string;
- ruleId: string;
- ruleName?: string | null;
- namePattern: string;
- };
-}
-
-interface PamResourceRotationRuleReorderEvent {
- type: EventType.PAM_RESOURCE_ROTATION_RULE_REORDER;
- metadata: {
- resourceId: string;
- resourceName: string;
- ruleIds: string[];
- };
-}
-
interface UpdateCertificateRenewalConfigEvent {
type: EventType.UPDATE_CERTIFICATE_RENEWAL_CONFIG;
metadata: {
@@ -7764,9 +7616,21 @@ export type Event =
| PamRecordingConfigUpsertEvent
| PamRecordingConfigDeleteEvent
| PamRecordingBucketConnectionTestFailedEvent
+ | PamAccountTemplateCreateEvent
+ | PamAccountTemplateUpdateEvent
+ | PamAccountTemplateDeleteEvent
| PamFolderCreateEvent
| PamFolderUpdateEvent
| PamFolderDeleteEvent
+ | PamProductMemberAddEvent
+ | PamProductMemberUpdateEvent
+ | PamProductMemberRemoveEvent
+ | PamFolderMemberAddEvent
+ | PamFolderMemberUpdateEvent
+ | PamFolderMemberRemoveEvent
+ | PamAccountMemberAddEvent
+ | PamAccountMemberUpdateEvent
+ | PamAccountMemberRemoveEvent
| PamAccountListEvent
| PamAccountGetEvent
| PamAccountAccessEvent
@@ -7783,31 +7647,6 @@ export type Event =
| PamAccountPolicyListEvent
| PamAccountPolicyGetEvent
| PamAccountReadCredentialsEvent
- | PamResourceListEvent
- | PamResourceGetEvent
- | PamResourceCreateEvent
- | PamResourceUpdateEvent
- | PamResourceDeleteEvent
- | PamDomainListEvent
- | PamDomainGetEvent
- | PamDomainCreateEvent
- | PamDomainUpdateEvent
- | PamDomainDeleteEvent
- | PamDiscoverySourceListEvent
- | PamDiscoverySourceGetEvent
- | PamDiscoverySourceCreateEvent
- | PamDiscoverySourceUpdateEvent
- | PamDiscoverySourceDeleteEvent
- | PamDiscoveryScanEvent
- | PamDiscoverySourceRunListEvent
- | PamDiscoverySourceRunGetEvent
- | PamDiscoverySourceResourceListEvent
- | PamDiscoverySourceAccountListEvent
- | PamResourceRotationRuleListEvent
- | PamResourceRotationRuleCreateEvent
- | PamResourceRotationRuleUpdateEvent
- | PamResourceRotationRuleDeleteEvent
- | PamResourceRotationRuleReorderEvent
| UpdateCertificateRenewalConfigEvent
| UpdateCertificateMetadataEvent
| DisableCertificateRenewalConfigEvent
diff --git a/backend/src/ee/services/pam-account-template/pam-account-template-dal.ts b/backend/src/ee/services/pam-account-template/pam-account-template-dal.ts
new file mode 100644
index 0000000000..63d9ea15ff
--- /dev/null
+++ b/backend/src/ee/services/pam-account-template/pam-account-template-dal.ts
@@ -0,0 +1,38 @@
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { sanitizeSqlLikeString } from "@app/lib/fn";
+import { ormify } from "@app/lib/knex";
+
+import { PamAccountType } from "../pam/pam-enums";
+
+export type TPamAccountTemplateDALFactory = ReturnType<typeof pamAccountTemplateDALFactory>;
+
+export const pamAccountTemplateDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.PamAccountTemplate);
+
+ const findByProjectId = async (projectId: string, filters?: { search?: string; type?: PamAccountType }) => {
+ const qb = db.replicaNode()(TableName.PamAccountTemplate).where({ projectId });
+
+ if (filters?.search) {
+ const sanitized = sanitizeSqlLikeString(filters.search);
+ void qb.where((inner) => {
+ void inner.whereILike("name", `%${sanitized}%`).orWhereILike("type", `%${sanitized}%`);
+ });
+ }
+ if (filters?.type) {
+ void qb.where("type", filters.type);
+ }
+
+ return qb.orderBy("name", "asc");
+ };
+
+ const countAccountsByTemplateId = async (templateId: string) => {
+ const [result] = (await db
+ .replicaNode()(TableName.PamAccount)
+ .where({ templateId })
+ .count("id as count")) as unknown as [{ count: string }];
+ return Number(result.count);
+ };
+
+ return { ...orm, findByProjectId, countAccountsByTemplateId };
+};
diff --git a/backend/src/ee/services/pam-account-template/pam-account-template-service.ts b/backend/src/ee/services/pam-account-template/pam-account-template-service.ts
new file mode 100644
index 0000000000..3ff8be8b60
--- /dev/null
+++ b/backend/src/ee/services/pam-account-template/pam-account-template-service.ts
@@ -0,0 +1,168 @@
+import { ActionProjectType } from "@app/db/schemas";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { DatabaseErrorCode } from "@app/lib/error-codes";
+import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
+
+import { PamProductRole } from "../pam/pam-enums";
+import { TPamAccountTemplateDALFactory } from "./pam-account-template-dal";
+import {
+ TCreatePamAccountTemplateDTO,
+ TDeletePamAccountTemplateDTO,
+ TGetPamAccountTemplateDTO,
+ TListPamAccountTemplatesDTO,
+ TUpdatePamAccountTemplateDTO
+} from "./pam-account-template-types";
+
+type TActorContext = {
+ actorId: string;
+ actor: ActorType;
+ actorOrgId: string;
+ actorAuthMethod: ActorAuthMethod;
+};
+
+type TPamAccountTemplateServiceFactoryDep = {
+ pamAccountTemplateDAL: TPamAccountTemplateDALFactory;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+};
+
+export type TPamAccountTemplateServiceFactory = ReturnType<typeof pamAccountTemplateServiceFactory>;
+
+export const pamAccountTemplateServiceFactory = ({
+ pamAccountTemplateDAL,
+ permissionService
+}: TPamAccountTemplateServiceFactoryDep) => {
+ const verifyProductMembership = async (projectId: string, ctx: TActorContext) => {
+ const { hasRole } = await permissionService.getProjectPermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId,
+ actionProjectType: ActionProjectType.PAM
+ });
+ return { hasRole };
+ };
+
+ const verifyProductAdmin = async (projectId: string, ctx: TActorContext) => {
+ const { hasRole } = await verifyProductMembership(projectId, ctx);
+ if (!hasRole(PamProductRole.Admin)) {
+ throw new ForbiddenRequestError({ message: "Only PAM product admins can perform this action" });
+ }
+ };
+
+ const list = async ({ projectId, search, type, ...ctx }: TListPamAccountTemplatesDTO & TActorContext) => {
+ await verifyProductMembership(projectId, ctx);
+ return pamAccountTemplateDAL.findByProjectId(projectId, { search, type });
+ };
+
+ const getById = async ({ templateId, projectId, ...ctx }: TGetPamAccountTemplateDTO & TActorContext) => {
+ await verifyProductMembership(projectId, ctx);
+
+ const template = await pamAccountTemplateDAL.findById(templateId);
+ if (!template || template.projectId !== projectId) {
+ throw new NotFoundError({ message: `Account template with ID '${templateId}' not found` });
+ }
+
+ const accountCount = await pamAccountTemplateDAL.countAccountsByTemplateId(templateId);
+ return { ...template, accountCount };
+ };
+
+ const create = async ({
+ projectId,
+ name,
+ description,
+ type,
+ accessPolicy,
+ settings,
+ gatewayId,
+ gatewayPoolId,
+ recordingConnectionId,
+ ...ctx
+ }: TCreatePamAccountTemplateDTO & TActorContext) => {
+ await verifyProductAdmin(projectId, ctx);
+
+ try {
+ return await pamAccountTemplateDAL.create({
+ projectId,
+ name,
+ description,
+ type,
+ accessPolicy: accessPolicy ? JSON.stringify(accessPolicy) : undefined,
+ settings: settings ? JSON.stringify(settings) : undefined,
+ gatewayId,
+ gatewayPoolId,
+ recordingConnectionId
+ });
+ } catch (err) {
+ if (
+ err instanceof DatabaseError &&
+ (err as DatabaseError & { code?: string }).code === DatabaseErrorCode.UniqueViolation
+ ) {
+ throw new BadRequestError({ message: `A template named "${name}" already exists` });
+ }
+ throw err;
+ }
+ };
+
+ const update = async ({
+ templateId,
+ projectId,
+ name,
+ description,
+ accessPolicy,
+ settings,
+ gatewayId,
+ gatewayPoolId,
+ recordingConnectionId,
+ ...ctx
+ }: TUpdatePamAccountTemplateDTO & TActorContext) => {
+ await verifyProductAdmin(projectId, ctx);
+
+ const existing = await pamAccountTemplateDAL.findById(templateId);
+ if (!existing || existing.projectId !== projectId) {
+ throw new NotFoundError({ message: `Account template with ID '${templateId}' not found` });
+ }
+
+ const updateData: Record<string, unknown> = {};
+ if (name !== undefined) updateData.name = name;
+ if (description !== undefined) updateData.description = description;
+ if (accessPolicy !== undefined) updateData.accessPolicy = JSON.stringify(accessPolicy);
+ if (settings !== undefined) updateData.settings = JSON.stringify(settings);
+ if (gatewayId !== undefined) updateData.gatewayId = gatewayId;
+ if (gatewayPoolId !== undefined) updateData.gatewayPoolId = gatewayPoolId;
+ if (recordingConnectionId !== undefined) updateData.recordingConnectionId = recordingConnectionId;
+
+ try {
+ return await pamAccountTemplateDAL.updateById(templateId, updateData);
+ } catch (err) {
+ if (
+ err instanceof DatabaseError &&
+ (err as DatabaseError & { code?: string }).code === DatabaseErrorCode.UniqueViolation
+ ) {
+ throw new BadRequestError({ message: `A template named "${name}" already exists` });
+ }
+ throw err;
+ }
+ };
+
+ const deleteTemplate = async ({ templateId, projectId, ...ctx }: TDeletePamAccountTemplateDTO & TActorContext) => {
+ await verifyProductAdmin(projectId, ctx);
+
+ const existing = await pamAccountTemplateDAL.findById(templateId);
+ if (!existing || existing.projectId !== projectId) {
+ throw new NotFoundError({ message: `Account template with ID '${templateId}' not found` });
+ }
+
+ const accountCount = await pamAccountTemplateDAL.countAccountsByTemplateId(templateId);
+ if (accountCount > 0) {
+ throw new BadRequestError({
+ message: `Cannot delete template "${existing.name}" because ${accountCount} account(s) still reference it`
+ });
+ }
+
+ return pamAccountTemplateDAL.deleteById(templateId);
+ };
+
+ return { list, getById, create, update, deleteTemplate };
+};
diff --git a/backend/src/ee/services/pam-account-template/pam-account-template-types.ts b/backend/src/ee/services/pam-account-template/pam-account-template-types.ts
new file mode 100644
index 0000000000..b9c62ad9b2
--- /dev/null
+++ b/backend/src/ee/services/pam-account-template/pam-account-template-types.ts
@@ -0,0 +1,42 @@
+import { PamAccountType } from "../pam/pam-enums";
+import { TPamTemplateAccessPolicy, TPamTemplateSettings } from "../pam/pam-template-config-schemas";
+
+export type TCreatePamAccountTemplateDTO = {
+ projectId: string;
+ name: string;
+ description?: string;
+ type: PamAccountType;
+ accessPolicy?: TPamTemplateAccessPolicy;
+ settings?: TPamTemplateSettings;
+ gatewayId?: string;
+ gatewayPoolId?: string;
+ recordingConnectionId?: string;
+};
+
+export type TUpdatePamAccountTemplateDTO = {
+ templateId: string;
+ projectId: string;
+ name?: string;
+ description?: string | null;
+ accessPolicy?: TPamTemplateAccessPolicy;
+ settings?: TPamTemplateSettings;
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+ recordingConnectionId?: string | null;
+};
+
+export type TDeletePamAccountTemplateDTO = {
+ templateId: string;
+ projectId: string;
+};
+
+export type TGetPamAccountTemplateDTO = {
+ templateId: string;
+ projectId: string;
+};
+
+export type TListPamAccountTemplatesDTO = {
+ projectId: string;
+ search?: string;
+ type?: PamAccountType;
+};
diff --git a/backend/src/ee/services/pam-account/pam-account-dal.ts b/backend/src/ee/services/pam-account/pam-account-dal.ts
new file mode 100644
index 0000000000..565f67997f
--- /dev/null
+++ b/backend/src/ee/services/pam-account/pam-account-dal.ts
@@ -0,0 +1,108 @@
+import { TDbClient } from "@app/db";
+import { TableName, TPamAccounts } from "@app/db/schemas";
+import { sanitizeSqlLikeString } from "@app/lib/fn";
+import { ormify } from "@app/lib/knex";
+
+export type TPamAccountListItem = Pick<
+ TPamAccounts,
+ | "id"
+ | "name"
+ | "description"
+ | "folderId"
+ | "projectId"
+ | "templateId"
+ | "gatewayId"
+ | "gatewayPoolId"
+ | "recordingConnectionId"
+ | "createdAt"
+ | "updatedAt"
+> & {
+ accountType: string;
+ templateName: string;
+ folderName: string | null;
+};
+
+export type TPamAccountDetail = TPamAccounts & {
+ accountType: string;
+ templateName: string;
+ templateAccessPolicy: unknown;
+ templateSettings: unknown;
+ folderName: string | null;
+};
+
+export type TPamAccountDALFactory = ReturnType<typeof pamAccountDALFactory>;
+
+export const pamAccountDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.PamAccount);
+
+ const findAccessible = async (
+ projectId: string,
+ accessibleFolderIds: string[],
+ accessibleAccountIds: string[],
+ filters?: { folderId?: string; templateId?: string; search?: string }
+ ): Promise<TPamAccountListItem[]> => {
+ const qb = db
+ .replicaNode()(TableName.PamAccount)
+ .join(TableName.PamAccountTemplate, `${TableName.PamAccount}.templateId`, `${TableName.PamAccountTemplate}.id`)
+ .leftJoin(TableName.PamFolder, `${TableName.PamAccount}.folderId`, `${TableName.PamFolder}.id`)
+ .where(`${TableName.PamAccount}.projectId`, projectId)
+ .where((builder) => {
+ if (accessibleFolderIds.length > 0) {
+ void builder.whereIn(`${TableName.PamAccount}.folderId`, accessibleFolderIds);
+ }
+ if (accessibleAccountIds.length > 0) {
+ void builder.orWhereIn(`${TableName.PamAccount}.id`, accessibleAccountIds);
+ }
+ })
+ .select(
+ `${TableName.PamAccount}.id`,
+ `${TableName.PamAccount}.name`,
+ `${TableName.PamAccount}.description`,
+ `${TableName.PamAccount}.folderId`,
+ `${TableName.PamAccount}.projectId`,
+ `${TableName.PamAccount}.templateId`,
+ `${TableName.PamAccount}.gatewayId`,
+ `${TableName.PamAccount}.gatewayPoolId`,
+ `${TableName.PamAccount}.recordingConnectionId`,
+ `${TableName.PamAccount}.createdAt`,
+ `${TableName.PamAccount}.updatedAt`,
+ `${TableName.PamAccountTemplate}.type as accountType`,
+ `${TableName.PamAccountTemplate}.name as templateName`,
+ `${TableName.PamFolder}.name as folderName`
+ );
+
+ if (filters?.folderId) {
+ void qb.where(`${TableName.PamAccount}.folderId`, filters.folderId);
+ }
+ if (filters?.templateId) {
+ void qb.where(`${TableName.PamAccount}.templateId`, filters.templateId);
+ }
+ if (filters?.search) {
+ void qb.whereILike(`${TableName.PamAccount}.name`, `%${sanitizeSqlLikeString(filters.search)}%`);
+ }
+
+ return qb
+ .orderBy(`${TableName.PamFolder}.name`, "asc")
+ .orderBy(`${TableName.PamAccount}.name`, "asc") as unknown as Promise<TPamAccountListItem[]>;
+ };
+
+ const findByIdWithDetails = async (accountId: string): Promise<TPamAccountDetail | null> => {
+ const rows = (await db
+ .replicaNode()(TableName.PamAccount)
+ .join(TableName.PamAccountTemplate, `${TableName.PamAccount}.templateId`, `${TableName.PamAccountTemplate}.id`)
+ .leftJoin(TableName.PamFolder, `${TableName.PamAccount}.folderId`, `${TableName.PamFolder}.id`)
+ .where(`${TableName.PamAccount}.id`, accountId)
+ .select(
+ `${TableName.PamAccount}.*`,
+ `${TableName.PamAccountTemplate}.type as accountType`,
+ `${TableName.PamAccountTemplate}.name as templateName`,
+ `${TableName.PamAccountTemplate}.accessPolicy as templateAccessPolicy`,
+ `${TableName.PamAccountTemplate}.settings as templateSettings`,
+ `${TableName.PamFolder}.name as folderName`
+ )) as unknown as TPamAccountDetail[];
+
+ return rows[0] || null;
+ };
+
+ return { ...orm, findAccessible, findByIdWithDetails };
+};
diff --git a/backend/src/ee/services/pam-account/pam-account-schemas.ts b/backend/src/ee/services/pam-account/pam-account-schemas.ts
new file mode 100644
index 0000000000..a1431604c1
--- /dev/null
+++ b/backend/src/ee/services/pam-account/pam-account-schemas.ts
@@ -0,0 +1,64 @@
+import { z } from "zod";
+
+import { PamAccountType } from "../pam/pam-enums";
+
+const ACCOUNT_TYPE_CONFIGS = {
+ [PamAccountType.Postgres]: {
+ connectionDetails: z.object({
+ host: z.string().trim().min(1).max(255),
+ port: z.coerce.number(),
+ database: z.string().trim().min(1).max(255),
+ sslEnabled: z.boolean(),
+ sslRejectUnauthorized: z.boolean(),
+ sslCertificate: z
+ .string()
+ .trim()
+ .transform((v) => v || undefined)
+ .optional()
+ }),
+ credentials: z.object({
+ username: z.string().trim().min(1).max(63),
+ password: z.string().trim().min(1).max(256)
+ })
+ },
+
+ [PamAccountType.SSH]: {
+ connectionDetails: z.object({
+ host: z.string().trim().min(1).max(255),
+ port: z.coerce.number()
+ }),
+ credentials: z.discriminatedUnion("authMethod", [
+ z.object({
+ authMethod: z.literal("password"),
+ username: z.string().trim().min(1),
+ password: z.string().trim().min(1)
+ }),
+ z.object({
+ authMethod: z.literal("public-key"),
+ username: z.string().trim().min(1),
+ privateKey: z.string().trim().min(1).max(5000)
+ }),
+ z.object({ authMethod: z.literal("certificate"), username: z.string().trim().min(1) })
+ ])
+ }
+} as const satisfies Partial<Record<PamAccountType, { connectionDetails: z.ZodTypeAny; credentials: z.ZodTypeAny }>>;
+
+type TSupportedAccountType = keyof typeof ACCOUNT_TYPE_CONFIGS;
+
+const getAccountTypeConfig = (accountType: PamAccountType) => {
+ const config = ACCOUNT_TYPE_CONFIGS[accountType as TSupportedAccountType];
+ if (!config) {
+ throw new Error(`Account type '${accountType}' is not supported in this phase`);
+ }
+ return config;
+};
+
+export const validateConnectionDetails = (accountType: PamAccountType, data: unknown): Record<string, unknown> => {
+ return getAccountTypeConfig(accountType).connectionDetails.parse(data) as Record<string, unknown>;
+};
+
+export const validateCredentials = (accountType: PamAccountType, data: unknown): Record<string, unknown> => {
+ return getAccountTypeConfig(accountType).credentials.parse(data) as Record<string, unknown>;
+};
+
+export { ACCOUNT_TYPE_CONFIGS };
diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.ts
new file mode 100644
index 0000000000..6c0f210b0b
--- /dev/null
+++ b/backend/src/ee/services/pam-account/pam-account-service.ts
@@ -0,0 +1,447 @@
+import { ForbiddenError } from "@casl/ability";
+
+import { ActionProjectType, RESOURCE_SCOPE, ResourceType } from "@app/db/schemas";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ResourcePermissionPamResourceActions,
+ ResourcePermissionSub
+} from "@app/ee/services/permission/resource-permission";
+import { DatabaseErrorCode } from "@app/lib/error-codes";
+import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
+import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { KmsDataKey } from "@app/services/kms/kms-types";
+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
+
+import { TPamAccountTemplateDALFactory } from "../pam-account-template/pam-account-template-dal";
+import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";
+import { TPamAccountDALFactory } from "./pam-account-dal";
+import { validateConnectionDetails, validateCredentials } from "./pam-account-schemas";
+import {
+ TCreatePamAccountDTO,
+ TDeletePamAccountDTO,
+ TGetPamAccountDTO,
+ TListAccessibleAccountsDTO,
+ TListPamAccountsDTO,
+ TUpdatePamAccountDTO
+} from "./pam-account-types";
+
+type TActorContext = {
+ actorId: string;
+ actor: ActorType;
+ actorOrgId: string;
+ actorAuthMethod: ActorAuthMethod;
+};
+
+type TPamAccountServiceFactoryDep = {
+ pamAccountDAL: TPamAccountDALFactory;
+ pamFolderDAL: Pick<TPamFolderDALFactory, "findById">;
+ pamAccountTemplateDAL: Pick<TPamAccountTemplateDALFactory, "findById">;
+ membershipDAL: Pick<TMembershipDALFactory, "find" | "delete" | "findResourceMembershipsForActor">;
+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "delete">;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+};
+
+export type TPamAccountServiceFactory = ReturnType<typeof pamAccountServiceFactory>;
+
+export const pamAccountServiceFactory = ({
+ pamAccountDAL,
+ pamFolderDAL,
+ pamAccountTemplateDAL,
+ membershipDAL,
+ membershipRoleDAL,
+ permissionService,
+ kmsService
+}: TPamAccountServiceFactoryDep) => {
+ const getProjectCipher = async (projectId: string) =>
+ kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });
+
+ const encrypt = async (projectId: string, data: Record<string, unknown>) => {
+ const { encryptor } = await getProjectCipher(projectId);
+ return encryptor({ plainText: Buffer.from(JSON.stringify(data)) }).cipherTextBlob;
+ };
+
+ const decrypt = async (projectId: string, blob: Buffer): Promise<Record<string, unknown>> => {
+ const { decryptor } = await getProjectCipher(projectId);
+ return JSON.parse(decryptor({ cipherTextBlob: blob }).toString("utf-8")) as Record<string, unknown>;
+ };
+
+ const verifyProductMembership = async (projectId: string, ctx: TActorContext) => {
+ const { hasRole } = await permissionService.getProjectPermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId,
+ actionProjectType: ActionProjectType.PAM
+ });
+ return { hasRole };
+ };
+
+ const checkFolderPermission = async (folderId: string, projectId: string, ctx: TActorContext) => {
+ return permissionService.getResourcePermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ resourceType: ResourceType.PamFolder,
+ resourceId: folderId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId
+ });
+ };
+
+ const list = async ({ projectId, folderId, templateId, search, ...ctx }: TListPamAccountsDTO & TActorContext) => {
+ await verifyProductMembership(projectId, ctx);
+
+ const [folderMemberships, accountMemberships] = await Promise.all([
+ membershipDAL.findResourceMembershipsForActor({
+ projectId,
+ resourceType: ResourceType.PamFolder,
+ actorType: ctx.actor,
+ actorId: ctx.actorId
+ }),
+ membershipDAL.findResourceMembershipsForActor({
+ projectId,
+ resourceType: ResourceType.PamAccount,
+ actorType: ctx.actor,
+ actorId: ctx.actorId
+ })
+ ]);
+
+ const folderIds = folderMemberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id));
+ const accountIds = accountMemberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id));
+
+ if (folderIds.length === 0 && accountIds.length === 0) return [];
+
+ const accounts = await pamAccountDAL.findAccessible(projectId, folderIds, accountIds, {
+ folderId,
+ templateId,
+ search
+ });
+
+ return accounts.map((a) => ({
+ id: a.id,
+ name: a.name,
+ description: a.description,
+ folderId: a.folderId,
+ folderName: a.folderName,
+ templateId: a.templateId,
+ templateName: a.templateName,
+ accountType: a.accountType,
+ projectId: a.projectId,
+ gatewayId: a.gatewayId,
+ gatewayPoolId: a.gatewayPoolId,
+ recordingConnectionId: a.recordingConnectionId,
+ createdAt: a.createdAt,
+ updatedAt: a.updatedAt
+ }));
+ };
+
+ const checkAccountAccess = async (
+ accountId: string,
+ folderId: string | null | undefined,
+ projectId: string,
+ action: ResourcePermissionPamResourceActions,
+ ctx: TActorContext
+ ) => {
+ if (folderId) {
+ try {
+ const { permission } = await checkFolderPermission(folderId, projectId, ctx);
+ ForbiddenError.from(permission).throwUnlessCan(action, ResourcePermissionSub.PamResource);
+ return;
+ } catch {
+ // folder permission failed, fall through to account-level check
+ }
+ }
+
+ const { permission } = await permissionService.getResourcePermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ resourceType: ResourceType.PamAccount,
+ resourceId: accountId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId
+ });
+ ForbiddenError.from(permission).throwUnlessCan(action, ResourcePermissionSub.PamResource);
+ };
+
+ const getById = async ({ accountId, projectId, ...ctx }: TGetPamAccountDTO & TActorContext) => {
+ const account = await pamAccountDAL.findByIdWithDetails(accountId);
+ if (!account || account.projectId !== projectId) {
+ throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
+ }
+
+ await checkAccountAccess(
+ accountId,
+ account.folderId,
+ projectId,
+ ResourcePermissionPamResourceActions.ReadAccounts,
+ ctx
+ );
+
+ const connectionDetails = await decrypt(projectId, account.encryptedConnectionDetails);
+
+ return {
+ id: account.id,
+ name: account.name,
+ description: account.description,
+ folderId: account.folderId,
+ folderName: account.folderName,
+ templateId: account.templateId,
+ templateName: account.templateName,
+ templateAccessPolicy: account.templateAccessPolicy,
+ templateSettings: account.templateSettings,
+ accountType: account.accountType,
+ projectId: account.projectId,
+ gatewayId: account.gatewayId,
+ gatewayPoolId: account.gatewayPoolId,
+ recordingConnectionId: account.recordingConnectionId,
+ connectionDetails,
+ createdAt: account.createdAt,
+ updatedAt: account.updatedAt
+ };
+ };
+
+ const create = async ({
+ projectId,
+ accountType,
+ name,
+ description,
+ folderId,
+ templateId,
+ connectionDetails,
+ credentials,
+ gatewayId,
+ gatewayPoolId,
+ recordingConnectionId,
+ ...ctx
+ }: TCreatePamAccountDTO & TActorContext) => {
+ const { permission } = await checkFolderPermission(folderId, projectId, ctx);
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionPamResourceActions.CreateAccounts,
+ ResourcePermissionSub.PamResource
+ );
+
+ const folder = await pamFolderDAL.findById(folderId);
+ if (!folder || folder.projectId !== projectId) {
+ throw new NotFoundError({ message: `Folder with ID '${folderId}' not found` });
+ }
+
+ const template = await pamAccountTemplateDAL.findById(templateId);
+ if (!template || template.projectId !== projectId) {
+ throw new NotFoundError({ message: `Template with ID '${templateId}' not found` });
+ }
+ if (template.type !== accountType) {
+ throw new BadRequestError({
+ message: `Template type '${template.type}' does not match account type '${accountType}'`
+ });
+ }
+
+ const validatedConnectionDetails = validateConnectionDetails(accountType, connectionDetails);
+ const validatedCredentials = validateCredentials(accountType, credentials);
+
+ const encryptedConnectionDetails = await encrypt(projectId, validatedConnectionDetails);
+ const encryptedCredentials = await encrypt(projectId, validatedCredentials);
+
+ try {
+ const account = await pamAccountDAL.create({
+ projectId,
+ name,
+ description,
+ folderId,
+ templateId,
+ encryptedConnectionDetails,
+ encryptedCredentials,
+ gatewayId,
+ gatewayPoolId,
+ recordingConnectionId
+ });
+
+ return {
+ id: account.id,
+ name: account.name,
+ description: account.description,
+ folderId: account.folderId ?? null,
+ templateId: account.templateId,
+ projectId: account.projectId,
+ gatewayId: account.gatewayId,
+ gatewayPoolId: account.gatewayPoolId,
+ recordingConnectionId: account.recordingConnectionId,
+ createdAt: account.createdAt,
+ updatedAt: account.updatedAt,
+ accountType,
+ folderName: folder.name,
+ templateName: template.name,
+ connectionDetails: validatedConnectionDetails
+ };
+ } catch (err) {
+ if (
+ err instanceof DatabaseError &&
+ (err as DatabaseError & { code?: string }).code === DatabaseErrorCode.UniqueViolation
+ ) {
+ throw new BadRequestError({ message: `An account named "${name}" already exists in this folder` });
+ }
+ throw err;
+ }
+ };
+
+ const update = async ({
+ accountId,
+ projectId,
+ accountType,
+ name,
+ description,
+ folderId,
+ templateId,
+ connectionDetails,
+ credentials,
+ gatewayId,
+ gatewayPoolId,
+ recordingConnectionId,
+ ...ctx
+ }: TUpdatePamAccountDTO & TActorContext) => {
+ const existing = await pamAccountDAL.findByIdWithDetails(accountId);
+ if (!existing || existing.projectId !== projectId) {
+ throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
+ }
+
+ await checkAccountAccess(
+ accountId,
+ existing.folderId,
+ projectId,
+ ResourcePermissionPamResourceActions.EditAccounts,
+ ctx
+ );
+
+ if (folderId) {
+ const folder = await pamFolderDAL.findById(folderId);
+ if (!folder || folder.projectId !== projectId) {
+ throw new NotFoundError({ message: `Folder with ID '${folderId}' not found` });
+ }
+ }
+
+ if (templateId) {
+ const template = await pamAccountTemplateDAL.findById(templateId);
+ if (!template || template.projectId !== projectId) {
+ throw new NotFoundError({ message: `Template with ID '${templateId}' not found` });
+ }
+ }
+
+ const updateData: Record<string, unknown> = {};
+ if (name !== undefined) updateData.name = name;
+ if (description !== undefined) updateData.description = description;
+ if (folderId !== undefined) updateData.folderId = folderId;
+ if (templateId !== undefined) updateData.templateId = templateId;
+ if (gatewayId !== undefined) updateData.gatewayId = gatewayId;
+ if (gatewayPoolId !== undefined) updateData.gatewayPoolId = gatewayPoolId;
+ if (recordingConnectionId !== undefined) updateData.recordingConnectionId = recordingConnectionId;
+
+ if (connectionDetails) {
+ const validated = validateConnectionDetails(accountType, connectionDetails);
+ updateData.encryptedConnectionDetails = await encrypt(projectId, validated);
+ }
+
+ if (credentials) {
+ const validated = validateCredentials(accountType, credentials);
+ updateData.encryptedCredentials = await encrypt(projectId, validated);
+ }
+
+ try {
+ return await pamAccountDAL.updateById(accountId, updateData);
+ } catch (err) {
+ if (
+ err instanceof DatabaseError &&
+ (err as DatabaseError & { code?: string }).code === DatabaseErrorCode.UniqueViolation
+ ) {
+ throw new BadRequestError({ message: `An account named "${name}" already exists in this folder` });
+ }
+ throw err;
+ }
+ };
+
+ const deleteAccount = async ({ accountId, projectId, ...ctx }: TDeletePamAccountDTO & TActorContext) => {
+ const existing = await pamAccountDAL.findByIdWithDetails(accountId);
+ if (!existing || existing.projectId !== projectId) {
+ throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
+ }
+
+ await checkAccountAccess(
+ accountId,
+ existing.folderId,
+ projectId,
+ ResourcePermissionPamResourceActions.DeleteAccounts,
+ ctx
+ );
+
+ return pamAccountDAL.transaction(async (tx) => {
+ const memberships = await membershipDAL.find(
+ {
+ scope: RESOURCE_SCOPE,
+ scopeResourceType: ResourceType.PamAccount,
+ scopeResourceId: accountId
+ },
+ { tx }
+ );
+
+ if (memberships.length > 0) {
+ const ids = memberships.map((m) => m.id);
+ await membershipRoleDAL.delete({ $in: { membershipId: ids } }, tx);
+ await membershipDAL.delete({ $in: { id: ids } }, tx);
+ }
+
+ return pamAccountDAL.deleteById(accountId, tx);
+ });
+ };
+
+ const listAccessible = async ({ projectId, ...ctx }: TListAccessibleAccountsDTO & TActorContext) => {
+ await permissionService.getProjectPermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId,
+ actionProjectType: ActionProjectType.PAM
+ });
+
+ const [folderMemberships, accountMemberships] = await Promise.all([
+ membershipDAL.findResourceMembershipsForActor({
+ projectId,
+ resourceType: ResourceType.PamFolder,
+ actorType: ctx.actor,
+ actorId: ctx.actorId
+ }),
+ membershipDAL.findResourceMembershipsForActor({
+ projectId,
+ resourceType: ResourceType.PamAccount,
+ actorType: ctx.actor,
+ actorId: ctx.actorId
+ })
+ ]);
+
+ const folderIds = folderMemberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id));
+ const accountIds = accountMemberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id));
+
+ if (folderIds.length === 0 && accountIds.length === 0) return [];
+
+ const accounts = await pamAccountDAL.findAccessible(projectId, folderIds, accountIds);
+
+ return accounts.map((a) => ({
+ id: a.id,
+ name: a.name,
+ description: a.description,
+ folderId: a.folderId,
+ folderName: a.folderName,
+ templateId: a.templateId,
+ templateName: a.templateName,
+ accountType: a.accountType,
+ projectId: a.projectId,
+ createdAt: a.createdAt,
+ updatedAt: a.updatedAt
+ }));
+ };
+
+ return { list, listAccessible, getById, create, update, deleteAccount };
+};
diff --git a/backend/src/ee/services/pam-account/pam-account-types.ts b/backend/src/ee/services/pam-account/pam-account-types.ts
new file mode 100644
index 0000000000..3518f15b86
--- /dev/null
+++ b/backend/src/ee/services/pam-account/pam-account-types.ts
@@ -0,0 +1,51 @@
+import { PamAccountType } from "../pam/pam-enums";
+
+export type TCreatePamAccountDTO = {
+ projectId: string;
+ accountType: PamAccountType;
+ name: string;
+ description?: string;
+ folderId: string;
+ templateId: string;
+ connectionDetails: Record<string, unknown>;
+ credentials: Record<string, unknown>;
+ gatewayId?: string;
+ gatewayPoolId?: string;
+ recordingConnectionId?: string;
+};
+
+export type TUpdatePamAccountDTO = {
+ accountId: string;
+ projectId: string;
+ accountType: PamAccountType;
+ name?: string;
+ description?: string | null;
+ folderId?: string;
+ templateId?: string;
+ connectionDetails?: Record<string, unknown>;
+ credentials?: Record<string, unknown>;
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+ recordingConnectionId?: string | null;
+};
+
+export type TDeletePamAccountDTO = {
+ accountId: string;
+ projectId: string;
+};
+
+export type TGetPamAccountDTO = {
+ accountId: string;
+ projectId: string;
+};
+
+export type TListPamAccountsDTO = {
+ projectId: string;
+ folderId?: string;
+ templateId?: string;
+ search?: string;
+};
+
+export type TListAccessibleAccountsDTO = {
+ projectId: string;
+};
diff --git a/backend/src/ee/services/pam-folder/pam-folder-dal.ts b/backend/src/ee/services/pam-folder/pam-folder-dal.ts
new file mode 100644
index 0000000000..5e80b8ce16
--- /dev/null
+++ b/backend/src/ee/services/pam-folder/pam-folder-dal.ts
@@ -0,0 +1,50 @@
+import { TDbClient } from "@app/db";
+import { TableName, TPamFolders } from "@app/db/schemas";
+import { sanitizeSqlLikeString } from "@app/lib/fn";
+import { ormify } from "@app/lib/knex";
+
+export type TPamFolderWithCount = TPamFolders & { accountCount: number };
+
+export type TPamFolderDALFactory = ReturnType<typeof pamFolderDALFactory>;
+
+export const pamFolderDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.PamFolder);
+
+ const findByProjectIdFiltered = async (
+ projectId: string,
+ folderIds: string[],
+ filters?: { search?: string; accountIds?: string[] }
+ ): Promise<TPamFolderWithCount[]> => {
+ const qb = db
+ .replicaNode()(TableName.PamFolder)
+ .leftJoin(TableName.PamAccount, `${TableName.PamAccount}.folderId`, `${TableName.PamFolder}.id`)
+ .where(`${TableName.PamFolder}.projectId`, projectId)
+ .where((builder) => {
+ if (folderIds.length > 0) {
+ void builder.whereIn(`${TableName.PamFolder}.id`, folderIds);
+ }
+ if (filters?.accountIds && filters.accountIds.length > 0) {
+ void builder.orWhereIn(`${TableName.PamAccount}.id`, filters.accountIds);
+ }
+ });
+
+ if (filters?.search) {
+ void qb.whereILike(`${TableName.PamFolder}.name`, `%${sanitizeSqlLikeString(filters.search)}%`);
+ }
+
+ return qb
+ .groupBy(`${TableName.PamFolder}.id`)
+ .select(`${TableName.PamFolder}.*`, db.raw(`COUNT(${TableName.PamAccount}.id)::int as "accountCount"`))
+ .orderBy(`${TableName.PamFolder}.name`, "asc") as unknown as Promise<TPamFolderWithCount[]>;
+ };
+
+ const countAccountsByFolderId = async (folderId: string) => {
+ const [result] = (await db
+ .replicaNode()(TableName.PamAccount)
+ .where({ folderId })
+ .count("id as count")) as unknown as [{ count: string }];
+ return Number(result.count);
+ };
+
+ return { ...orm, findByProjectIdFiltered, countAccountsByFolderId };
+};
diff --git a/backend/src/ee/services/pam-folder/pam-folder-service.ts b/backend/src/ee/services/pam-folder/pam-folder-service.ts
new file mode 100644
index 0000000000..43390b7523
--- /dev/null
+++ b/backend/src/ee/services/pam-folder/pam-folder-service.ts
@@ -0,0 +1,220 @@
+import { ForbiddenError } from "@casl/ability";
+
+import { ActionProjectType, RESOURCE_SCOPE, ResourceType } from "@app/db/schemas";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ResourcePermissionPamResourceActions,
+ ResourcePermissionSub
+} from "@app/ee/services/permission/resource-permission";
+import { DatabaseErrorCode } from "@app/lib/error-codes";
+import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
+
+import { PamProductRole, PamResourceRole } from "../pam/pam-enums";
+import { TPamFolderDALFactory } from "./pam-folder-dal";
+import {
+ TCreatePamFolderDTO,
+ TDeletePamFolderDTO,
+ TGetPamFolderDTO,
+ TListPamFoldersDTO,
+ TUpdatePamFolderDTO
+} from "./pam-folder-types";
+
+type TActorContext = {
+ actorId: string;
+ actor: ActorType;
+ actorOrgId: string;
+ actorAuthMethod: ActorAuthMethod;
+};
+
+type TPamFolderServiceFactoryDep = {
+ pamFolderDAL: TPamFolderDALFactory;
+ membershipDAL: Pick<
+ TMembershipDALFactory,
+ "create" | "find" | "delete" | "findResourceMembershipsForActor" | "transaction"
+ >;
+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create" | "delete">;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
+};
+
+export type TPamFolderServiceFactory = ReturnType<typeof pamFolderServiceFactory>;
+
+export const pamFolderServiceFactory = ({
+ pamFolderDAL,
+ membershipDAL,
+ membershipRoleDAL,
+ permissionService
+}: TPamFolderServiceFactoryDep) => {
+ const verifyProductMembership = async (projectId: string, ctx: TActorContext) => {
+ const { hasRole } = await permissionService.getProjectPermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId,
+ actionProjectType: ActionProjectType.PAM
+ });
+ return { hasRole };
+ };
+
+ const verifyProductAdmin = async (projectId: string, ctx: TActorContext) => {
+ const { hasRole } = await verifyProductMembership(projectId, ctx);
+ if (!hasRole(PamProductRole.Admin)) {
+ throw new ForbiddenRequestError({ message: "Only PAM product admins can perform this action" });
+ }
+ };
+
+ const checkFolderPermission = async (
+ folderId: string,
+ projectId: string,
+ action: ResourcePermissionPamResourceActions,
+ ctx: TActorContext
+ ) => {
+ const { permission } = await permissionService.getResourcePermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ resourceType: ResourceType.PamFolder,
+ resourceId: folderId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId
+ });
+ ForbiddenError.from(permission).throwUnlessCan(action, ResourcePermissionSub.PamResource);
+ };
+
+ const list = async ({ projectId, search, ...ctx }: TListPamFoldersDTO & TActorContext) => {
+ await verifyProductMembership(projectId, ctx);
+
+ const [folderMemberships, accountMemberships] = await Promise.all([
+ membershipDAL.findResourceMembershipsForActor({
+ projectId,
+ resourceType: ResourceType.PamFolder,
+ actorType: ctx.actor,
+ actorId: ctx.actorId
+ }),
+ membershipDAL.findResourceMembershipsForActor({
+ projectId,
+ resourceType: ResourceType.PamAccount,
+ actorType: ctx.actor,
+ actorId: ctx.actorId
+ })
+ ]);
+
+ const folderIds = folderMemberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id));
+ const accountIds = accountMemberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id));
+
+ if (folderIds.length === 0 && accountIds.length === 0) return [];
+
+ return pamFolderDAL.findByProjectIdFiltered(projectId, folderIds, { search, accountIds });
+ };
+
+ const getById = async ({ folderId, projectId, ...ctx }: TGetPamFolderDTO & TActorContext) => {
+ await checkFolderPermission(folderId, projectId, ResourcePermissionPamResourceActions.ReadFolder, ctx);
+
+ const folder = await pamFolderDAL.findById(folderId);
+ if (!folder || folder.projectId !== projectId) {
+ throw new NotFoundError({ message: `Folder with ID '${folderId}' not found` });
+ }
+
+ const accountCount = await pamFolderDAL.countAccountsByFolderId(folderId);
+ return { ...folder, accountCount };
+ };
+
+ const create = async ({ projectId, name, description, ...ctx }: TCreatePamFolderDTO & TActorContext) => {
+ await verifyProductAdmin(projectId, ctx);
+
+ try {
+ return await pamFolderDAL.transaction(async (tx) => {
+ const folder = await pamFolderDAL.create({ projectId, name, description }, tx);
+
+ const membership = await membershipDAL.create(
+ {
+ scope: RESOURCE_SCOPE,
+ scopeOrgId: ctx.actorOrgId,
+ scopeProjectId: projectId,
+ scopeResourceType: ResourceType.PamFolder,
+ scopeResourceId: folder.id,
+ ...(ctx.actor === ActorType.USER ? { actorUserId: ctx.actorId } : { actorIdentityId: ctx.actorId }),
+ isActive: true
+ },
+ tx
+ );
+ await membershipRoleDAL.create({ membershipId: membership.id, role: PamResourceRole.Admin }, tx);
+
+ return folder;
+ });
+ } catch (err) {
+ if (
+ err instanceof DatabaseError &&
+ (err as DatabaseError & { code?: string }).code === DatabaseErrorCode.UniqueViolation
+ ) {
+ throw new BadRequestError({ message: `A folder named "${name}" already exists` });
+ }
+ throw err;
+ }
+ };
+
+ const update = async ({ folderId, projectId, name, description, ...ctx }: TUpdatePamFolderDTO & TActorContext) => {
+ await checkFolderPermission(folderId, projectId, ResourcePermissionPamResourceActions.EditFolder, ctx);
+
+ const existing = await pamFolderDAL.findById(folderId);
+ if (!existing || existing.projectId !== projectId) {
+ throw new NotFoundError({ message: `Folder with ID '${folderId}' not found` });
+ }
+
+ const updateData: Record<string, unknown> = {};
+ if (name !== undefined) updateData.name = name;
+ if (description !== undefined) updateData.description = description;
+
+ try {
+ return await pamFolderDAL.updateById(folderId, updateData);
+ } catch (err) {
+ if (
+ err instanceof DatabaseError &&
+ (err as DatabaseError & { code?: string }).code === DatabaseErrorCode.UniqueViolation
+ ) {
+ throw new BadRequestError({ message: `A folder named "${name}" already exists` });
+ }
+ throw err;
+ }
+ };
+
+ const deleteFolder = async ({ folderId, projectId, ...ctx }: TDeletePamFolderDTO & TActorContext) => {
+ await checkFolderPermission(folderId, projectId, ResourcePermissionPamResourceActions.DeleteFolder, ctx);
+
+ const existing = await pamFolderDAL.findById(folderId);
+ if (!existing || existing.projectId !== projectId) {
+ throw new NotFoundError({ message: `Folder with ID '${folderId}' not found` });
+ }
+
+ const accountCount = await pamFolderDAL.countAccountsByFolderId(folderId);
+ if (accountCount > 0) {
+ throw new BadRequestError({
+ message: `Cannot delete folder "${existing.name}" because it contains ${accountCount} account(s)`
+ });
+ }
+
+ return pamFolderDAL.transaction(async (tx) => {
+ const memberships = await membershipDAL.find(
+ {
+ scope: RESOURCE_SCOPE,
+ scopeResourceType: ResourceType.PamFolder,
+ scopeResourceId: folderId
+ },
+ { tx }
+ );
+
+ if (memberships.length > 0) {
+ const ids = memberships.map((m) => m.id);
+ await membershipRoleDAL.delete({ $in: { membershipId: ids } }, tx);
+ await membershipDAL.delete({ $in: { id: ids } }, tx);
+ }
+
+ return pamFolderDAL.deleteById(folderId, tx);
+ });
+ };
+
+ return { list, getById, create, update, deleteFolder };
+};
diff --git a/backend/src/ee/services/pam-folder/pam-folder-types.ts b/backend/src/ee/services/pam-folder/pam-folder-types.ts
new file mode 100644
index 0000000000..a30dde1a78
--- /dev/null
+++ b/backend/src/ee/services/pam-folder/pam-folder-types.ts
@@ -0,0 +1,27 @@
+export type TCreatePamFolderDTO = {
+ projectId: string;
+ name: string;
+ description?: string;
+};
+
+export type TUpdatePamFolderDTO = {
+ folderId: string;
+ projectId: string;
+ name?: string;
+ description?: string | null;
+};
+
+export type TDeletePamFolderDTO = {
+ folderId: string;
+ projectId: string;
+};
+
+export type TGetPamFolderDTO = {
+ folderId: string;
+ projectId: string;
+};
+
+export type TListPamFoldersDTO = {
+ projectId: string;
+ search?: string;
+};
diff --git a/backend/src/ee/services/pam-membership/pam-membership-service.ts b/backend/src/ee/services/pam-membership/pam-membership-service.ts
new file mode 100644
index 0000000000..aff2858a0c
--- /dev/null
+++ b/backend/src/ee/services/pam-membership/pam-membership-service.ts
@@ -0,0 +1,638 @@
+import { ForbiddenError } from "@casl/ability";
+import { Knex } from "knex";
+
+import { AccessScope, ActionProjectType, RESOURCE_SCOPE, ResourceType } from "@app/db/schemas";
+import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ResourcePermissionPamResourceActions,
+ ResourcePermissionSub
+} from "@app/ee/services/permission/resource-permission";
+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
+import { TUserDALFactory } from "@app/services/user/user-dal";
+
+import { PamProductRole, PamResourceRole } from "../pam/pam-enums";
+import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
+import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";
+import {
+ TAddPamAccountMemberDTO,
+ TAddPamFolderMemberDTO,
+ TAddPamProductMemberDTO,
+ TListPamAccountMembersDTO,
+ TListPamFolderMembersDTO,
+ TListPamProductMembersDTO,
+ TRemovePamAccountMemberDTO,
+ TRemovePamFolderMemberDTO,
+ TRemovePamProductMemberDTO,
+ TUpdatePamAccountMemberDTO,
+ TUpdatePamFolderMemberDTO,
+ TUpdatePamProductMemberDTO
+} from "./pam-membership-types";
+
+type TActorContext = {
+ actorId: string;
+ actor: ActorType;
+ actorOrgId: string;
+ actorAuthMethod: ActorAuthMethod;
+};
+
+type TPamMembershipServiceFactoryDep = {
+ membershipDAL: Pick<
+ TMembershipDALFactory,
+ "create" | "find" | "findById" | "delete" | "deleteById" | "findResourceMembershipsForActor" | "transaction"
+ >;
+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create" | "find" | "delete" | "update">;
+ pamFolderDAL: Pick<TPamFolderDALFactory, "findById">;
+ pamAccountDAL: Pick<TPamAccountDALFactory, "findById">;
+ userDAL: Pick<TUserDALFactory, "findById">;
+ groupDAL: Pick<TGroupDALFactory, "findById">;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
+};
+
+export type TPamMembershipServiceFactory = ReturnType<typeof pamMembershipServiceFactory>;
+
+const VALID_PRODUCT_ROLES = Object.values(PamProductRole);
+const VALID_RESOURCE_ROLES = Object.values(PamResourceRole);
+
+const resolveActorColumn = (dto: { userId?: string; groupId?: string }) => {
+ if (dto.userId) return { column: "actorUserId" as const, id: dto.userId, kind: "user" as const };
+ if (dto.groupId) return { column: "actorGroupId" as const, id: dto.groupId, kind: "group" as const };
+ throw new BadRequestError({ message: "Either userId or groupId is required" });
+};
+
+const resourceScope = (projectId: string, resourceType: ResourceType, resourceId: string) => ({
+ scope: RESOURCE_SCOPE as typeof RESOURCE_SCOPE,
+ scopeProjectId: projectId,
+ scopeResourceType: resourceType,
+ scopeResourceId: resourceId
+});
+
+export const pamMembershipServiceFactory = ({
+ membershipDAL,
+ membershipRoleDAL,
+ pamFolderDAL,
+ pamAccountDAL,
+ userDAL,
+ groupDAL,
+ permissionService
+}: TPamMembershipServiceFactoryDep) => {
+ // Shared helpers
+
+ const checkProductAdmin = async (projectId: string, ctx: TActorContext) => {
+ const { hasRole } = await permissionService.getProjectPermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId,
+ actionProjectType: ActionProjectType.PAM
+ });
+ if (!hasRole(PamProductRole.Admin)) {
+ throw new ForbiddenRequestError({ message: "Only PAM product admins can perform this action" });
+ }
+ };
+
+ const checkManageMembers = async (
+ projectId: string,
+ resource: { type: ResourceType; id: string; parentFolderId?: string | null },
+ ctx: TActorContext
+ ) => {
+ if (resource.parentFolderId) {
+ try {
+ const { permission } = await permissionService.getResourcePermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ resourceType: ResourceType.PamFolder,
+ resourceId: resource.parentFolderId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionPamResourceActions.ManageMembers,
+ ResourcePermissionSub.PamResource
+ );
+ return;
+ } catch {
+ if (resource.type === ResourceType.PamFolder)
+ throw new ForbiddenRequestError({ message: "You do not have permission to manage members on this folder" });
+ }
+ }
+
+ const { permission } = await permissionService.getResourcePermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ resourceType: resource.type,
+ resourceId: resource.id,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionPamResourceActions.ManageMembers,
+ ResourcePermissionSub.PamResource
+ );
+ };
+
+ const checkAccountManagePermission = async (projectId: string, accountId: string, ctx: TActorContext) => {
+ const account = await pamAccountDAL.findById(accountId);
+ if (!account || account.projectId !== projectId) {
+ throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
+ }
+ await checkManageMembers(
+ projectId,
+ { type: ResourceType.PamAccount, id: accountId, parentFolderId: account.folderId },
+ ctx
+ );
+ return account;
+ };
+
+ const validateActorExists = async (dto: { userId?: string; groupId?: string }, orgId: string) => {
+ const { column, id, kind } = resolveActorColumn(dto);
+
+ if (kind === "user") {
+ const user = await userDAL.findById(id);
+ if (!user) throw new NotFoundError({ message: `User with ID '${id}' not found` });
+
+ const orgMemberships = await membershipDAL.find({
+ scope: AccessScope.Organization,
+ scopeOrgId: orgId,
+ actorUserId: id,
+ isActive: true
+ });
+ if (orgMemberships.length === 0) {
+ throw new BadRequestError({ message: "User must be an active member of this organization" });
+ }
+ } else {
+ const group = await groupDAL.findById(id);
+ if (!group) throw new NotFoundError({ message: `Group with ID '${id}' not found` });
+ if (group.orgId !== orgId) throw new BadRequestError({ message: "Group does not belong to this organization" });
+ }
+
+ return { column, id, kind };
+ };
+
+ const validateProductMember = async (projectId: string, dto: { userId?: string; groupId?: string }) => {
+ const { column, id } = resolveActorColumn(dto);
+ const memberships = await membershipDAL.find({
+ scope: AccessScope.Project,
+ scopeProjectId: projectId,
+ [column]: id
+ });
+ if (memberships.length === 0) {
+ throw new BadRequestError({ message: "Must be a PAM product member first" });
+ }
+ };
+
+ const resolveMemberships = async (
+ memberships: Awaited<ReturnType<typeof membershipDAL.find>>,
+ defaultRole: string
+ ) => {
+ return Promise.all(
+ memberships.map(async (m) => {
+ const roles = await membershipRoleDAL.find({ membershipId: m.id });
+ return {
+ membershipId: m.id,
+ userId: m.actorUserId,
+ identityId: m.actorIdentityId,
+ groupId: m.actorGroupId,
+ role: roles[0]?.role ?? defaultRole,
+ isActive: m.isActive,
+ createdAt: m.createdAt
+ };
+ })
+ );
+ };
+
+ const upsertRole = async (membershipId: string, role: string, tx: Knex) => {
+ const existing = await membershipRoleDAL.find({ membershipId }, { tx });
+ if (existing.length > 0) {
+ await membershipRoleDAL.update({ membershipId }, { role }, tx);
+ } else {
+ await membershipRoleDAL.create({ membershipId, role }, tx);
+ }
+ };
+
+ // Product members
+
+ const listProductMembers = async ({ projectId, ...ctx }: TListPamProductMembersDTO & TActorContext) => {
+ await permissionService.getProjectPermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId,
+ actionProjectType: ActionProjectType.PAM
+ });
+
+ const memberships = await membershipDAL.find({ scope: AccessScope.Project, scopeProjectId: projectId });
+ return resolveMemberships(memberships, PamProductRole.Member);
+ };
+
+ const addProductMember = async ({ projectId, role, ...dto }: TAddPamProductMemberDTO & TActorContext) => {
+ await checkProductAdmin(projectId, dto);
+
+ if (!VALID_PRODUCT_ROLES.includes(role)) {
+ throw new BadRequestError({
+ message: `Invalid product role '${role}'. Expected: ${VALID_PRODUCT_ROLES.join(", ")}`
+ });
+ }
+
+ const { column, id, kind } = await validateActorExists(dto, dto.actorOrgId);
+
+ return membershipDAL.transaction(async (tx) => {
+ const existing = await membershipDAL.find(
+ { scope: AccessScope.Project, scopeProjectId: projectId, [column]: id },
+ { tx }
+ );
+ if (existing.length > 0) {
+ throw new BadRequestError({
+ message: `${kind === "user" ? "User" : "Group"} is already a member of this PAM product`
+ });
+ }
+
+ const membership = await membershipDAL.create(
+ {
+ scope: AccessScope.Project,
+ scopeOrgId: dto.actorOrgId,
+ scopeProjectId: projectId,
+ [column]: id,
+ isActive: true
+ },
+ tx
+ );
+
+ const membershipRole = await membershipRoleDAL.create({ membershipId: membership.id, role }, tx);
+
+ return {
+ membershipId: membership.id,
+ userId: kind === "user" ? id : undefined,
+ groupId: kind === "group" ? id : undefined,
+ role: membershipRole.role,
+ createdAt: membership.createdAt
+ };
+ });
+ };
+
+ const assertNotLastAdmin = async (projectId: string, membershipId: string, tx?: Knex) => {
+ const allProductMemberships = await membershipDAL.find(
+ { scope: AccessScope.Project, scopeProjectId: projectId },
+ { tx }
+ );
+ const otherMemberships = allProductMemberships.filter((m) => m.id !== membershipId);
+
+ const otherRoles = await Promise.all(
+ otherMemberships.map((m) => membershipRoleDAL.find({ membershipId: m.id }, { tx }))
+ );
+ const hasOtherAdmin = otherRoles.some((roles) => roles.some((r) => r.role === PamProductRole.Admin));
+ if (!hasOtherAdmin) {
+ throw new BadRequestError({ message: "Cannot remove or demote the last product admin" });
+ }
+ };
+
+ const updateProductMemberRole = async ({ projectId, role, ...dto }: TUpdatePamProductMemberDTO & TActorContext) => {
+ await checkProductAdmin(projectId, dto);
+
+ if (!VALID_PRODUCT_ROLES.includes(role)) {
+ throw new BadRequestError({
+ message: `Invalid product role '${role}'. Expected: ${VALID_PRODUCT_ROLES.join(", ")}`
+ });
+ }
+
+ const { column, id, kind } = resolveActorColumn(dto);
+
+ return membershipDAL.transaction(async (tx) => {
+ const [membership] = await membershipDAL.find(
+ { scope: AccessScope.Project, scopeProjectId: projectId, [column]: id },
+ { tx }
+ );
+ if (!membership) {
+ throw new NotFoundError({
+ message: `${kind === "user" ? "User" : "Group"} is not a member of this PAM product`
+ });
+ }
+
+ const existingRoles = await membershipRoleDAL.find({ membershipId: membership.id }, { tx });
+ const wasAdmin = existingRoles.some((r) => r.role === PamProductRole.Admin);
+ if (wasAdmin && role !== PamProductRole.Admin) {
+ await assertNotLastAdmin(projectId, membership.id, tx);
+ }
+
+ await upsertRole(membership.id, role, tx);
+
+ return {
+ membershipId: membership.id,
+ userId: kind === "user" ? id : undefined,
+ groupId: kind === "group" ? id : undefined,
+ role
+ };
+ });
+ };
+
+ const removeProductMember = async ({ projectId, ...dto }: TRemovePamProductMemberDTO & TActorContext) => {
+ await checkProductAdmin(projectId, dto);
+
+ const { column, id, kind } = resolveActorColumn(dto);
+
+ return membershipDAL.transaction(async (tx) => {
+ const [membership] = await membershipDAL.find(
+ { scope: AccessScope.Project, scopeProjectId: projectId, [column]: id },
+ { tx }
+ );
+ if (!membership) {
+ throw new NotFoundError({
+ message: `${kind === "user" ? "User" : "Group"} is not a member of this PAM product`
+ });
+ }
+
+ const roles = await membershipRoleDAL.find({ membershipId: membership.id }, { tx });
+ if (roles.some((r) => r.role === PamProductRole.Admin)) {
+ await assertNotLastAdmin(projectId, membership.id, tx);
+ }
+
+ await membershipRoleDAL.delete({ membershipId: membership.id }, tx);
+
+ const resourceMemberships = await membershipDAL.find(
+ { scope: RESOURCE_SCOPE, scopeProjectId: projectId, [column]: id },
+ { tx }
+ );
+ await Promise.all(
+ resourceMemberships.map(async (rm) => {
+ await membershipRoleDAL.delete({ membershipId: rm.id }, tx);
+ await membershipDAL.deleteById(rm.id, tx);
+ })
+ );
+
+ await membershipDAL.deleteById(membership.id, tx);
+
+ return {
+ membershipId: membership.id,
+ userId: kind === "user" ? id : undefined,
+ groupId: kind === "group" ? id : undefined
+ };
+ });
+ };
+
+ // Resource (folder/account) members
+
+ const listResourceMembers = async (projectId: string, resourceType: ResourceType, resourceId: string) => {
+ const memberships = await membershipDAL.find(resourceScope(projectId, resourceType, resourceId));
+ return resolveMemberships(memberships, PamResourceRole.Requester);
+ };
+
+ const addResourceMember = async (
+ projectId: string,
+ resourceType: ResourceType,
+ resourceId: string,
+ resourceKey: string,
+ role: string,
+ dto: { userId?: string; groupId?: string } & TActorContext
+ ) => {
+ if (!VALID_RESOURCE_ROLES.includes(role as PamResourceRole)) {
+ throw new BadRequestError({
+ message: `Invalid resource role '${role}'. Expected: ${VALID_RESOURCE_ROLES.join(", ")}`
+ });
+ }
+
+ const { column, id, kind } = await validateActorExists(dto, dto.actorOrgId);
+ await validateProductMember(projectId, dto);
+
+ return membershipDAL.transaction(async (tx) => {
+ const existing = await membershipDAL.find(
+ { ...resourceScope(projectId, resourceType, resourceId), [column]: id },
+ { tx }
+ );
+ if (existing.length > 0) {
+ throw new BadRequestError({
+ message: `${kind === "user" ? "User" : "Group"} is already a member of this ${resourceKey}`
+ });
+ }
+
+ const membership = await membershipDAL.create(
+ {
+ ...resourceScope(projectId, resourceType, resourceId),
+ scopeOrgId: dto.actorOrgId,
+ [column]: id,
+ isActive: true
+ },
+ tx
+ );
+
+ const membershipRole = await membershipRoleDAL.create({ membershipId: membership.id, role }, tx);
+
+ return {
+ membershipId: membership.id,
+ [resourceKey]: resourceId,
+ userId: kind === "user" ? id : undefined,
+ groupId: kind === "group" ? id : undefined,
+ role: membershipRole.role,
+ createdAt: membership.createdAt
+ };
+ });
+ };
+
+ const updateResourceMemberRole = async (
+ projectId: string,
+ resourceType: ResourceType,
+ resourceId: string,
+ resourceKey: string,
+ role: string,
+ dto: { userId?: string; groupId?: string }
+ ) => {
+ if (!VALID_RESOURCE_ROLES.includes(role as PamResourceRole)) {
+ throw new BadRequestError({
+ message: `Invalid resource role '${role}'. Expected: ${VALID_RESOURCE_ROLES.join(", ")}`
+ });
+ }
+
+ const { column, id, kind } = resolveActorColumn(dto);
+
+ return membershipDAL.transaction(async (tx) => {
+ const [membership] = await membershipDAL.find(
+ { ...resourceScope(projectId, resourceType, resourceId), [column]: id },
+ { tx }
+ );
+ if (!membership) {
+ throw new NotFoundError({
+ message: `${kind === "user" ? "User" : "Group"} is not a member of this ${resourceKey}`
+ });
+ }
+
+ await upsertRole(membership.id, role, tx);
+
+ return {
+ membershipId: membership.id,
+ [resourceKey]: resourceId,
+ userId: kind === "user" ? id : undefined,
+ groupId: kind === "group" ? id : undefined,
+ role
+ };
+ });
+ };
+
+ const removeResourceMember = async (
+ projectId: string,
+ resourceType: ResourceType,
+ resourceId: string,
+ resourceKey: string,
+ dto: { userId?: string; groupId?: string }
+ ) => {
+ const { column, id, kind } = resolveActorColumn(dto);
+
+ const [membership] = await membershipDAL.find({
+ ...resourceScope(projectId, resourceType, resourceId),
+ [column]: id
+ });
+ if (!membership) {
+ throw new NotFoundError({
+ message: `${kind === "user" ? "User" : "Group"} is not a member of this ${resourceKey}`
+ });
+ }
+
+ await membershipDAL.transaction(async (tx) => {
+ await membershipRoleDAL.delete({ membershipId: membership.id }, tx);
+ await membershipDAL.deleteById(membership.id, tx);
+ });
+
+ return {
+ membershipId: membership.id,
+ [resourceKey]: resourceId,
+ userId: kind === "user" ? id : undefined,
+ groupId: kind === "group" ? id : undefined
+ };
+ };
+
+ // Folder members
+
+ const listFolderMembers = async ({ projectId, folderId, ...ctx }: TListPamFolderMembersDTO & TActorContext) => {
+ const folder = await pamFolderDAL.findById(folderId);
+ if (!folder || folder.projectId !== projectId) {
+ throw new NotFoundError({ message: `Folder with ID '${folderId}' not found` });
+ }
+
+ await permissionService.getResourcePermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ resourceType: ResourceType.PamFolder,
+ resourceId: folderId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId
+ });
+
+ return listResourceMembers(projectId, ResourceType.PamFolder, folderId);
+ };
+
+ const addFolderMember = async ({ projectId, folderId, role, ...dto }: TAddPamFolderMemberDTO & TActorContext) => {
+ await checkManageMembers(projectId, { type: ResourceType.PamFolder, id: folderId }, dto);
+
+ const folder = await pamFolderDAL.findById(folderId);
+ if (!folder || folder.projectId !== projectId) {
+ throw new NotFoundError({ message: `Folder with ID '${folderId}' not found` });
+ }
+
+ return addResourceMember(projectId, ResourceType.PamFolder, folderId, "folderId", role, dto);
+ };
+
+ const updateFolderMemberRole = async ({
+ projectId,
+ folderId,
+ role,
+ ...dto
+ }: TUpdatePamFolderMemberDTO & TActorContext) => {
+ await checkManageMembers(projectId, { type: ResourceType.PamFolder, id: folderId }, dto);
+ return updateResourceMemberRole(projectId, ResourceType.PamFolder, folderId, "folderId", role, dto);
+ };
+
+ const removeFolderMember = async ({ projectId, folderId, ...dto }: TRemovePamFolderMemberDTO & TActorContext) => {
+ await checkManageMembers(projectId, { type: ResourceType.PamFolder, id: folderId }, dto);
+ return removeResourceMember(projectId, ResourceType.PamFolder, folderId, "folderId", dto);
+ };
+
+ // Account members
+
+ const listAccountMembers = async ({ projectId, accountId, ...ctx }: TListPamAccountMembersDTO & TActorContext) => {
+ const account = await pamAccountDAL.findById(accountId);
+ if (!account || account.projectId !== projectId) {
+ throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
+ }
+
+ let hasAccess = false;
+ if (account.folderId) {
+ try {
+ const { permission } = await permissionService.getResourcePermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ resourceType: ResourceType.PamFolder,
+ resourceId: account.folderId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionPamResourceActions.ReadAccounts,
+ ResourcePermissionSub.PamResource
+ );
+ hasAccess = true;
+ } catch {
+ // fall through to account-level check
+ }
+ }
+
+ if (!hasAccess) {
+ const { permission } = await permissionService.getResourcePermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ resourceType: ResourceType.PamAccount,
+ resourceId: accountId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionPamResourceActions.ReadAccounts,
+ ResourcePermissionSub.PamResource
+ );
+ }
+
+ return listResourceMembers(projectId, ResourceType.PamAccount, accountId);
+ };
+
+ const addAccountMember = async ({ projectId, accountId, role, ...dto }: TAddPamAccountMemberDTO & TActorContext) => {
+ await checkAccountManagePermission(projectId, accountId, dto);
+ return addResourceMember(projectId, ResourceType.PamAccount, accountId, "accountId", role, dto);
+ };
+
+ const updateAccountMemberRole = async ({
+ projectId,
+ accountId,
+ role,
+ ...dto
+ }: TUpdatePamAccountMemberDTO & TActorContext) => {
+ await checkAccountManagePermission(projectId, accountId, dto);
+ return updateResourceMemberRole(projectId, ResourceType.PamAccount, accountId, "accountId", role, dto);
+ };
+
+ const removeAccountMember = async ({ projectId, accountId, ...dto }: TRemovePamAccountMemberDTO & TActorContext) => {
+ await checkAccountManagePermission(projectId, accountId, dto);
+ return removeResourceMember(projectId, ResourceType.PamAccount, accountId, "accountId", dto);
+ };
+
+ return {
+ listProductMembers,
+ addProductMember,
+ updateProductMemberRole,
+ removeProductMember,
+ listFolderMembers,
+ addFolderMember,
+ updateFolderMemberRole,
+ removeFolderMember,
+ listAccountMembers,
+ addAccountMember,
+ updateAccountMemberRole,
+ removeAccountMember
+ };
+};
diff --git a/backend/src/ee/services/pam-membership/pam-membership-types.ts b/backend/src/ee/services/pam-membership/pam-membership-types.ts
new file mode 100644
index 0000000000..695fbdabaf
--- /dev/null
+++ b/backend/src/ee/services/pam-membership/pam-membership-types.ts
@@ -0,0 +1,81 @@
+import { PamProductRole, PamResourceRole } from "../pam/pam-enums";
+
+export type TListPamProductMembersDTO = {
+ projectId: string;
+};
+
+export type TAddPamProductMemberDTO = {
+ projectId: string;
+ userId?: string;
+ groupId?: string;
+ role: PamProductRole;
+};
+
+export type TUpdatePamProductMemberDTO = {
+ projectId: string;
+ userId?: string;
+ groupId?: string;
+ role: PamProductRole;
+};
+
+export type TRemovePamProductMemberDTO = {
+ projectId: string;
+ userId?: string;
+ groupId?: string;
+};
+
+export type TListPamFolderMembersDTO = {
+ projectId: string;
+ folderId: string;
+};
+
+export type TAddPamFolderMemberDTO = {
+ projectId: string;
+ folderId: string;
+ userId?: string;
+ groupId?: string;
+ role: PamResourceRole;
+};
+
+export type TUpdatePamFolderMemberDTO = {
+ projectId: string;
+ folderId: string;
+ userId?: string;
+ groupId?: string;
+ role: PamResourceRole;
+};
+
+export type TRemovePamFolderMemberDTO = {
+ projectId: string;
+ folderId: string;
+ userId?: string;
+ groupId?: string;
+};
+
+export type TListPamAccountMembersDTO = {
+ projectId: string;
+ accountId: string;
+};
+
+export type TAddPamAccountMemberDTO = {
+ projectId: string;
+ accountId: string;
+ userId?: string;
+ groupId?: string;
+ role: PamResourceRole;
+};
+
+export type TUpdatePamAccountMemberDTO = {
+ projectId: string;
+ accountId: string;
+ userId?: string;
+ groupId?: string;
+ role: PamResourceRole;
+};
+
+export type TRemovePamAccountMemberDTO = {
+ projectId: string;
+ accountId: string;
+ userId?: string;
+ groupId?: string;
+};
diff --git a/backend/src/ee/services/pam/pam-enums.ts b/backend/src/ee/services/pam/pam-enums.ts
index e51ea9ed10..734b4d2777 100644
--- a/backend/src/ee/services/pam/pam-enums.ts
+++ b/backend/src/ee/services/pam/pam-enums.ts
@@ -12,7 +12,7 @@ export enum PamAccountType {
ActiveDirectory = "active-directory"
}
-export enum PamFolderRole {
+export enum PamResourceRole {
Admin = "admin",
Requester = "requester",
Auditor = "auditor"
diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.ts
index 9a6f5c13e6..56964da7c9 100644
--- a/backend/src/ee/services/permission/default-roles.ts
+++ b/backend/src/ee/services/permission/default-roles.ts
@@ -49,6 +49,7 @@ import {
ResourcePermissionApplicationEnrollmentActions,
ResourcePermissionApprovalPolicyActions,
ResourcePermissionCertificateActions,
+ ResourcePermissionPamResourceActions,
ResourcePermissionPkiSyncActions,
ResourcePermissionSet,
ResourcePermissionSignerActions,
@@ -1138,3 +1139,52 @@ export const signerAdminPermissions = buildSignerAdminPermissionRules();
export const signerOperatorPermissions = buildSignerOperatorPermissionRules();
export const signerAuditorPermissions = buildSignerAuditorPermissionRules();
export const projectAdminSignerFallbackPermissions = buildProjectAdminSignerFallbackRules();
+
+const buildPamResourceAdminPermissionRules = () => {
+ const { can, rules } = new AbilityBuilder<MongoAbility<ResourcePermissionSet>>(createMongoAbility);
+ can(
+ [
+ ResourcePermissionPamResourceActions.ReadFolder,
+ ResourcePermissionPamResourceActions.EditFolder,
+ ResourcePermissionPamResourceActions.DeleteFolder,
+ ResourcePermissionPamResourceActions.ReadAccounts,
+ ResourcePermissionPamResourceActions.CreateAccounts,
+ ResourcePermissionPamResourceActions.EditAccounts,
+ ResourcePermissionPamResourceActions.DeleteAccounts,
+ ResourcePermissionPamResourceActions.LaunchSessions,
+ ResourcePermissionPamResourceActions.ViewSessions,
+ ResourcePermissionPamResourceActions.TerminateSessions,
+ ResourcePermissionPamResourceActions.ViewCredentials,
+ ResourcePermissionPamResourceActions.RequestAccess,
+ ResourcePermissionPamResourceActions.ApproveRequests,
+ ResourcePermissionPamResourceActions.ManagePolicies,
+ ResourcePermissionPamResourceActions.ManageRotation,
+ ResourcePermissionPamResourceActions.ManageMembers,
+ ResourcePermissionPamResourceActions.ViewAuditLogs
+ ],
+ ResourcePermissionSub.PamResource
+ );
+ return rules;
+};
+
+const buildPamResourceRequesterPermissionRules = () => {
+ const { can, rules } = new AbilityBuilder<MongoAbility<ResourcePermissionSet>>(createMongoAbility);
+ can(
+ [ResourcePermissionPamResourceActions.ReadAccounts, ResourcePermissionPamResourceActions.RequestAccess],
+ ResourcePermissionSub.PamResource
+ );
+ return rules;
+};
+
+const buildPamResourceAuditorPermissionRules = () => {
+ const { can, rules } = new AbilityBuilder<MongoAbility<ResourcePermissionSet>>(createMongoAbility);
+ can(
+ [ResourcePermissionPamResourceActions.ViewSessions, ResourcePermissionPamResourceActions.ViewAuditLogs],
+ ResourcePermissionSub.PamResource
+ );
+ return rules;
+};
+
+export const pamResourceAdminPermissions = buildPamResourceAdminPermissionRules();
+export const pamResourceRequesterPermissions = buildPamResourceRequesterPermissionRules();
+export const pamResourceAuditorPermissions = buildPamResourceAuditorPermissionRules();
diff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.ts
index 1648523aff..e6c9d2c9b1 100644
--- a/backend/src/ee/services/permission/permission-service.ts
+++ b/backend/src/ee/services/permission/permission-service.ts
@@ -20,6 +20,9 @@ import {
applicationAuditorPermissions,
applicationOperatorPermissions,
cryptographicOperatorPermissions,
+ pamResourceAdminPermissions,
+ pamResourceAuditorPermissions,
+ pamResourceRequesterPermissions,
projectAdminApplicationFallbackPermissions,
projectAdminPermissions,
projectAdminSignerFallbackPermissions,
@@ -147,6 +150,19 @@ const resolveResourceRoleRules = (resourceType: ResourceType, role: string) => {
}
}
+ if (resourceType === ResourceType.PamFolder || resourceType === ResourceType.PamAccount) {
+ switch (role) {
+ case "admin":
+ return pamResourceAdminPermissions;
+ case "requester":
+ return pamResourceRequesterPermissions;
+ case "auditor":
+ return pamResourceAuditorPermissions;
+ default:
+ throw new NotFoundError({ name: "PamRoleInvalid", message: `PAM role '${role}' not found` });
+ }
+ }
+
switch (role) {
case ResourceMembershipRole.Admin:
return applicationAdminPermissions;
@@ -175,6 +191,7 @@ const buildResourcePermissionRules = (appUserRoles: TBuildProjectPermissionDTO,
const resolveResourceProjectAdminFallback = (resourceType: ResourceType) => {
if (resourceType === ResourceType.Signer) return projectAdminSignerFallbackPermissions;
+ if (resourceType === ResourceType.PamFolder || resourceType === ResourceType.PamAccount) return [];
return projectAdminApplicationFallbackPermissions;
};
@@ -692,7 +709,10 @@ export const permissionServiceFactory = ({
projectId,
actorAuthMethod,
actorOrgId,
- actionProjectType: ActionProjectType.CertificateManager
+ actionProjectType:
+ resourceType === ResourceType.PamFolder || resourceType === ResourceType.PamAccount
+ ? ActionProjectType.PAM
+ : ActionProjectType.CertificateManager
});
isProjectAdmin = projectPerm.hasRole(ProjectMembershipRole.Admin);
isProjectMember = true;
diff --git a/backend/src/ee/services/permission/resource-permission.ts b/backend/src/ee/services/permission/resource-permission.ts
index b650dd51b4..8d297f2f36 100644
--- a/backend/src/ee/services/permission/resource-permission.ts
+++ b/backend/src/ee/services/permission/resource-permission.ts
@@ -20,7 +20,28 @@ export enum ResourcePermissionSub {
ApprovalRequests = "approval-requests",
ApprovalRequestGrants = "approval-request-grants",
Member = "member",
- Signer = "pki-signer"
+ Signer = "pki-signer",
+ PamResource = "pam-resource" // folders and accounts
+}
+
+export enum ResourcePermissionPamResourceActions {
+ ReadFolder = "read-folder",
+ EditFolder = "edit-folder",
+ DeleteFolder = "delete-folder",
+ ReadAccounts = "read-accounts",
+ CreateAccounts = "create-accounts",
+ EditAccounts = "edit-accounts",
+ DeleteAccounts = "delete-accounts",
+ LaunchSessions = "launch-sessions",
+ ViewSessions = "view-sessions",
+ TerminateSessions = "terminate-sessions",
+ ViewCredentials = "view-credentials",
+ RequestAccess = "request-access",
+ ApproveRequests = "approve-requests",
+ ManagePolicies = "manage-policies",
+ ManageRotation = "manage-rotation",
+ ManageMembers = "manage-members",
+ ViewAuditLogs = "view-audit-logs"
}
export enum ResourcePermissionSignerActions {
@@ -93,6 +114,7 @@ export type ResourcePermissionSet =
| [ProjectPermissionApprovalRequestGrantActions, ResourcePermissionSub.ApprovalRequestGrants]
| [ProjectPermissionMemberActions, ResourcePermissionSub.Member]
| [ResourcePermissionSignerActions, ResourcePermissionSub.Signer]
+ | [ResourcePermissionPamResourceActions, ResourcePermissionSub.PamResource]
| [ProjectPermissionCertificateProfileActions, ProjectPermissionSub.CertificateProfiles];
export type TResourceAbility = MongoAbility<ResourcePermissionSet>;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 5c403dae4c..6bc627eb12 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -95,7 +95,14 @@ import { licenseDALFactory } from "@app/ee/services/license/license-dal";
import { licenseServiceFactory } from "@app/ee/services/license/license-service";
import { oidcConfigDALFactory } from "@app/ee/services/oidc/oidc-config-dal";
import { oidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-service";
+import { pamAccountDALFactory } from "@app/ee/services/pam-account/pam-account-dal";
+import { pamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-service";
+import { pamAccountTemplateDALFactory } from "@app/ee/services/pam-account-template/pam-account-template-dal";
+import { pamAccountTemplateServiceFactory } from "@app/ee/services/pam-account-template/pam-account-template-service";
+import { pamFolderDALFactory } from "@app/ee/services/pam-folder/pam-folder-dal";
+import { pamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";
import { pamProjectResolverFactory } from "@app/ee/services/pam-instance/pam-project-resolver";
+import { pamMembershipServiceFactory } from "@app/ee/services/pam-membership/pam-membership-service";
import { permissionDALFactory } from "@app/ee/services/permission/permission-dal";
import { permissionServiceFactory } from "@app/ee/services/permission/permission-service";
import { pitServiceFactory } from "@app/ee/services/pit/pit-service";
@@ -481,6 +488,7 @@ import { injectAssumePrivilege } from "../plugins/auth/inject-assume-privilege";
import { injectIdentity } from "../plugins/auth/inject-identity";
import { injectPermission } from "../plugins/auth/inject-permission";
import { forwardToGoSidecar } from "../plugins/go-sidecar-forwarding";
+import { injectPamProjectId } from "../plugins/inject-pam-project-id";
import { injectRateLimits } from "../plugins/inject-rate-limits";
import { forwardWritesToPrimary } from "../plugins/primary-forwarding-mode";
import { registerV1Routes } from "./v1";
@@ -1491,6 +1499,42 @@ export const registerRoutes = async (
keyStore
});
+ const pamAccountTemplateDAL = pamAccountTemplateDALFactory(db);
+ const pamFolderDAL = pamFolderDALFactory(db);
+ const pamAccountDAL = pamAccountDALFactory(db);
+
+ const pamAccountTemplateService = pamAccountTemplateServiceFactory({
+ pamAccountTemplateDAL,
+ permissionService
+ });
+
+ const pamFolderService = pamFolderServiceFactory({
+ pamFolderDAL,
+ membershipDAL,
+ membershipRoleDAL,
+ permissionService
+ });
+
+ const pamAccountService = pamAccountServiceFactory({
+ pamAccountDAL,
+ pamFolderDAL,
+ pamAccountTemplateDAL,
+ membershipDAL,
+ membershipRoleDAL,
+ permissionService,
+ kmsService
+ });
+
+ const pamMembershipService = pamMembershipServiceFactory({
+ membershipDAL,
+ membershipRoleDAL,
+ pamFolderDAL,
+ pamAccountDAL,
+ userDAL,
+ groupDAL,
+ permissionService
+ });
+
const certManagerInstanceService = certManagerInstanceServiceFactory({
db,
orgDAL,
@@ -3402,6 +3446,10 @@ export const registerRoutes = async (
pkiApplicationEnrollment: pkiApplicationEnrollmentService,
certManagerProjectResolver,
pamProjectResolver,
+ pamAccountTemplate: pamAccountTemplateService,
+ pamFolder: pamFolderService,
+ pamAccount: pamAccountService,
+ pamMembership: pamMembershipService,
certManagerInstance: certManagerInstanceService,
certManagerExport: certManagerExportService,
certificateAuthorityCrl: certificateAuthorityCrlService,
@@ -3534,6 +3582,7 @@ export const registerRoutes = async (
await server.register(injectIdentity, { shouldForwardWritesToPrimaryInstance });
await server.register(injectAssumePrivilege);
await server.register(injectPermission);
+ await server.register(injectPamProjectId);
await server.register(injectRateLimits);
await server.register(injectAuditLogInfo);
diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.ts
index 377f934c50..6315b79f62 100644
--- a/backend/src/services/telemetry/telemetry-types.ts
+++ b/backend/src/services/telemetry/telemetry-types.ts
@@ -14,7 +14,6 @@ import {
UnknownUserActor,
UserActor
} from "@app/ee/services/audit-log/audit-log-types";
-import { PamParentType } from "@app/ee/services/pam-account/pam-account-enums";
import { SecretRotation } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-enums";
import { SecretScanningDataSource } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";
import { EnforcementLevel, SecretSharingAccessType } from "@app/lib/types";
@@ -97,20 +96,24 @@ export enum PostHogEventTypes {
GatewayCertExchanged = "Gateway Cert Exchanged",
GatewayUpdated = "Gateway Updated",
GatewayDeleted = "Gateway Deleted",
- PamResourceCreated = "PAM Resource Created",
- PamResourceDeleted = "PAM Resource Deleted",
+ PamAccountTemplateCreated = "PAM Account Template Created",
+ PamAccountTemplateDeleted = "PAM Account Template Deleted",
+ PamFolderCreated = "PAM Folder Created",
+ PamFolderDeleted = "PAM Folder Deleted",
PamAccountCreated = "PAM Account Created",
PamAccountDeleted = "PAM Account Deleted",
PamAccountAccessed = "PAM Account Accessed",
- PamAccountRotated = "PAM Account Rotated",
PamSessionStarted = "PAM Session Started",
PamSessionEnded = "PAM Session Ended",
- PamWebAccessStarted = "PAM Web Access Started",
- PamDiscoverySourceCreated = "PAM Discovery Source Created",
- PamDiscoverySourceDeleted = "PAM Discovery Source Deleted",
- PamDiscoveryScanTriggered = "PAM Discovery Scan Triggered",
- PamRotationRuleCreated = "PAM Rotation Rule Created",
- PamRotationRuleDeleted = "PAM Rotation Rule Deleted",
+ PamProductMemberAdded = "PAM Product Member Added",
+ PamProductMemberUpdated = "PAM Product Member Updated",
+ PamProductMemberRemoved = "PAM Product Member Removed",
+ PamFolderMemberAdded = "PAM Folder Member Added",
+ PamFolderMemberUpdated = "PAM Folder Member Updated",
+ PamFolderMemberRemoved = "PAM Folder Member Removed",
+ PamAccountMemberAdded = "PAM Account Member Added",
+ PamAccountMemberUpdated = "PAM Account Member Updated",
+ PamAccountMemberRemoved = "PAM Account Member Removed",
ResourceAuthMethodLogin = "Resource Auth Method Login",
ResourceAuthMethodUpdated = "Resource Auth Method Updated",
@@ -933,88 +936,81 @@ export type TGatewayDeletedEvent = {
};
};
-export type TPamResourceEvent = {
- event: PostHogEventTypes.PamResourceCreated | PostHogEventTypes.PamResourceDeleted;
+export type TPamAccountTemplateEvent = {
+ event: PostHogEventTypes.PamAccountTemplateCreated | PostHogEventTypes.PamAccountTemplateDeleted;
properties: {
- resourceType: string;
- projectId: string;
+ accountType: string;
+ orgId: string;
+ };
+};
+
+export type TPamFolderEvent = {
+ event: PostHogEventTypes.PamFolderCreated | PostHogEventTypes.PamFolderDeleted;
+ properties: {
+ orgId: string;
};
};
export type TPamAccountEvent = {
event: PostHogEventTypes.PamAccountCreated | PostHogEventTypes.PamAccountDeleted;
properties: {
- parentType: PamParentType;
- projectId: string;
+ accountType: string;
+ orgId: string;
};
};
export type TPamAccountAccessedEvent = {
event: PostHogEventTypes.PamAccountAccessed;
properties: {
- resourceType: string;
- projectId: string;
+ accountType: string;
+ orgId: string;
duration: number;
};
};
-export type TPamAccountRotatedEvent = {
- event: PostHogEventTypes.PamAccountRotated;
- properties: {
- parentType: PamParentType;
- projectId: string;
- };
-};
-
export type TPamSessionStartedEvent = {
event: PostHogEventTypes.PamSessionStarted;
properties: {
- projectId: string;
+ orgId: string;
};
};
export type TPamSessionEndedEvent = {
event: PostHogEventTypes.PamSessionEnded;
properties: {
- resourceType: string;
- projectId: string;
+ accountType: string;
+ orgId: string;
durationMs?: number;
};
};
-export type TPamWebAccessStartedEvent = {
- event: PostHogEventTypes.PamWebAccessStarted;
- properties: {
- projectId: string;
- };
-};
-
-export type TPamDiscoveryEvent = {
+export type TPamProductMemberEvent = {
event:
- | PostHogEventTypes.PamDiscoverySourceCreated
- | PostHogEventTypes.PamDiscoverySourceDeleted
- | PostHogEventTypes.PamDiscoveryScanTriggered;
+ | PostHogEventTypes.PamProductMemberAdded
+ | PostHogEventTypes.PamProductMemberUpdated
+ | PostHogEventTypes.PamProductMemberRemoved;
properties: {
- discoveryType: string;
- projectId: string;
+ orgId: string;
};
};
-export type TPamRotationRuleCreatedEvent = {
- event: PostHogEventTypes.PamRotationRuleCreated;
+export type TPamFolderMemberEvent = {
+ event:
+ | PostHogEventTypes.PamFolderMemberAdded
+ | PostHogEventTypes.PamFolderMemberUpdated
+ | PostHogEventTypes.PamFolderMemberRemoved;
properties: {
- resourceType: string;
- projectId: string;
- enabled: boolean;
- hasSchedule: boolean;
+ orgId: string;
};
};
-export type TPamRotationRuleDeletedEvent = {
- event: PostHogEventTypes.PamRotationRuleDeleted;
+export type TPamAccountMemberEvent = {
+ event:
+ | PostHogEventTypes.PamAccountMemberAdded
+ | PostHogEventTypes.PamAccountMemberUpdated
+ | PostHogEventTypes.PamAccountMemberRemoved;
properties: {
- resourceType: string;
- projectId: string;
+ orgId: string;
};
};
@@ -1944,16 +1940,15 @@ export type TPostHogEvent = {
| TGatewayCertExchangedEvent
| TGatewayUpdatedEvent
| TGatewayDeletedEvent
- | TPamResourceEvent
+ | TPamAccountTemplateEvent
+ | TPamFolderEvent
| TPamAccountEvent
| TPamAccountAccessedEvent
- | TPamAccountRotatedEvent
| TPamSessionStartedEvent
| TPamSessionEndedEvent
- | TPamWebAccessStartedEvent
- | TPamDiscoveryEvent
- | TPamRotationRuleCreatedEvent
- | TPamRotationRuleDeletedEvent
+ | TPamProductMemberEvent
+ | TPamFolderMemberEvent
+ | TPamAccountMemberEvent
| TResourceAuthMethodEvent
| THoneyTokenCreatedEvent
| THoneyTokenUpdatedEvent
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index b969caba01..aa810999df 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -312,9 +312,21 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.PAM_SESSION_TERMINATE]: "Terminate PAM Session",
[EventType.PAM_SESSION_GET]: "Get PAM Session",
[EventType.PAM_SESSION_LIST]: "List PAM Sessions",
+ [EventType.PAM_ACCOUNT_TEMPLATE_CREATE]: "Create PAM Account Template",
+ [EventType.PAM_ACCOUNT_TEMPLATE_UPDATE]: "Update PAM Account Template",
+ [EventType.PAM_ACCOUNT_TEMPLATE_DELETE]: "Delete PAM Account Template",
[EventType.PAM_FOLDER_CREATE]: "Create PAM Folder",
[EventType.PAM_FOLDER_UPDATE]: "Update PAM Folder",
[EventType.PAM_FOLDER_DELETE]: "Delete PAM Folder",
+ [EventType.PAM_PRODUCT_MEMBER_ADD]: "Add PAM Product Member",
+ [EventType.PAM_PRODUCT_MEMBER_UPDATE]: "Update PAM Product Member",
+ [EventType.PAM_PRODUCT_MEMBER_REMOVE]: "Remove PAM Product Member",
+ [EventType.PAM_FOLDER_MEMBER_ADD]: "Add PAM Folder Member",
+ [EventType.PAM_FOLDER_MEMBER_UPDATE]: "Update PAM Folder Member",
+ [EventType.PAM_FOLDER_MEMBER_REMOVE]: "Remove PAM Folder Member",
+ [EventType.PAM_ACCOUNT_MEMBER_ADD]: "Add PAM Account Member",
+ [EventType.PAM_ACCOUNT_MEMBER_UPDATE]: "Update PAM Account Member",
+ [EventType.PAM_ACCOUNT_MEMBER_REMOVE]: "Remove PAM Account Member",
[EventType.PAM_ACCOUNT_LIST]: "List PAM Accounts",
[EventType.PAM_ACCOUNT_ACCESS]: "Access PAM Account",
[EventType.PAM_ACCOUNT_CREATE]: "Create PAM Account",
@@ -333,28 +345,6 @@ export const eventToNameMap: { [K in EventType]: string } = {
[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",
- [EventType.PAM_RESOURCE_UPDATE]: "Update PAM Resource",
- [EventType.PAM_RESOURCE_DELETE]: "Delete PAM Resource",
-
- [EventType.PAM_DISCOVERY_SOURCE_LIST]: "List PAM Discovery Sources",
- [EventType.PAM_DISCOVERY_SOURCE_GET]: "Get PAM Discovery Source",
- [EventType.PAM_DISCOVERY_SOURCE_CREATE]: "Create PAM Discovery Source",
- [EventType.PAM_DISCOVERY_SOURCE_UPDATE]: "Update PAM Discovery Source",
- [EventType.PAM_DISCOVERY_SOURCE_DELETE]: "Delete PAM Discovery Source",
- [EventType.PAM_DISCOVERY_SCAN]: "PAM Discovery Scan",
- [EventType.PAM_DISCOVERY_SOURCE_RUN_LIST]: "List PAM Discovery Source Runs",
- [EventType.PAM_DISCOVERY_SOURCE_RUN_GET]: "Get PAM Discovery Source Run",
- [EventType.PAM_DISCOVERY_SOURCE_RESOURCE_LIST]: "List PAM Discovery Source Resources",
- [EventType.PAM_DISCOVERY_SOURCE_ACCOUNT_LIST]: "List PAM Discovery Source Accounts",
- [EventType.PAM_RESOURCE_ROTATION_RULE_LIST]: "List PAM Resource Rotation Rules",
- [EventType.PAM_RESOURCE_ROTATION_RULE_CREATE]: "Create PAM Resource Rotation Rule",
- [EventType.PAM_RESOURCE_ROTATION_RULE_UPDATE]: "Update PAM Resource Rotation Rule",
- [EventType.PAM_RESOURCE_ROTATION_RULE_DELETE]: "Delete PAM Resource Rotation Rule",
- [EventType.PAM_RESOURCE_ROTATION_RULE_REORDER]: "Reorder PAM Resource Rotation Rules",
-
[EventType.CREATE_CERTIFICATE_PROFILE]: "Create Certificate Profile",
[EventType.UPDATE_CERTIFICATE_PROFILE]: "Update Certificate Profile",
[EventType.DELETE_CERTIFICATE_PROFILE]: "Delete Certificate Profile",
@@ -499,9 +489,21 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {
EventType.PAM_SESSION_TERMINATE,
EventType.PAM_SESSION_GET,
EventType.PAM_SESSION_LIST,
+ EventType.PAM_ACCOUNT_TEMPLATE_CREATE,
+ EventType.PAM_ACCOUNT_TEMPLATE_UPDATE,
+ EventType.PAM_ACCOUNT_TEMPLATE_DELETE,
EventType.PAM_FOLDER_CREATE,
EventType.PAM_FOLDER_UPDATE,
EventType.PAM_FOLDER_DELETE,
+ EventType.PAM_PRODUCT_MEMBER_ADD,
+ EventType.PAM_PRODUCT_MEMBER_UPDATE,
+ EventType.PAM_PRODUCT_MEMBER_REMOVE,
+ EventType.PAM_FOLDER_MEMBER_ADD,
+ EventType.PAM_FOLDER_MEMBER_UPDATE,
+ EventType.PAM_FOLDER_MEMBER_REMOVE,
+ EventType.PAM_ACCOUNT_MEMBER_ADD,
+ EventType.PAM_ACCOUNT_MEMBER_UPDATE,
+ EventType.PAM_ACCOUNT_MEMBER_REMOVE,
EventType.PAM_ACCOUNT_LIST,
EventType.PAM_ACCOUNT_ACCESS,
EventType.PAM_ACCOUNT_CREATE,
@@ -514,26 +516,6 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {
EventType.PAM_ACCOUNT_POLICY_GET,
EventType.PAM_ACCOUNT_READ_CREDENTIALS,
EventType.PAM_WEB_ACCESS_SESSION_TICKET_CREATED,
- EventType.PAM_RESOURCE_LIST,
- EventType.PAM_RESOURCE_GET,
- EventType.PAM_RESOURCE_CREATE,
- EventType.PAM_RESOURCE_UPDATE,
- EventType.PAM_RESOURCE_DELETE,
- EventType.PAM_DISCOVERY_SOURCE_LIST,
- EventType.PAM_DISCOVERY_SOURCE_GET,
- EventType.PAM_DISCOVERY_SOURCE_CREATE,
- EventType.PAM_DISCOVERY_SOURCE_UPDATE,
- EventType.PAM_DISCOVERY_SOURCE_DELETE,
- EventType.PAM_DISCOVERY_SCAN,
- EventType.PAM_DISCOVERY_SOURCE_RUN_LIST,
- EventType.PAM_DISCOVERY_SOURCE_RUN_GET,
- EventType.PAM_DISCOVERY_SOURCE_RESOURCE_LIST,
- EventType.PAM_DISCOVERY_SOURCE_ACCOUNT_LIST,
- EventType.PAM_RESOURCE_ROTATION_RULE_LIST,
- 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_SESSION_CHUNK_UPLOAD,
EventType.PAM_SESSION_UPLOAD_TOKEN_INVALID,
EventType.PAM_RECORDING_CONFIG_UPDATE,
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index 49dcd625d0..38fe01ede0 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -304,9 +304,21 @@ export enum EventType {
PAM_SESSION_TERMINATE = "pam-session-terminate",
PAM_SESSION_GET = "pam-session-get",
PAM_SESSION_LIST = "pam-session-list",
+ PAM_ACCOUNT_TEMPLATE_CREATE = "pam-account-template-create",
+ PAM_ACCOUNT_TEMPLATE_UPDATE = "pam-account-template-update",
+ PAM_ACCOUNT_TEMPLATE_DELETE = "pam-account-template-delete",
PAM_FOLDER_CREATE = "pam-folder-create",
PAM_FOLDER_UPDATE = "pam-folder-update",
PAM_FOLDER_DELETE = "pam-folder-delete",
+ PAM_PRODUCT_MEMBER_ADD = "pam-product-member-add",
+ PAM_PRODUCT_MEMBER_UPDATE = "pam-product-member-update",
+ PAM_PRODUCT_MEMBER_REMOVE = "pam-product-member-remove",
+ PAM_FOLDER_MEMBER_ADD = "pam-folder-member-add",
+ PAM_FOLDER_MEMBER_UPDATE = "pam-folder-member-update",
+ PAM_FOLDER_MEMBER_REMOVE = "pam-folder-member-remove",
+ PAM_ACCOUNT_MEMBER_ADD = "pam-account-member-add",
+ PAM_ACCOUNT_MEMBER_UPDATE = "pam-account-member-update",
+ PAM_ACCOUNT_MEMBER_REMOVE = "pam-account-member-remove",
PAM_ACCOUNT_LIST = "pam-account-list",
PAM_ACCOUNT_ACCESS = "pam-account-access",
PAM_ACCOUNT_CREATE = "pam-account-create",
@@ -319,27 +331,6 @@ export enum EventType {
PAM_ACCOUNT_POLICY_GET = "pam-account-policy-get",
PAM_ACCOUNT_READ_CREDENTIALS = "pam-account-read-credentials",
PAM_WEB_ACCESS_SESSION_TICKET_CREATED = "pam-web-access-session-ticket-created",
- PAM_RESOURCE_LIST = "pam-resource-list",
- PAM_RESOURCE_GET = "pam-resource-get",
- PAM_RESOURCE_CREATE = "pam-resource-create",
- PAM_RESOURCE_UPDATE = "pam-resource-update",
- PAM_RESOURCE_DELETE = "pam-resource-delete",
-
- PAM_DISCOVERY_SOURCE_LIST = "pam-discovery-source-list",
- PAM_DISCOVERY_SOURCE_GET = "pam-discovery-source-get",
- PAM_DISCOVERY_SOURCE_CREATE = "pam-discovery-source-create",
- PAM_DISCOVERY_SOURCE_UPDATE = "pam-discovery-source-update",
- PAM_DISCOVERY_SOURCE_DELETE = "pam-discovery-source-delete",
- PAM_DISCOVERY_SCAN = "pam-discovery-scan",
- PAM_DISCOVERY_SOURCE_RUN_LIST = "pam-discovery-source-run-list",
- PAM_DISCOVERY_SOURCE_RUN_GET = "pam-discovery-source-run-get",
- PAM_DISCOVERY_SOURCE_RESOURCE_LIST = "pam-discovery-source-resource-list",
- PAM_DISCOVERY_SOURCE_ACCOUNT_LIST = "pam-discovery-source-account-list",
- PAM_RESOURCE_ROTATION_RULE_LIST = "pam-resource-rotation-rule-list",
- PAM_RESOURCE_ROTATION_RULE_CREATE = "pam-resource-rotation-rule-create",
- 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",