Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
checkpoint 1: schema, migration, and project bootstrapping
x03220599589c8b65df
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex 1943188ba8..d2d95a27b9 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -39,6 +39,7 @@ import { TPamDiscoverySourceServiceFactory } from "@app/ee/services/pam-discoverimport { TPamDomainServiceFactory } from "@app/ee/services/pam-domain/pam-domain-service";import { TPamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";import { TPamInsightsServiceFactory } from "@app/ee/services/pam-insights/pam-insights-service";+import { TPamProjectResolverFactory } from "@app/ee/services/pam-instance/pam-project-resolver";import { TPamProjectRecordingConfigServiceFactory } from "@app/ee/services/pam-project-recording-config/pam-project-recording-config-service";import { TPamResourceRotationRulesServiceFactory } from "@app/ee/services/pam-resource/pam-resource-rotation-rules-service";import { TPamResourceServiceFactory } from "@app/ee/services/pam-resource/pam-resource-service";@@ -263,6 +264,7 @@ declare module "fastify" {};auditLogInfo: Pick<TCreateAuditLogDTO, "userAgent" | "userAgentType" | "ipAddress" | "actor" | "orgId">;internalCertManagerProjectId: string;+ internalPamProjectId: string;ssoConfig: Awaited<ReturnType<TSamlConfigServiceFactory["getSaml"]>>;ldapConfig: Awaited<ReturnType<TLdapConfigServiceFactory["getLdapCfg"]>> & {allowedFields?: TAllowedFields[];@@ -341,6 +343,7 @@ declare module "fastify" {signerPolicy: TSignerPolicyServiceFactory;pkiApplicationEnrollment: TPkiApplicationEnrollmentServiceFactory;certManagerProjectResolver: TCertManagerProjectResolverFactory;+ pamProjectResolver: TPamProjectResolverFactory;certManagerInstance: TCertManagerInstanceServiceFactory;certManagerExport: TCertManagerExportServiceFactory;sshCertificateAuthority: TSshCertificateAuthorityServiceFactory;diff --git a/backend/src/db/migrations/20260603030053_pam-revamp.ts b/backend/src/db/migrations/20260603030053_pam-revamp.tsnew file mode 100644index 0000000000..83f051393e--- /dev/null+++ b/backend/src/db/migrations/20260603030053_pam-revamp.ts@@ -0,0 +1,446 @@+/* eslint-disable no-await-in-loop */+import slugify from "@sindresorhus/slugify";+import { Knex } from "knex";++import { PamFolderRole, PamProductRole } 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 { initLogger } from "@app/lib/logger";+import { alphaNumericNanoId } from "@app/lib/nanoid";+import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";+import { KmsDataKey } from "@app/services/kms/kms-types";+import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";++import {+ AccessScope,+ OrgMembershipRole,+ ProjectMembershipRole,+ ProjectType,+ RESOURCE_SCOPE,+ ResourceType,+ TableName+} from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";+import { getMigrationEnvConfig, getMigrationHsmConfig } from "./utils/env-config";+import { getMigrationEncryptionServices, getMigrationHsmService } from "./utils/services";++const BACKFILL_CHUNK_SIZE = 8;++const seedDefaultTemplates = async (knex: Knex, orgId: string) => {+ for (const template of DEFAULT_ACCOUNT_TEMPLATES) {+ await knex(TableName.PamAccountTemplate)+ .insert({+ orgId,+ name: template.name,+ type: template.type,+ accessPolicy: JSON.stringify(template.accessPolicy),+ settings: JSON.stringify(template.settings)+ })+ .onConflict(["orgId", "name"])+ .ignore();+ }+};++const createPamProjectForOrg = async (knex: Knex, orgId: string) => {+ const slug = slugify(`pam-${alphaNumericNanoId(4)}`);++ const [{ id: projectId }] = (await knex(TableName.Project)+ .insert({+ name: "Access Management",+ slug,+ type: ProjectType.PAM,+ orgId,+ version: 3,+ pitVersionLimit: 10+ })+ .returning("id")) as Array<{ id: string }>;++ await knex(TableName.Organization).where("id", orgId).update({ defaultPamProjectId: projectId });+ await seedDefaultTemplates(knex, orgId);++ return projectId;+};++const backfillPamProjectsForAllOrgs = async (knex: Knex) => {+ const allOrgs = (await knex(TableName.Organization).whereNull("defaultPamProjectId").select("id")) as Array<{+ id: string;+ }>;++ for (let i = 0; i < allOrgs.length; i += BACKFILL_CHUNK_SIZE) {+ const chunk = allOrgs.slice(i, i + BACKFILL_CHUNK_SIZE);+ await Promise.all(chunk.map(({ id }) => createPamProjectForOrg(knex, id)));+ }+};++export async function up(knex: Knex): Promise<void> {+ await knex.schema.alterTable(TableName.Organization, (t) => {+ t.string("defaultPamProjectId", 36).nullable();+ t.foreign("defaultPamProjectId").references("id").inTable(TableName.Project).onDelete("SET NULL");+ });++ await knex.schema.createTable(TableName.PamAccountTemplate, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());++ t.uuid("orgId").notNullable();+ t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");+ t.index("orgId");++ t.string("name").notNullable();+ t.text("description").nullable();++ t.string("type").notNullable();+ t.index("type");++ t.jsonb("accessPolicy").nullable();+ t.jsonb("settings").nullable();++ t.uuid("gatewayId").nullable();+ t.foreign("gatewayId").references("id").inTable(TableName.GatewayV2).onDelete("SET NULL");++ t.uuid("gatewayPoolId").nullable();+ t.foreign("gatewayPoolId").references("id").inTable(TableName.GatewayPool).onDelete("SET NULL");++ t.uuid("recordingConnectionId").nullable();+ t.foreign("recordingConnectionId").references("id").inTable(TableName.AppConnection).onDelete("SET NULL");++ t.unique(["orgId", "name"]);++ t.timestamps(true, true, true);+ });++ await createOnUpdateTrigger(knex, TableName.PamAccountTemplate);++ await backfillPamProjectsForAllOrgs(knex);++ // Drop old folders table and recreate with new schema+ await knex.raw(`UPDATE ${TableName.PamAccount} SET "folderId" = NULL WHERE "folderId" IS NOT NULL`);+ await knex.schema.alterTable(TableName.PamAccount, (t) => {+ t.dropForeign(["folderId"]);+ });+ await dropOnUpdateTrigger(knex, TableName.PamFolder);+ await knex.schema.dropTable(TableName.PamFolder);++ await knex.schema.createTable(TableName.PamFolder, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());++ t.uuid("orgId").notNullable();+ t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");+ t.index("orgId");++ t.string("name").notNullable();+ t.index("name");++ t.text("description").nullable();++ t.unique(["orgId", "name"]);++ t.timestamps(true, true, true);+ });++ await createOnUpdateTrigger(knex, TableName.PamFolder);++ await knex.schema.alterTable(TableName.PamAccount, (t) => {+ t.foreign("folderId").references("id").inTable(TableName.PamFolder).onDelete("CASCADE");+ });++ // Add new columns to accounts+ await knex.raw(`ALTER TABLE ${TableName.PamAccount} DROP CONSTRAINT IF EXISTS chk_pam_account_parent`);++ await knex.schema.alterTable(TableName.PamAccount, (t) => {+ t.uuid("orgId").nullable();+ t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");+ t.index("orgId");++ t.uuid("templateId").nullable();+ t.foreign("templateId").references("id").inTable(TableName.PamAccountTemplate).onDelete("RESTRICT");+ t.index("templateId");++ t.binary("encryptedConnectionDetails").nullable();+ t.binary("encryptedInternalMetadata").nullable();++ t.uuid("gatewayId").nullable();+ t.foreign("gatewayId").references("id").inTable(TableName.GatewayV2).onDelete("SET NULL");++ t.uuid("gatewayPoolId").nullable();+ t.foreign("gatewayPoolId").references("id").inTable(TableName.GatewayPool).onDelete("SET NULL");++ t.uuid("recordingConnectionId").nullable();+ t.foreign("recordingConnectionId").references("id").inTable(TableName.AppConnection).onDelete("SET NULL");+ });++ await knex.raw(`+ UPDATE ${TableName.PamAccount} a+ SET "orgId" = p."orgId"+ FROM ${TableName.Project} p+ WHERE a."projectId" = p.id+ `);++ // Migrate data from old projects+ initLogger();+ const { hsmService } = await getMigrationHsmService({ envConfig: getMigrationHsmConfig() });+ const superAdminDAL = superAdminDALFactory(knex);+ const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);+ const envConfig = await getMigrationEnvConfig(superAdminDAL, hsmService, kmsRootConfigDAL);+ const keyStore = inMemoryKeyStore();+ const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db: knex });++ const getProjectCipher = async (projectId: string) =>+ kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId }, knex);++ const orgsWithPam = await knex(TableName.Project).where("type", ProjectType.PAM).distinct("orgId").select("orgId");++ for (const { orgId } of orgsWithPam) {+ const org = await knex(TableName.Organization).where("id", orgId).first("defaultPamProjectId");+ const newProjectId = org!.defaultPamProjectId as string;+ const newProjectCipher = await getProjectCipher(newProjectId);++ const reEncrypt = (oldCipher: Awaited<ReturnType<typeof getProjectCipher>>, blob?: Buffer | null) => {+ if (!blob) return undefined;+ const plainText = oldCipher.decryptor({ cipherTextBlob: blob });+ return newProjectCipher.encryptor({ plainText }).cipherTextBlob;+ };++ const templates = await knex(TableName.PamAccountTemplate).where({ orgId }).select("id", "type");+ const templateMap: Record<string, string> = {};+ for (const t of templates) {+ templateMap[t.type] = t.id;+ }++ const oldPamProjects = await knex(TableName.Project)+ .where({ orgId, type: ProjectType.PAM })+ .whereNot("id", newProjectId)+ .select("id", "name");++ const projectToFolder: Record<string, string> = {};++ for (const project of oldPamProjects) {+ const folderName = slugify(project.name) || project.id.slice(0, 8);+ const [folder] = await knex(TableName.PamFolder).insert({ orgId, name: folderName }).returning("id");+ projectToFolder[project.id] = folder.id;+ }++ for (const [projectId, folderId] of Object.entries(projectToFolder)) {+ const oldProjectCipher = await getProjectCipher(projectId);++ const resourceAccounts = await knex(TableName.PamAccount)+ .join(TableName.PamResource, `${TableName.PamAccount}.resourceId`, `${TableName.PamResource}.id`)+ .where(`${TableName.PamResource}.projectId`, projectId)+ .select(+ `${TableName.PamAccount}.id as accountId`,+ `${TableName.PamAccount}.encryptedCredentials`,+ `${TableName.PamResource}.resourceType`,+ `${TableName.PamResource}.encryptedConnectionDetails`,+ `${TableName.PamResource}.encryptedResourceMetadata`,+ `${TableName.PamResource}.gatewayId`,+ `${TableName.PamResource}.gatewayPoolId`+ );++ for (const account of resourceAccounts) {+ const templateId = templateMap[account.resourceType];+ if (!templateId) continue;++ await knex(TableName.PamAccount)+ .where("id", account.accountId)+ .update({+ folderId,+ templateId,+ encryptedCredentials: reEncrypt(oldProjectCipher, account.encryptedCredentials),+ encryptedConnectionDetails: reEncrypt(oldProjectCipher, account.encryptedConnectionDetails),+ encryptedInternalMetadata: reEncrypt(oldProjectCipher, account.encryptedResourceMetadata),+ gatewayId: account.gatewayId,+ gatewayPoolId: account.gatewayPoolId+ });+ }++ const domainAccounts = await knex(TableName.PamAccount)+ .join(TableName.PamDomain, `${TableName.PamAccount}.domainId`, `${TableName.PamDomain}.id`)+ .where(`${TableName.PamDomain}.projectId`, projectId)+ .select(+ `${TableName.PamAccount}.id as accountId`,+ `${TableName.PamAccount}.encryptedCredentials`,+ `${TableName.PamDomain}.domainType`,+ `${TableName.PamDomain}.encryptedConnectionDetails`,+ `${TableName.PamDomain}.gatewayId`,+ `${TableName.PamDomain}.gatewayPoolId`+ );++ for (const account of domainAccounts) {+ const templateId = templateMap[account.domainType];+ if (!templateId) continue;++ await knex(TableName.PamAccount)+ .where("id", account.accountId)+ .update({+ folderId,+ templateId,+ encryptedCredentials: reEncrypt(oldProjectCipher, account.encryptedCredentials),+ encryptedConnectionDetails: reEncrypt(oldProjectCipher, account.encryptedConnectionDetails),+ gatewayId: account.gatewayId,+ gatewayPoolId: account.gatewayPoolId+ });+ }+ }++ // Migrate permissions+ const orgAdmins = new Set(+ (+ await knex(TableName.Membership)+ .join(TableName.MembershipRole, `${TableName.MembershipRole}.membershipId`, `${TableName.Membership}.id`)+ .where(`${TableName.Membership}.scope`, AccessScope.Organization)+ .where(`${TableName.Membership}.scopeOrgId`, orgId)+ .where(`${TableName.MembershipRole}.role`, OrgMembershipRole.Admin)+ .whereNotNull(`${TableName.Membership}.actorUserId`)+ .select(`${TableName.Membership}.actorUserId as userId`)+ ).map((r: { userId: string }) => r.userId)+ );++ const pamProjectAdmins = new Set<string>();+ const allPamUsers = new Map<string, string[]>();++ for (const project of oldPamProjects) {+ const projectMembers = await knex(TableName.Membership)+ .where({ scope: AccessScope.Project, scopeProjectId: project.id })+ .whereNotNull("actorUserId")+ .select("id", "actorUserId as userId");++ for (const member of projectMembers) {+ if (!allPamUsers.has(member.userId)) {+ allPamUsers.set(member.userId, []);+ }+ allPamUsers.get(member.userId)!.push(project.id);++ const roles = await knex(TableName.MembershipRole).where("membershipId", member.id).select("role");++ if (roles.some((r: { role: string }) => r.role === ProjectMembershipRole.Admin)) {+ pamProjectAdmins.add(member.userId);+ }+ }+ }++ for (const [userId] of allPamUsers) {+ const isProductAdmin = orgAdmins.has(userId) && pamProjectAdmins.has(userId);++ const [membership] = await knex(TableName.Membership)+ .insert({+ scope: AccessScope.Project,+ scopeOrgId: orgId,+ scopeProjectId: newProjectId,+ actorUserId: userId,+ isActive: true+ })+ .returning("id");++ await knex(TableName.MembershipRole).insert({+ membershipId: membership.id,+ role: isProductAdmin ? PamProductRole.Admin : PamProductRole.Member+ });+ }++ for (const project of oldPamProjects) {+ const folderId = projectToFolder[project.id];++ const projectMembers = await knex(TableName.Membership)+ .where({ scope: AccessScope.Project, scopeProjectId: project.id })+ .whereNotNull("actorUserId")+ .select("id", "actorUserId as userId");++ for (const member of projectMembers) {+ 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.Connector;++ const [folderMembership] = await knex(TableName.Membership)+ .insert({+ scope: RESOURCE_SCOPE,+ scopeOrgId: orgId,+ scopeProjectId: newProjectId,+ scopeResourceType: ResourceType.PamFolder,+ scopeResourceId: folderId,+ actorUserId: member.userId,+ isActive: true+ })+ .returning("id");++ await knex(TableName.MembershipRole).insert({+ membershipId: folderMembership.id,+ role: folderRole+ });+ }+ }+ }++ // Clean up orphaned accounts and deduplicate before adding constraints+ await knex(TableName.PamAccount).whereNull("folderId").orWhereNull("templateId").delete();++ await knex.raw(`+ UPDATE ${TableName.PamAccount} a+ SET name = a.name || '-' || LEFT(a.id::text, 8)+ FROM (+ SELECT id, ROW_NUMBER() OVER (PARTITION BY "folderId", name ORDER BY "createdAt") AS rn+ FROM ${TableName.PamAccount}+ WHERE "folderId" IS NOT NULL+ ) dups+ WHERE a.id = dups.id AND dups.rn > 1+ `);++ await knex.raw(`DROP INDEX IF EXISTS "uidx_pam_account_children_name"`);+ await knex.raw(`DROP INDEX IF EXISTS "uidx_pam_account_root_name"`);++ await knex.schema.alterTable(TableName.PamAccount, (t) => {+ t.uuid("orgId").notNullable().alter();+ t.uuid("templateId").notNullable().alter();+ t.binary("encryptedConnectionDetails").notNullable().alter();+ t.dropColumn("projectId");+ t.dropColumn("resourceId");+ t.dropColumn("domainId");+ t.dropColumn("policyId");+ t.dropColumn("lastRotatedAt");+ t.dropColumn("rotationStatus");+ t.dropColumn("encryptedLastRotationMessage");+ t.dropColumn("requireMfa");+ t.dropColumn("internalMetadata");+ t.dropColumn("discoveryFingerprint");+ t.unique(["folderId", "name"]);+ });++ // Sessions+ await knex.schema.alterTable(TableName.PamSession, (t) => {+ t.uuid("orgId").nullable();+ t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");+ t.index("orgId");+ t.string("folderName").nullable();+ t.string("selectedHost").nullable();+ });++ await knex.raw(`+ UPDATE ${TableName.PamSession} s+ SET "orgId" = p."orgId"+ FROM ${TableName.Project} p+ WHERE s."projectId" = p.id+ `);++ await knex(TableName.PamSession).whereNull("orgId").delete();++ await knex.schema.alterTable(TableName.PamSession, (t) => {+ t.uuid("orgId").notNullable().alter();+ });++ await knex.schema.alterTable(TableName.PamSession, (t) => {+ t.renameColumn("resourceType", "accountType");+ });++ await knex.schema.alterTable(TableName.PamSession, (t) => {+ t.dropColumn("projectId");+ t.dropColumn("resourceName");+ t.dropColumn("resourceId");+ t.dropColumn("selectedResourceId");+ t.dropColumn("encryptedAiInsights");+ t.dropColumn("aiInsightsStatus");+ t.dropColumn("aiInsightsError");+ });+}++export async function down(): Promise<void> {+ // No down migration or it will error+}diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 9617cc1308..b8f20e393f 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -121,6 +121,7 @@ export * from "./organization-assets";export * from "./organizations";export * from "./pam-account-dependencies";export * from "./pam-account-policies";+export * from "./pam-account-templates";export * from "./pam-accounts";export * from "./pam-discovery-source-accounts";export * from "./pam-discovery-source-dependencies";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex 22f9bc6b98..f2877293dc 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -230,6 +230,7 @@ export enum TableName {KeyValueStore = "key_value_store",// PAM+ PamAccountTemplate = "pam_account_templates",PamFolder = "pam_folders",PamResource = "pam_resources",PamAccount = "pam_accounts",@@ -364,7 +365,9 @@ export enum ResourceMembershipRole {export enum ResourceType {CertificateApplication = "certificate-application",- Signer = "pki-signer"+ Signer = "pki-signer",+ PamFolder = "pam-folder",+ PamAccount = "pam-account"}export enum SecretEncryptionAlgo {diff --git a/backend/src/db/schemas/organizations.ts b/backend/src/db/schemas/organizations.tsindex 76ad1aa180..eb9596139e 100644--- a/backend/src/db/schemas/organizations.ts+++ b/backend/src/db/schemas/organizations.ts@@ -43,7 +43,8 @@ export const OrganizationsSchema = z.object({rootOrgId: z.string().uuid().nullable().optional(),blockDuplicateSecretSyncDestinations: z.boolean().default(false),secretShareBrandConfig: z.unknown().nullable().optional(),- defaultCertManagerProjectId: z.string().nullable().optional()+ defaultCertManagerProjectId: z.string().nullable().optional(),+ defaultPamProjectId: z.string().nullable().optional()});export type TOrganizations = z.infer<typeof OrganizationsSchema>;diff --git a/backend/src/db/schemas/pam-account-templates.ts b/backend/src/db/schemas/pam-account-templates.tsnew file mode 100644index 0000000000..25754e210d--- /dev/null+++ b/backend/src/db/schemas/pam-account-templates.ts@@ -0,0 +1,27 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { TImmutableDBKeys } from "./models";++export const PamAccountTemplatesSchema = z.object({+ id: z.string().uuid(),+ orgId: z.string().uuid(),+ name: z.string(),+ description: z.string().nullable().optional(),+ type: z.string(),+ accessPolicy: z.unknown().nullable().optional(),+ settings: z.unknown().nullable().optional(),+ gatewayId: z.string().uuid().nullable().optional(),+ gatewayPoolId: z.string().uuid().nullable().optional(),+ recordingConnectionId: z.string().uuid().nullable().optional(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TPamAccountTemplates = z.infer<typeof PamAccountTemplatesSchema>;+export type TPamAccountTemplatesInsert = Omit<z.input<typeof PamAccountTemplatesSchema>, TImmutableDBKeys>;+export type TPamAccountTemplatesUpdate = Partial<Omit<z.input<typeof PamAccountTemplatesSchema>, TImmutableDBKeys>>;diff --git a/backend/src/db/schemas/pam-accounts.ts b/backend/src/db/schemas/pam-accounts.tsindex 8402e7b1d5..bdf8e5c1b0 100644--- a/backend/src/db/schemas/pam-accounts.ts+++ b/backend/src/db/schemas/pam-accounts.ts@@ -11,22 +11,19 @@ import { TImmutableDBKeys } from "./models";export const PamAccountsSchema = z.object({id: z.string().uuid(),- projectId: z.string(),folderId: z.string().uuid().nullable().optional(),- resourceId: z.string().uuid().nullable().optional(),name: z.string(),description: z.string().nullable().optional(),encryptedCredentials: zodBuffer,createdAt: z.date(),updatedAt: z.date(),- lastRotatedAt: z.date().nullable().optional(),- rotationStatus: z.string().nullable().optional(),- encryptedLastRotationMessage: zodBuffer.nullable().optional(),- requireMfa: z.boolean().default(false).nullable().optional(),- internalMetadata: z.unknown().nullable().optional(),- discoveryFingerprint: z.string().nullable().optional(),- policyId: z.string().uuid().nullable().optional(),- domainId: z.string().uuid().nullable().optional()+ orgId: z.string().uuid(),+ templateId: z.string().uuid(),+ encryptedConnectionDetails: zodBuffer,+ encryptedInternalMetadata: zodBuffer.nullable().optional(),+ gatewayId: z.string().uuid().nullable().optional(),+ gatewayPoolId: z.string().uuid().nullable().optional(),+ recordingConnectionId: z.string().uuid().nullable().optional()});export type TPamAccounts = z.infer<typeof PamAccountsSchema>;diff --git a/backend/src/db/schemas/pam-folders.ts b/backend/src/db/schemas/pam-folders.tsindex 80243c1bce..360937ba94 100644--- a/backend/src/db/schemas/pam-folders.ts+++ b/backend/src/db/schemas/pam-folders.ts@@ -9,8 +9,7 @@ import { TImmutableDBKeys } from "./models";export const PamFoldersSchema = z.object({id: z.string().uuid(),- projectId: z.string(),- parentId: z.string().uuid().nullable().optional(),+ orgId: z.string().uuid(),name: z.string(),description: z.string().nullable().optional(),createdAt: z.date(),diff --git a/backend/src/db/schemas/pam-sessions.ts b/backend/src/db/schemas/pam-sessions.tsindex 230328fc54..48a8d90d4a 100644--- a/backend/src/db/schemas/pam-sessions.ts+++ b/backend/src/db/schemas/pam-sessions.ts@@ -11,10 +11,8 @@ import { TImmutableDBKeys } from "./models";export const PamSessionsSchema = z.object({id: z.string().uuid(),- projectId: z.string(),accountId: z.string().uuid().nullable().optional(),- resourceType: z.string(),- resourceName: z.string(),+ accountType: z.string(),accountName: z.string(),userId: z.string().uuid().nullable().optional(),actorName: z.string(),@@ -29,15 +27,13 @@ export const PamSessionsSchema = z.object({createdAt: z.date(),updatedAt: z.date(),accessMethod: z.string().nullable().optional(),- resourceId: z.string().uuid().nullable().optional(),- encryptedAiInsights: zodBuffer.nullable().optional(),- aiInsightsStatus: z.string().nullable().optional(),- aiInsightsError: z.string().nullable().optional(),reason: z.string().nullable().optional(),- selectedResourceId: z.string().uuid().nullable().optional(),encryptedSessionKey: zodBuffer.nullable().optional(),gatewayUploadTokenHash: zodBuffer.nullable().optional(),- gatewayId: z.string().uuid().nullable().optional()+ gatewayId: z.string().uuid().nullable().optional(),+ orgId: z.string().uuid(),+ folderName: z.string().nullable().optional(),+ selectedHost: z.string().nullable().optional()});export type TPamSessions = z.infer<typeof PamSessionsSchema>;diff --git a/backend/src/ee/routes/v1/index.ts b/backend/src/ee/routes/v1/index.tsindex e01b59e78e..bc11127229 100644--- a/backend/src/ee/routes/v1/index.ts+++ b/backend/src/ee/routes/v1/index.ts@@ -1,5 +1,6 @@import { registerProjectTemplateRouter } from "@app/ee/routes/v1/project-template-router";import { injectCertManagerProjectId } from "@app/server/plugins/inject-cert-manager-project-id";+import { injectPamProjectId } from "@app/server/plugins/inject-pam-project-id";import { registerAccessApprovalPolicyRouter } from "./access-approval-policy-router";import { registerAccessApprovalRequestRouter } from "./access-approval-request-router";@@ -216,6 +217,7 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {await server.register(async (pamRouter) => {+ await pamRouter.register(injectPamProjectId);await pamRouter.register(registerPamFolderRouter, { prefix: "/folders" });await pamRouter.register(async (sessionRouter) => {diff --git a/backend/src/ee/services/pam-instance/pam-project-bootstrap.ts b/backend/src/ee/services/pam-instance/pam-project-bootstrap.tsnew file mode 100644index 0000000000..78628be48e--- /dev/null+++ b/backend/src/ee/services/pam-instance/pam-project-bootstrap.ts@@ -0,0 +1,287 @@+import slugify from "@sindresorhus/slugify";+import { Knex } from "knex";++import { AccessScope, ProjectMembershipRole, ProjectType, ProjectVersion, TableName, TProjects } from "@app/db/schemas";+import { alphaNumericNanoId } from "@app/lib/nanoid";+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";+import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";+import { TProjectDALFactory } from "@app/services/project/project-dal";++import { PamAccountType } from "../pam/pam-enums";+import { TPamTemplateAccessPolicy, TPamTemplateSettings } from "../pam/pam-template-config-schemas";+import { PamRecordingStorageBackend } from "../pam-session-recording-storage/pam-session-recording-storage-enums";++type TBootstrapDeps = {+ projectDAL: Pick<TProjectDALFactory, "create" | "findOne">;+ membershipDAL: Pick<TMembershipDALFactory, "create">;+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create">;+};++type TBootstrapInput = {+ orgId: string;+ adminUserIds?: string[];+ adminIdentityIds?: string[];+};++export type TDefaultTemplate = {+ name: string;+ type: PamAccountType;+ accessPolicy: TPamTemplateAccessPolicy;+ settings: TPamTemplateSettings;+};++const DEFAULT_ACCESS_POLICY: TPamTemplateAccessPolicy = {+ maxSessionDurationSeconds: 3600,+ requireReason: false,+ requireMfa: false+};++export const DEFAULT_ACCOUNT_TEMPLATES: TDefaultTemplate[] = [+ {+ name: "ssh",+ type: PamAccountType.SSH,+ accessPolicy: DEFAULT_ACCESS_POLICY,+ settings: {+ recordingEnabled: true,+ recordingStorageBackend: PamRecordingStorageBackend.Postgres+ }+ },+ {+ name: "postgres",+ type: PamAccountType.Postgres,+ accessPolicy: DEFAULT_ACCESS_POLICY,+ settings: {+ recordingEnabled: true,+ recordingStorageBackend: PamRecordingStorageBackend.Postgres,+ passwordConstraints: {+ minLength: 16,+ maxLength: 99,+ requireUppercase: true,+ requireLowercase: true,+ requireNumbers: true,+ requireSymbols: false+ }+ }+ },+ {+ name: "mysql",+ type: PamAccountType.MySQL,+ accessPolicy: DEFAULT_ACCESS_POLICY,+ settings: {+ recordingEnabled: true,+ recordingStorageBackend: PamRecordingStorageBackend.Postgres,+ passwordConstraints: {+ minLength: 16,+ maxLength: 80,+ requireUppercase: true,+ requireLowercase: true,+ requireNumbers: true,+ requireSymbols: false+ }+ }+ },+ {+ name: "mssql",+ type: PamAccountType.MsSQL,+ accessPolicy: DEFAULT_ACCESS_POLICY,+ settings: {+ recordingEnabled: true,+ recordingStorageBackend: PamRecordingStorageBackend.Postgres,+ passwordConstraints: {+ minLength: 16,+ maxLength: 128,+ requireUppercase: true,+ requireLowercase: true,+ requireNumbers: true,+ requireSymbols: true+ }+ }+ },+ {+ name: "oracledb",+ type: PamAccountType.OracleDB,+ accessPolicy: DEFAULT_ACCESS_POLICY,+ settings: {+ recordingEnabled: true,+ recordingStorageBackend: PamRecordingStorageBackend.Postgres,+ passwordConstraints: {+ minLength: 16,+ maxLength: 30,+ requireUppercase: true,+ requireLowercase: true,+ requireNumbers: true,+ requireSymbols: true+ }+ }+ },+ {+ name: "mongodb",+ type: PamAccountType.MongoDB,+ accessPolicy: DEFAULT_ACCESS_POLICY,+ settings: {+ recordingEnabled: true,+ recordingStorageBackend: PamRecordingStorageBackend.Postgres,+ passwordConstraints: {+ minLength: 16,+ maxLength: 128,+ requireUppercase: true,+ requireLowercase: true,+ requireNumbers: true,+ requireSymbols: false+ }+ }+ },+ {+ name: "redis",+ type: PamAccountType.Redis,+ accessPolicy: DEFAULT_ACCESS_POLICY,+ settings: {+ recordingEnabled: true,+ recordingStorageBackend: PamRecordingStorageBackend.Postgres,+ passwordConstraints: {+ minLength: 16,+ maxLength: 128,+ requireUppercase: true,+ requireLowercase: true,+ requireNumbers: true,+ requireSymbols: false+ }+ }+ },+ {+ name: "kubernetes",+ type: PamAccountType.Kubernetes,+ accessPolicy: DEFAULT_ACCESS_POLICY,+ settings: {+ recordingEnabled: true,+ recordingStorageBackend: PamRecordingStorageBackend.Postgres+ }+ },+ {+ name: "aws-iam",+ type: PamAccountType.AwsIam,+ accessPolicy: DEFAULT_ACCESS_POLICY,+ settings: {+ recordingEnabled: true,+ recordingStorageBackend: PamRecordingStorageBackend.Postgres+ }+ },+ {+ name: "windows",+ type: PamAccountType.Windows,+ accessPolicy: DEFAULT_ACCESS_POLICY,+ settings: {+ recordingEnabled: true,+ recordingStorageBackend: PamRecordingStorageBackend.AwsS3,+ passwordConstraints: {+ minLength: 14,+ maxLength: 127,+ requireUppercase: true,+ requireLowercase: true,+ requireNumbers: true,+ requireSymbols: true+ }+ }+ },+ {+ name: "active-directory",+ type: PamAccountType.ActiveDirectory,+ accessPolicy: DEFAULT_ACCESS_POLICY,+ settings: {+ recordingEnabled: true,+ recordingStorageBackend: PamRecordingStorageBackend.AwsS3,+ passwordConstraints: {+ minLength: 14,+ maxLength: 127,+ requireUppercase: true,+ requireLowercase: true,+ requireNumbers: true,+ requireSymbols: true+ }+ }+ }+];++export const bootstrapPamProject = async (+ { orgId, adminUserIds = [], adminIdentityIds = [] }: TBootstrapInput,+ { projectDAL, membershipDAL, membershipRoleDAL }: TBootstrapDeps,+ tx: Knex+): Promise<{ project: TProjects; created: boolean }> => {+ const existing = await projectDAL.findOne({ orgId, type: ProjectType.PAM }, tx);+ if (existing) {+ return { project: existing, created: false };+ }++ const slug = slugify(`pam-${alphaNumericNanoId(4)}`);++ const project = await projectDAL.create(+ {+ name: "Access Management",+ slug,+ type: ProjectType.PAM,+ orgId,+ version: ProjectVersion.V3,+ pitVersionLimit: 10+ },+ tx+ );++ for (const userId of adminUserIds) {+ // eslint-disable-next-line no-await-in-loop+ const membership = await membershipDAL.create(+ {+ scope: AccessScope.Project,+ scopeOrgId: orgId,+ scopeProjectId: project.id,+ actorUserId: userId,+ isActive: true+ },+ tx+ );++ // eslint-disable-next-line no-await-in-loop+ await membershipRoleDAL.create(+ {+ membershipId: membership.id,+ role: ProjectMembershipRole.Admin+ },+ tx+ );+ }++ for (const identityId of adminIdentityIds) {+ // eslint-disable-next-line no-await-in-loop+ const membership = await membershipDAL.create(+ {+ scope: AccessScope.Project,+ scopeOrgId: orgId,+ scopeProjectId: project.id,+ actorIdentityId: identityId,+ isActive: true+ },+ tx+ );++ // eslint-disable-next-line no-await-in-loop+ await membershipRoleDAL.create(+ {+ membershipId: membership.id,+ role: ProjectMembershipRole.Admin+ },+ tx+ );+ }++ for (const template of DEFAULT_ACCOUNT_TEMPLATES) {+ // eslint-disable-next-line no-await-in-loop+ await tx(TableName.PamAccountTemplate).insert({+ orgId,+ name: template.name,+ type: template.type,+ accessPolicy: JSON.stringify(template.accessPolicy),+ settings: JSON.stringify(template.settings)+ });+ }++ return { project, created: true };+};diff --git a/backend/src/ee/services/pam-instance/pam-project-resolver.ts b/backend/src/ee/services/pam-instance/pam-project-resolver.tsnew file mode 100644index 0000000000..2f710cc560--- /dev/null+++ b/backend/src/ee/services/pam-instance/pam-project-resolver.ts@@ -0,0 +1,23 @@+import { BadRequestError } from "@app/lib/errors";+import { TOrgDALFactory } from "@app/services/org/org-dal";++type TResolverDeps = {+ orgDAL: Pick<TOrgDALFactory, "findById">;+};++export type TPamProjectResolverFactory = ReturnType<typeof pamProjectResolverFactory>;++export const pamProjectResolverFactory = ({ orgDAL }: TResolverDeps) => ({+ resolve: async (actorOrgId: string): Promise<string> => {+ const org = await orgDAL.findById(actorOrgId);+ if (!org) {+ throw new BadRequestError({ message: "Organization not found." });+ }+ if (!org.defaultPamProjectId) {+ throw new BadRequestError({+ message: "This organization has no Access Management project. Contact your administrator."+ });+ }+ return org.defaultPamProjectId;+ }+});diff --git a/backend/src/ee/services/pam/pam-enums.ts b/backend/src/ee/services/pam/pam-enums.tsnew file mode 100644index 0000000000..48c303e90e--- /dev/null+++ b/backend/src/ee/services/pam/pam-enums.ts@@ -0,0 +1,24 @@+export enum PamAccountType {+ SSH = "ssh",+ Postgres = "postgres",+ MySQL = "mysql",+ MsSQL = "mssql",+ OracleDB = "oracledb",+ MongoDB = "mongodb",+ Redis = "redis",+ Kubernetes = "kubernetes",+ AwsIam = "aws-iam",+ Windows = "windows",+ ActiveDirectory = "active-directory"+}++export enum PamFolderRole {+ Admin = "admin",+ Connector = "connector",+ Auditor = "auditor"+}++export enum PamProductRole {+ Admin = "admin",+ Member = "member"+}diff --git a/backend/src/ee/services/pam/pam-template-config-schemas.ts b/backend/src/ee/services/pam/pam-template-config-schemas.tsnew file mode 100644index 0000000000..8d693fb07d--- /dev/null+++ b/backend/src/ee/services/pam/pam-template-config-schemas.ts@@ -0,0 +1,36 @@+import { z } from "zod";++import { PamRecordingStorageBackend } from "../pam-session-recording-storage/pam-session-recording-storage-enums";++export const PamPasswordConstraintsSchema = z.object({+ minLength: z.number().int().min(1).max(256),+ maxLength: z.number().int().min(1).max(256),+ requireUppercase: z.boolean(),+ requireLowercase: z.boolean(),+ requireNumbers: z.boolean(),+ requireSymbols: z.boolean()+});++export const PamRecordingS3ConfigSchema = z.object({+ bucket: z.string().min(1),+ region: z.string().min(1),+ keyPrefix: z.string().optional()+});++export const PamTemplateSettingsSchema = z.object({+ recordingEnabled: z.boolean().default(true),+ recordingStorageBackend: z.nativeEnum(PamRecordingStorageBackend).default(PamRecordingStorageBackend.Postgres),+ recordingS3Config: PamRecordingS3ConfigSchema.optional(),+ passwordConstraints: PamPasswordConstraintsSchema.optional(),+ sessionLogMaskingPatterns: z.array(z.string().min(1).max(500)).max(20).optional()+});++export const PamTemplateAccessPolicySchema = z.object({+ maxSessionDurationSeconds: z.number().int().min(60).max(86400),+ requireReason: z.boolean().default(false),+ requireMfa: z.boolean().default(false)+});++export type TPamTemplateSettings = z.infer<typeof PamTemplateSettingsSchema>;+export type TPamTemplateAccessPolicy = z.infer<typeof PamTemplateAccessPolicySchema>;+export type TPamPasswordConstraints = z.infer<typeof PamPasswordConstraintsSchema>;diff --git a/backend/src/ee/services/sub-org/sub-org-service.ts b/backend/src/ee/services/sub-org/sub-org-service.tsindex a973e29ef2..0dc182263b 100644--- a/backend/src/ee/services/sub-org/sub-org-service.ts+++ b/backend/src/ee/services/sub-org/sub-org-service.ts@@ -2,6 +2,7 @@ import { ForbiddenError } from "@casl/ability";import slugify from "@sindresorhus/slugify";import { AccessScope, OrganizationActionScope, OrgMembershipRole, OrgMembershipStatus } from "@app/db/schemas";+import { bootstrapPamProject } from "@app/ee/services/pam-instance/pam-project-bootstrap";import { BadRequestError } from "@app/lib/errors";import { ActorType } from "@app/services/auth/auth-type";import { bootstrapCertManagerProject } from "@app/services/cert-manager-instance/cert-manager-project-bootstrap";@@ -106,6 +107,16 @@ export const subOrgServiceFactory = ({tx);+ await bootstrapPamProject(+ {+ orgId: org.id,+ adminUserIds: permission.type === ActorType.USER ? [permission.id] : [],+ adminIdentityIds: permission.type === ActorType.IDENTITY ? [permission.id] : []+ },+ { projectDAL, membershipDAL, membershipRoleDAL },+ tx+ );+return org;});diff --git a/backend/src/server/plugins/inject-pam-project-id.ts b/backend/src/server/plugins/inject-pam-project-id.tsnew file mode 100644index 0000000000..1e40e7688c--- /dev/null+++ b/backend/src/server/plugins/inject-pam-project-id.ts@@ -0,0 +1,17 @@+import { FastifyPluginAsync } from "fastify";+import fp from "fastify-plugin";++const PAM_PREFIX = "/api/v1/pam/";++export const injectPamProjectId: FastifyPluginAsync = fp(async (server) => {+ server.decorateRequest("internalPamProjectId", "");++ server.addHook("preValidation", async (req) => {+ if (!req.permission?.orgId) return;++ const routePath = req.routeOptions.url ?? "";+ if (!routePath.startsWith(PAM_PREFIX)) return;++ req.internalPamProjectId = await server.services.pamProjectResolver.resolve(req.permission.orgId);+ });+});diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 3f60027115..26fa9f6299 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -112,6 +112,7 @@ import { pamDomainServiceFactory } from "@app/ee/services/pam-domain/pam-domain-import { pamFolderDALFactory } from "@app/ee/services/pam-folder/pam-folder-dal";import { pamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";import { pamInsightsServiceFactory } from "@app/ee/services/pam-insights/pam-insights-service";+import { pamProjectResolverFactory } from "@app/ee/services/pam-instance/pam-project-resolver";import { pamProjectRecordingConfigDALFactory } from "@app/ee/services/pam-project-recording-config/pam-project-recording-config-dal";import { pamProjectRecordingConfigServiceFactory } from "@app/ee/services/pam-project-recording-config/pam-project-recording-config-service";import { pamResourceDALFactory } from "@app/ee/services/pam-resource/pam-resource-dal";@@ -1518,6 +1519,10 @@ export const registerRoutes = async (projectDAL});+ const pamProjectResolver = pamProjectResolverFactory({+ orgDAL+ });+const certManagerInstanceService = certManagerInstanceServiceFactory({db,orgDAL,@@ -3609,6 +3614,7 @@ export const registerRoutes = async (signerPolicy: signerPolicyService,pkiApplicationEnrollment: pkiApplicationEnrollmentService,certManagerProjectResolver,+ pamProjectResolver,certManagerInstance: certManagerInstanceService,certManagerExport: certManagerExportService,certificateAuthorityCrl: certificateAuthorityCrlService,diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.tsindex 8f23cf3c02..28d6d485f4 100644--- a/backend/src/services/org/org-service.ts+++ b/backend/src/services/org/org-service.ts@@ -16,6 +16,7 @@ import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-grouimport { TLdapConfigDALFactory } from "@app/ee/services/ldap-config/ldap-config-dal";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { TOidcConfigDALFactory } from "@app/ee/services/oidc/oidc-config-dal";+import { bootstrapPamProject } from "@app/ee/services/pam-instance/pam-project-bootstrap";import {OrgPermissionActions,OrgPermissionGroupActions,@@ -693,6 +694,15 @@ export const orgServiceFactory = ({tx);+ await bootstrapPamProject(+ {+ orgId: org.id,+ adminUserIds: userId ? [userId] : []+ },+ { projectDAL, membershipDAL, membershipRoleDAL },+ tx+ );+return org;};